diff --git a/.gitignore b/.gitignore index ad46b3088..78472522f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,61 +1,11 @@ -# Logs -logs -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# Runtime data -pids -*.pid -*.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# nyc test coverage -.nyc_output - -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# Bower dependency directory (https://bower.io/) -bower_components - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (https://nodejs.org/api/addons.html) -build/Release - # Dependency directories -node_modules/ -jspm_packages/ - -# TypeScript v1 declaration files -typings/ +node_modules # Optional npm cache directory .npm -# Optional eslint cache -.eslintcache - -# Optional REPL history -.node_repl_history - -# Output of 'npm pack' -*.tgz - -# Yarn Integrity file -.yarn-integrity - -# dotenv environment variables file -.env - -# next.js build output -.next +# Output files +server/out/ +client/out/ +client/server/ +client/*.vsix diff --git a/README.md b/README.md index 29f7ebd64..67b584394 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,16 @@ +# pyright -# Contributing +Static type checker for the Python language + + +## Build Instructions +1. Install [nodejs](https://nodejs.org/en/) +2. Open terminal window in main directory of cloned source +3. Execute "npm install" to download dependencies +4. Execute "npm run build" + + +## Contributing This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us diff --git a/client/out/src/extension.js b/client/out/src/extension.js new file mode 100644 index 000000000..c0a4df633 --- /dev/null +++ b/client/out/src/extension.js @@ -0,0 +1,44 @@ +"use strict"; +/* +* extension.ts +* +* Provides client for Pyright Python language server. This portion runs +* in the context of the VS Code process and talks to the server, which +* runs in another process. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +const path = require("path"); +const vscode_1 = require("vscode"); +const vscode_languageclient_1 = require("vscode-languageclient"); +function activate(context) { + let serverModule = context.asAbsolutePath(path.join('server', 'server.js')); + let debugOptions = { execArgv: ["--nolazy", "--inspect=6600"] }; + // If the extension is launched in debug mode, then the debug server options are used. + // Otherwise the run options are used. + let serverOptions = { + run: { module: serverModule, transport: vscode_languageclient_1.TransportKind.ipc }, + debug: { module: serverModule, transport: vscode_languageclient_1.TransportKind.ipc, options: debugOptions } + }; + // Options to control the language client + let clientOptions = { + // Register the server for plain text documents + documentSelector: [{ + scheme: 'file', + language: 'python' + }], + synchronize: { + // Synchronize the setting section 'languageServerExample' to the server + configurationSection: 'python', + // Notify the server about file changes to '.clientrc files contain in the workspace + fileEvents: vscode_1.workspace.createFileSystemWatcher('**/.clientrc') + } + }; + // Create the language client and start the client. + let languageClient = new vscode_languageclient_1.LanguageClient('python', 'Python', serverOptions, clientOptions); + let disposable = languageClient.start(); + // Push the disposable to the context's subscriptions so that the + // client can be deactivated on extension deactivation. + context.subscriptions.push(disposable); +} +exports.activate = activate; +//# sourceMappingURL=extension.js.map \ No newline at end of file diff --git a/client/out/src/extension.js.map b/client/out/src/extension.js.map new file mode 100644 index 000000000..4aa4b46ff --- /dev/null +++ b/client/out/src/extension.js.map @@ -0,0 +1 @@ +{"version":3,"file":"extension.js","sourceRoot":"","sources":["../../src/extension.ts"],"names":[],"mappings":";AAAA;;;;;;EAME;;AAEF,6BAA6B;AAC7B,mCAAqD;AACrD,iEAA4G;AAE5G,SAAgB,QAAQ,CAAC,OAAyB;IACjD,IAAI,YAAY,GAAG,OAAO,CAAC,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,WAAW,CAAC,CAAC,CAAC;IAC5E,IAAI,YAAY,GAAG,EAAE,QAAQ,EAAE,CAAC,UAAU,EAAE,gBAAgB,CAAC,EAAE,CAAC;IAEhE,sFAAsF;IACtF,sCAAsC;IACtC,IAAI,aAAa,GAAkB;QAClC,GAAG,EAAG,EAAE,MAAM,EAAE,YAAY,EAAE,SAAS,EAAE,qCAAa,CAAC,GAAG,EAAE;QAC5D,KAAK,EAAE,EAAE,MAAM,EAAE,YAAY,EAAE,SAAS,EAAE,qCAAa,CAAC,GAAG,EAAE,OAAO,EAAE,YAAY,EAAE;KACpF,CAAA;IAED,yCAAyC;IACzC,IAAI,aAAa,GAA0B;QAC1C,+CAA+C;QAC/C,gBAAgB,EAAE,CAAC;gBAClB,MAAM,EAAE,MAAM;gBACd,QAAQ,EAAE,QAAQ;aAClB,CAAC;QACF,WAAW,EAAE;YACZ,wEAAwE;YACxE,oBAAoB,EAAE,QAAQ;YAC9B,oFAAoF;YACpF,UAAU,EAAE,kBAAS,CAAC,uBAAuB,CAAC,cAAc,CAAC;SAC7D;KACD,CAAA;IAED,mDAAmD;IACnD,IAAI,cAAc,GAAG,IAAI,sCAAc,CAAC,QAAQ,EAAE,QAAQ,EAAE,aAAa,EAAE,aAAa,CAAC,CAAC;IAC1F,IAAI,UAAU,GAAG,cAAc,CAAC,KAAK,EAAE,CAAC;IAExC,kEAAkE;IAClE,uDAAuD;IACvD,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;AACxC,CAAC;AAjCD,4BAiCC"} \ No newline at end of file diff --git a/client/package-lock.json b/client/package-lock.json new file mode 100644 index 000000000..b207a0b68 --- /dev/null +++ b/client/package-lock.json @@ -0,0 +1,1819 @@ +{ + "name": "pyright", + "version": "0.1.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "ajv": { + "version": "6.10.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.10.0.tgz", + "integrity": "sha512-nffhOpkymDECQyR0mnsUtoCE8RlX38G0rYP+wgLWFyZuUyuuojSSvi/+euOiQBIn63whYwYVIIH1TvE3tu4OEg==", + "dev": true, + "requires": { + "fast-deep-equal": "^2.0.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + } + }, + "ansi-cyan": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/ansi-cyan/-/ansi-cyan-0.1.1.tgz", + "integrity": "sha1-U4rlKK+JgvKK4w2G8vF0VtJgmHM=", + "dev": true, + "requires": { + "ansi-wrap": "0.1.0" + } + }, + "ansi-red": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/ansi-red/-/ansi-red-0.1.1.tgz", + "integrity": "sha1-jGOPnRCAgAo1PJwoyKgcpHBdlGw=", + "dev": true, + "requires": { + "ansi-wrap": "0.1.0" + } + }, + "ansi-wrap": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/ansi-wrap/-/ansi-wrap-0.1.0.tgz", + "integrity": "sha1-qCJQ3bABXponyoLoLqYDu/pF768=", + "dev": true + }, + "append-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/append-buffer/-/append-buffer-1.0.2.tgz", + "integrity": "sha1-2CIM9GYIFSXv6lBhTz3mUU36WPE=", + "dev": true, + "requires": { + "buffer-equal": "^1.0.0" + } + }, + "arr-diff": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-1.1.0.tgz", + "integrity": "sha1-aHwydYFjWI/vfeezb6vklesaOZo=", + "dev": true, + "requires": { + "arr-flatten": "^1.0.1", + "array-slice": "^0.2.3" + } + }, + "arr-flatten": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.1.0.tgz", + "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==", + "dev": true + }, + "arr-union": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-2.1.0.tgz", + "integrity": "sha1-IPnqtexw9cfSFbEHexw5Fh0pLH0=", + "dev": true + }, + "array-differ": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/array-differ/-/array-differ-1.0.0.tgz", + "integrity": "sha1-7/UuN1gknTO+QCuLuOVkuytdQDE=", + "dev": true + }, + "array-slice": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/array-slice/-/array-slice-0.2.3.tgz", + "integrity": "sha1-3Tz7gO15c6dRF82sabC5nshhhvU=", + "dev": true + }, + "array-union": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", + "integrity": "sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk=", + "dev": true, + "requires": { + "array-uniq": "^1.0.1" + } + }, + "array-uniq": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.3.tgz", + "integrity": "sha1-r2rId6Jcx/dOBYiUdThY39sk/bY=", + "dev": true + }, + "arrify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", + "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", + "dev": true + }, + "asn1": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz", + "integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==", + "dev": true, + "requires": { + "safer-buffer": "~2.1.0" + } + }, + "assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", + "dev": true + }, + "asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", + "dev": true + }, + "aws-sign2": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", + "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=", + "dev": true + }, + "aws4": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.8.0.tgz", + "integrity": "sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ==", + "dev": true + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", + "dev": true, + "requires": { + "tweetnacl": "^0.14.3" + } + }, + "block-stream": { + "version": "0.0.9", + "resolved": "https://registry.npmjs.org/block-stream/-/block-stream-0.0.9.tgz", + "integrity": "sha1-E+v+d4oDIFz+A3UUgeu0szAMEmo=", + "dev": true, + "requires": { + "inherits": "~2.0.0" + } + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "browser-stdout": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.0.tgz", + "integrity": "sha1-81HTKWnTL6XXpVZxVCY9korjvR8=", + "dev": true + }, + "buffer-crc32": { + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", + "integrity": "sha1-DTM+PwDqxQqhRUq9MO+MKl2ackI=", + "dev": true + }, + "buffer-equal": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-equal/-/buffer-equal-1.0.0.tgz", + "integrity": "sha1-WWFrSYME1Var1GaWayLu2j7KX74=", + "dev": true + }, + "buffer-from": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", + "dev": true + }, + "caseless": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=", + "dev": true + }, + "clone": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/clone/-/clone-0.2.0.tgz", + "integrity": "sha1-xhJqkK1Pctv1rNskPMN3JP6T/B8=", + "dev": true + }, + "clone-buffer": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/clone-buffer/-/clone-buffer-1.0.0.tgz", + "integrity": "sha1-4+JbIHrE5wGvch4staFnksrD3Fg=", + "dev": true + }, + "clone-stats": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-0.0.1.tgz", + "integrity": "sha1-uI+UqCzzi4eR1YBG6kAprYjKmdE=", + "dev": true + }, + "cloneable-readable": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/cloneable-readable/-/cloneable-readable-1.1.2.tgz", + "integrity": "sha512-Bq6+4t+lbM8vhTs/Bef5c5AdEMtapp/iFb6+s4/Hh9MVTt8OLKH7ZOOZSCT+Ys7hsHvqv0GuMPJ1lnQJVHvxpg==", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "process-nextick-args": "^2.0.0", + "readable-stream": "^2.3.5" + } + }, + "combined-stream": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.7.tgz", + "integrity": "sha512-brWl9y6vOB1xYPZcpZde3N9zDByXTosAeMDo4p1wzo6UMOX4vumB+TP1RZ76sfE6Md68Q0NJSrE/gbezd4Ul+w==", + "dev": true, + "requires": { + "delayed-stream": "~1.0.0" + } + }, + "commander": { + "version": "2.11.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.11.0.tgz", + "integrity": "sha512-b0553uYA5YAEGgyYIGYROzKQ7X5RAqedkfjiZxwi0kL1g3bOaBNNZfYkzt/CL0umgD5wc9Jec2FbB98CjkMRvQ==", + "dev": true + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "convert-source-map": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.6.0.tgz", + "integrity": "sha512-eFu7XigvxdZ1ETfbgPBohgyQ/Z++C0eEhTor0qRwBw9unw+L0/6V8wkSuGgzdThkiS5lSpdptOQPD8Ak40a+7A==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.1" + } + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", + "dev": true + }, + "dashdash": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", + "dev": true, + "requires": { + "assert-plus": "^1.0.0" + } + }, + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-assign": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/deep-assign/-/deep-assign-1.0.0.tgz", + "integrity": "sha1-sJJ0O+hCfcYh6gBnzex+cN0Z83s=", + "dev": true, + "requires": { + "is-obj": "^1.0.0" + } + }, + "define-properties": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", + "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", + "dev": true, + "requires": { + "object-keys": "^1.0.12" + } + }, + "delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", + "dev": true + }, + "diff": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/diff/-/diff-3.3.1.tgz", + "integrity": "sha512-MKPHZDMB0o6yHyDryUOScqZibp914ksXwAMYMTHj6KO8UeKsRYNJD3oNCKjTqZon+V488P7N/HzXF8t7ZR95ww==", + "dev": true + }, + "duplexer": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.1.tgz", + "integrity": "sha1-rOb/gIwc5mtX0ev5eXessCM0z8E=", + "dev": true + }, + "duplexify": { + "version": "3.7.1", + "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-3.7.1.tgz", + "integrity": "sha512-07z8uv2wMyS51kKhD1KsdXJg5WQ6t93RneqRxUHnskXVtlYYkLqM0gqStQZ3pj073g687jPCHrqNfCzawLYh5g==", + "dev": true, + "requires": { + "end-of-stream": "^1.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.0.0", + "stream-shift": "^1.0.0" + } + }, + "ecc-jsbn": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", + "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", + "dev": true, + "requires": { + "jsbn": "~0.1.0", + "safer-buffer": "^2.1.0" + } + }, + "end-of-stream": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.1.tgz", + "integrity": "sha512-1MkrZNvWTKCaigbn+W15elq2BB/L22nqrSY5DKlo3X6+vclJm8Bb5djXJBmEX6fS3+zCh/F4VBK5Z2KxJt4s2Q==", + "dev": true, + "requires": { + "once": "^1.4.0" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "event-stream": { + "version": "3.3.4", + "resolved": "https://registry.npmjs.org/event-stream/-/event-stream-3.3.4.tgz", + "integrity": "sha1-SrTJoPWlTbkzi0w02Gv86PSzVXE=", + "dev": true, + "requires": { + "duplexer": "~0.1.1", + "from": "~0", + "map-stream": "~0.1.0", + "pause-stream": "0.0.11", + "split": "0.3", + "stream-combiner": "~0.0.4", + "through": "~2.3.1" + } + }, + "extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "dev": true + }, + "extend-shallow": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-1.1.4.tgz", + "integrity": "sha1-Gda/lN/AnXa6cR85uHLSH/TdkHE=", + "dev": true, + "requires": { + "kind-of": "^1.1.0" + } + }, + "extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=", + "dev": true + }, + "fast-deep-equal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", + "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=", + "dev": true + }, + "fast-json-stable-stringify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", + "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=", + "dev": true + }, + "fd-slicer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz", + "integrity": "sha1-JcfInLH5B3+IkbvmHY85Dq4lbx4=", + "dev": true, + "requires": { + "pend": "~1.2.0" + } + }, + "flush-write-stream": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/flush-write-stream/-/flush-write-stream-1.1.1.tgz", + "integrity": "sha512-3Z4XhFZ3992uIq0XOqb9AreonueSYphE6oYbpt5+3u06JWklbsPkNv3ZKkP9Bz/r+1MWCaMoSQ28P85+1Yc77w==", + "dev": true, + "requires": { + "inherits": "^2.0.3", + "readable-stream": "^2.3.6" + } + }, + "forever-agent": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", + "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=", + "dev": true + }, + "form-data": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", + "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", + "dev": true, + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.6", + "mime-types": "^2.1.12" + } + }, + "from": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/from/-/from-0.1.7.tgz", + "integrity": "sha1-g8YK/Fi5xWmXAH7Rp2izqzA6RP4=", + "dev": true + }, + "fs-mkdirp-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-mkdirp-stream/-/fs-mkdirp-stream-1.0.0.tgz", + "integrity": "sha1-C3gV/DIBxqaeFNuYzgmMFpNSWes=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.11", + "through2": "^2.0.3" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "fstream": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.11.tgz", + "integrity": "sha1-XB+x8RdHcRTwYyoOtLcbPLD9MXE=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "inherits": "~2.0.0", + "mkdirp": ">=0.5 0", + "rimraf": "2" + } + }, + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true + }, + "getpass": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", + "dev": true, + "requires": { + "assert-plus": "^1.0.0" + } + }, + "glob": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz", + "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "glob-parent": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-3.1.0.tgz", + "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", + "dev": true, + "requires": { + "is-glob": "^3.1.0", + "path-dirname": "^1.0.0" + } + }, + "glob-stream": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/glob-stream/-/glob-stream-6.1.0.tgz", + "integrity": "sha1-cEXJlBOz65SIjYOrRtC0BMx73eQ=", + "dev": true, + "requires": { + "extend": "^3.0.0", + "glob": "^7.1.1", + "glob-parent": "^3.1.0", + "is-negated-glob": "^1.0.0", + "ordered-read-streams": "^1.0.0", + "pumpify": "^1.3.5", + "readable-stream": "^2.1.5", + "remove-trailing-separator": "^1.0.1", + "to-absolute-glob": "^2.0.0", + "unique-stream": "^2.0.2" + } + }, + "graceful-fs": { + "version": "4.1.15", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", + "integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==", + "dev": true + }, + "growl": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/growl/-/growl-1.10.3.tgz", + "integrity": "sha512-hKlsbA5Vu3xsh1Cg3J7jSmX/WaW6A5oBeqzM88oNbCRQFz+zUaXm6yxS4RVytp1scBoJzSYl4YAEOQIt6O8V1Q==", + "dev": true + }, + "gulp-chmod": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/gulp-chmod/-/gulp-chmod-2.0.0.tgz", + "integrity": "sha1-AMOQuSigeZslGsz2MaoJ4BzGKZw=", + "dev": true, + "requires": { + "deep-assign": "^1.0.0", + "stat-mode": "^0.2.0", + "through2": "^2.0.0" + } + }, + "gulp-filter": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/gulp-filter/-/gulp-filter-5.1.0.tgz", + "integrity": "sha1-oF4Rr/sHz33PQafeHLe2OsN4PnM=", + "dev": true, + "requires": { + "multimatch": "^2.0.0", + "plugin-error": "^0.1.2", + "streamfilter": "^1.0.5" + } + }, + "gulp-gunzip": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/gulp-gunzip/-/gulp-gunzip-1.0.0.tgz", + "integrity": "sha1-FbdBFF6Dqcb1CIYkG1fMWHHxUak=", + "dev": true, + "requires": { + "through2": "~0.6.5", + "vinyl": "~0.4.6" + }, + "dependencies": { + "isarray": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=", + "dev": true + }, + "readable-stream": { + "version": "1.0.34", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.34.tgz", + "integrity": "sha1-Elgg40vIQtLyqq+v5MKRbuMsFXw=", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "string_decoder": { + "version": "0.10.31", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=", + "dev": true + }, + "through2": { + "version": "0.6.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-0.6.5.tgz", + "integrity": "sha1-QaucZ7KdVyCQcUEOHXp6lozTrUg=", + "dev": true, + "requires": { + "readable-stream": ">=1.0.33-1 <1.1.0-0", + "xtend": ">=4.0.0 <4.1.0-0" + } + } + } + }, + "gulp-remote-src-vscode": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/gulp-remote-src-vscode/-/gulp-remote-src-vscode-0.5.1.tgz", + "integrity": "sha512-mw4OGjtC/jlCWJFhbcAlel4YPvccChlpsl3JceNiB/DLJi24/UPxXt53/N26lgI3dknEqd4ErfdHrO8sJ5bATQ==", + "dev": true, + "requires": { + "event-stream": "3.3.4", + "node.extend": "^1.1.2", + "request": "^2.79.0", + "through2": "^2.0.3", + "vinyl": "^2.0.1" + }, + "dependencies": { + "clone": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", + "integrity": "sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18=", + "dev": true + }, + "clone-stats": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-1.0.0.tgz", + "integrity": "sha1-s3gt/4u1R04Yuba/D9/ngvh3doA=", + "dev": true + }, + "vinyl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-2.2.0.tgz", + "integrity": "sha512-MBH+yP0kC/GQ5GwBqrTPTzEfiiLjta7hTtvQtbxBgTeSXsmKQRQecjibMbxIXzVT3Y9KJK+drOz1/k+vsu8Nkg==", + "dev": true, + "requires": { + "clone": "^2.1.1", + "clone-buffer": "^1.0.0", + "clone-stats": "^1.0.0", + "cloneable-readable": "^1.0.0", + "remove-trailing-separator": "^1.0.1", + "replace-ext": "^1.0.0" + } + } + } + }, + "gulp-untar": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/gulp-untar/-/gulp-untar-0.0.7.tgz", + "integrity": "sha512-0QfbCH2a1k2qkTLWPqTX+QO4qNsHn3kC546YhAP3/n0h+nvtyGITDuDrYBMDZeW4WnFijmkOvBWa5HshTic1tw==", + "dev": true, + "requires": { + "event-stream": "~3.3.4", + "streamifier": "~0.1.1", + "tar": "^2.2.1", + "through2": "~2.0.3", + "vinyl": "^1.2.0" + }, + "dependencies": { + "clone": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "integrity": "sha1-2jCcwmPfFZlMaIypAheco8fNfH4=", + "dev": true + }, + "replace-ext": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/replace-ext/-/replace-ext-0.0.1.tgz", + "integrity": "sha1-KbvZIHinOfC8zitO5B6DeVNSKSQ=", + "dev": true + }, + "vinyl": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-1.2.0.tgz", + "integrity": "sha1-XIgDbPVl5d8FVYv8kR+GVt8hiIQ=", + "dev": true, + "requires": { + "clone": "^1.0.0", + "clone-stats": "^0.0.1", + "replace-ext": "0.0.1" + } + } + } + }, + "gulp-vinyl-zip": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/gulp-vinyl-zip/-/gulp-vinyl-zip-2.1.2.tgz", + "integrity": "sha512-wJn09jsb8PyvUeyFF7y7ImEJqJwYy40BqL9GKfJs6UGpaGW9A+N68Q+ajsIpb9AeR6lAdjMbIdDPclIGo1/b7Q==", + "dev": true, + "requires": { + "event-stream": "3.3.4", + "queue": "^4.2.1", + "through2": "^2.0.3", + "vinyl": "^2.0.2", + "vinyl-fs": "^3.0.3", + "yauzl": "^2.2.1", + "yazl": "^2.2.1" + }, + "dependencies": { + "clone": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", + "integrity": "sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18=", + "dev": true + }, + "clone-stats": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-1.0.0.tgz", + "integrity": "sha1-s3gt/4u1R04Yuba/D9/ngvh3doA=", + "dev": true + }, + "vinyl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-2.2.0.tgz", + "integrity": "sha512-MBH+yP0kC/GQ5GwBqrTPTzEfiiLjta7hTtvQtbxBgTeSXsmKQRQecjibMbxIXzVT3Y9KJK+drOz1/k+vsu8Nkg==", + "dev": true, + "requires": { + "clone": "^2.1.1", + "clone-buffer": "^1.0.0", + "clone-stats": "^1.0.0", + "cloneable-readable": "^1.0.0", + "remove-trailing-separator": "^1.0.1", + "replace-ext": "^1.0.0" + } + } + } + }, + "har-schema": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", + "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=", + "dev": true + }, + "har-validator": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.3.tgz", + "integrity": "sha512-sNvOCzEQNr/qrvJgc3UG/kD4QtlHycrzwS+6mfTrrSq97BvaYcPZZI1ZSqGSPR73Cxn4LKTD4PttRwfU7jWq5g==", + "dev": true, + "requires": { + "ajv": "^6.5.5", + "har-schema": "^2.0.0" + } + }, + "has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1" + } + }, + "has-flag": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-2.0.0.tgz", + "integrity": "sha1-6CB68cx7MNRGzHC3NLXovhj4jVE=", + "dev": true + }, + "has-symbols": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.0.tgz", + "integrity": "sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q=", + "dev": true + }, + "he": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/he/-/he-1.1.1.tgz", + "integrity": "sha1-k0EP0hsAlzUVH4howvJx80J+I/0=", + "dev": true + }, + "http-signature": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", + "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", + "dev": true, + "requires": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + } + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "is": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/is/-/is-3.3.0.tgz", + "integrity": "sha512-nW24QBoPcFGGHJGUwnfpI7Yc5CdqWNdsyHQszVE/z2pKHXzh7FZ5GWhJqSyaQ9wMkQnsTx+kAI8bHlCX4tKdbg==", + "dev": true + }, + "is-absolute": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-absolute/-/is-absolute-1.0.0.tgz", + "integrity": "sha512-dOWoqflvcydARa360Gvv18DZ/gRuHKi2NU/wU5X1ZFzdYfH29nkiNZsF3mp4OJ3H4yo9Mx8A/uAGNzpzPN3yBA==", + "dev": true, + "requires": { + "is-relative": "^1.0.0", + "is-windows": "^1.0.1" + } + }, + "is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", + "dev": true + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "dev": true + }, + "is-glob": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", + "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", + "dev": true, + "requires": { + "is-extglob": "^2.1.0" + } + }, + "is-negated-glob": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-negated-glob/-/is-negated-glob-1.0.0.tgz", + "integrity": "sha1-aRC8pdqMleeEtXUbl2z1oQ/uNtI=", + "dev": true + }, + "is-obj": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-obj/-/is-obj-1.0.1.tgz", + "integrity": "sha1-PkcprB9f3gJc19g6iW2rn09n2w8=", + "dev": true + }, + "is-relative": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-relative/-/is-relative-1.0.0.tgz", + "integrity": "sha512-Kw/ReK0iqwKeu0MITLFuj0jbPAmEiOsIwyIXvvbfa6QfmN9pkD1M+8pdk7Rl/dTKbH34/XBFMbgD4iMJhLQbGA==", + "dev": true, + "requires": { + "is-unc-path": "^1.0.0" + } + }, + "is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", + "dev": true + }, + "is-unc-path": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-unc-path/-/is-unc-path-1.0.0.tgz", + "integrity": "sha512-mrGpVd0fs7WWLfVsStvgF6iEJnbjDFZh9/emhRDcGWTduTfNHd9CHeUwH3gYIjdbwo4On6hunkztwOaAw0yllQ==", + "dev": true, + "requires": { + "unc-path-regex": "^0.1.2" + } + }, + "is-utf8": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-utf8/-/is-utf8-0.2.1.tgz", + "integrity": "sha1-Sw2hRCEE0bM2NA6AeX6GXPOffXI=", + "dev": true + }, + "is-valid-glob": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-valid-glob/-/is-valid-glob-1.0.0.tgz", + "integrity": "sha1-Kb8+/3Ab4tTTFdusw5vDn+j2Aao=", + "dev": true + }, + "is-windows": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", + "dev": true + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true + }, + "jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", + "dev": true + }, + "json-schema": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", + "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=", + "dev": true + }, + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, + "json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE=", + "dev": true + }, + "json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=", + "dev": true + }, + "jsprim": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", + "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", + "dev": true, + "requires": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.2.3", + "verror": "1.10.0" + } + }, + "kind-of": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-1.1.0.tgz", + "integrity": "sha1-FAo9LUGjbS78+pN3tiwk+ElaXEQ=", + "dev": true + }, + "lazystream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/lazystream/-/lazystream-1.0.0.tgz", + "integrity": "sha1-9plf4PggOS9hOWvolGJAe7dxaOQ=", + "dev": true, + "requires": { + "readable-stream": "^2.0.5" + } + }, + "lead": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/lead/-/lead-1.0.0.tgz", + "integrity": "sha1-bxT5mje+Op3XhPVJVpDlkDRm7kI=", + "dev": true, + "requires": { + "flush-write-stream": "^1.0.2" + } + }, + "map-stream": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/map-stream/-/map-stream-0.1.0.tgz", + "integrity": "sha1-5WqpTEyAVaFkBKBnS3jyFffI4ZQ=", + "dev": true + }, + "mime-db": { + "version": "1.38.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.38.0.tgz", + "integrity": "sha512-bqVioMFFzc2awcdJZIzR3HjZFX20QhilVS7hytkKrv7xFAn8bM1gzc/FOX2awLISvWe0PV8ptFKcon+wZ5qYkg==", + "dev": true + }, + "mime-types": { + "version": "2.1.22", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.22.tgz", + "integrity": "sha512-aGl6TZGnhm/li6F7yx82bJiBZwgiEa4Hf6CNr8YO+r5UHr53tSTYZb102zyU50DOWWKeOv0uQLRL0/9EiKWCog==", + "dev": true, + "requires": { + "mime-db": "~1.38.0" + } + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "dev": true + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "dev": true, + "requires": { + "minimist": "0.0.8" + } + }, + "mocha": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-4.1.0.tgz", + "integrity": "sha512-0RVnjg1HJsXY2YFDoTNzcc1NKhYuXKRrBAG2gDygmJJA136Cs2QlRliZG1mA0ap7cuaT30mw16luAeln+4RiNA==", + "dev": true, + "requires": { + "browser-stdout": "1.3.0", + "commander": "2.11.0", + "debug": "3.1.0", + "diff": "3.3.1", + "escape-string-regexp": "1.0.5", + "glob": "7.1.2", + "growl": "1.10.3", + "he": "1.1.1", + "mkdirp": "0.5.1", + "supports-color": "4.4.0" + }, + "dependencies": { + "glob": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.2.tgz", + "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + } + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + }, + "multimatch": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/multimatch/-/multimatch-2.1.0.tgz", + "integrity": "sha1-nHkGoi+0wCkZ4vX3UWG0zb1LKis=", + "dev": true, + "requires": { + "array-differ": "^1.0.0", + "array-union": "^1.0.1", + "arrify": "^1.0.0", + "minimatch": "^3.0.0" + } + }, + "node.extend": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/node.extend/-/node.extend-1.1.8.tgz", + "integrity": "sha512-L/dvEBwyg3UowwqOUTyDsGBU6kjBQOpOhshio9V3i3BMPv5YUb9+mWNN8MK0IbWqT0AqaTSONZf0aTuMMahWgA==", + "dev": true, + "requires": { + "has": "^1.0.3", + "is": "^3.2.1" + } + }, + "normalize-path": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", + "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", + "dev": true, + "requires": { + "remove-trailing-separator": "^1.0.1" + } + }, + "now-and-later": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/now-and-later/-/now-and-later-2.0.0.tgz", + "integrity": "sha1-vGHLtFbXnLMiB85HygUTb/Ln1u4=", + "dev": true, + "requires": { + "once": "^1.3.2" + } + }, + "oauth-sign": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", + "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", + "dev": true + }, + "object-keys": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.0.tgz", + "integrity": "sha512-6OO5X1+2tYkNyNEx6TsCxEqFfRWaqx6EtMiSbGrw8Ob8v9Ne+Hl8rBAgLBZn5wjEz3s/s6U1WXFUFOcxxAwUpg==", + "dev": true + }, + "object.assign": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.0.tgz", + "integrity": "sha512-exHJeq6kBKj58mqGyTQ9DFvrZC/eR6OwxzoM9YRoGBqrXYonaFyGiFMuc9VZrXf7DarreEwMpurG3dd+CNyW5w==", + "dev": true, + "requires": { + "define-properties": "^1.1.2", + "function-bind": "^1.1.1", + "has-symbols": "^1.0.0", + "object-keys": "^1.0.11" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "ordered-read-streams": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ordered-read-streams/-/ordered-read-streams-1.0.1.tgz", + "integrity": "sha1-d8DLN8QVJdZBZtmQ/61+xqDhNj4=", + "dev": true, + "requires": { + "readable-stream": "^2.0.1" + } + }, + "path-dirname": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/path-dirname/-/path-dirname-1.0.2.tgz", + "integrity": "sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA=", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "pause-stream": { + "version": "0.0.11", + "resolved": "https://registry.npmjs.org/pause-stream/-/pause-stream-0.0.11.tgz", + "integrity": "sha1-/lo0sMvOErWqaitAPuLnO2AvFEU=", + "dev": true, + "requires": { + "through": "~2.3" + } + }, + "pend": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", + "integrity": "sha1-elfrVQpng/kRUzH89GY9XI4AelA=", + "dev": true + }, + "performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=", + "dev": true + }, + "plugin-error": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/plugin-error/-/plugin-error-0.1.2.tgz", + "integrity": "sha1-O5uzM1zPAPQl4HQ34ZJ2ln2kes4=", + "dev": true, + "requires": { + "ansi-cyan": "^0.1.1", + "ansi-red": "^0.1.1", + "arr-diff": "^1.0.1", + "arr-union": "^2.0.1", + "extend-shallow": "^1.1.2" + } + }, + "process-nextick-args": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", + "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==", + "dev": true + }, + "psl": { + "version": "1.1.31", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.1.31.tgz", + "integrity": "sha512-/6pt4+C+T+wZUieKR620OpzN/LlnNKuWjy1iFLQ/UG35JqHlR/89MP1d96dUfkf6Dne3TuLQzOYEYshJ+Hx8mw==", + "dev": true + }, + "pump": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pump/-/pump-2.0.1.tgz", + "integrity": "sha512-ruPMNRkN3MHP1cWJc9OWr+T/xDP0jhXYCLfJcBuX54hhfIBnaQmAUMfDcG4DM5UMWByBbJY69QSphm3jtDKIkA==", + "dev": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "pumpify": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/pumpify/-/pumpify-1.5.1.tgz", + "integrity": "sha512-oClZI37HvuUJJxSKKrC17bZ9Cu0ZYhEAGPsPUy9KlMUmv9dKX2o77RUmq7f3XjIxbwyGwYzbzQ1L2Ks8sIradQ==", + "dev": true, + "requires": { + "duplexify": "^3.6.0", + "inherits": "^2.0.3", + "pump": "^2.0.0" + } + }, + "punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "dev": true + }, + "qs": { + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", + "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==", + "dev": true + }, + "querystringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.1.0.tgz", + "integrity": "sha512-sluvZZ1YiTLD5jsqZcDmFyV2EwToyXZBfpoVOmktMmW+VEnhgakFHnasVph65fOjGPTWN0Nw3+XQaSeMayr0kg==", + "dev": true + }, + "queue": { + "version": "4.5.1", + "resolved": "https://registry.npmjs.org/queue/-/queue-4.5.1.tgz", + "integrity": "sha512-AMD7w5hRXcFSb8s9u38acBZ+309u6GsiibP4/0YacJeaurRshogB7v/ZcVPxP5gD5+zIw6ixRHdutiYUJfwKHw==", + "dev": true, + "requires": { + "inherits": "~2.0.0" + } + }, + "readable-stream": { + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "remove-bom-buffer": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/remove-bom-buffer/-/remove-bom-buffer-3.0.0.tgz", + "integrity": "sha512-8v2rWhaakv18qcvNeli2mZ/TMTL2nEyAKRvzo1WtnZBl15SHyEhrCu2/xKlJyUFKHiHgfXIyuY6g2dObJJycXQ==", + "dev": true, + "requires": { + "is-buffer": "^1.1.5", + "is-utf8": "^0.2.1" + } + }, + "remove-bom-stream": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/remove-bom-stream/-/remove-bom-stream-1.2.0.tgz", + "integrity": "sha1-BfGlk/FuQuH7kOv1nejlaVJflSM=", + "dev": true, + "requires": { + "remove-bom-buffer": "^3.0.0", + "safe-buffer": "^5.1.0", + "through2": "^2.0.3" + } + }, + "remove-trailing-separator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz", + "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=", + "dev": true + }, + "replace-ext": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/replace-ext/-/replace-ext-1.0.0.tgz", + "integrity": "sha1-3mMSg3P8v3w8z6TeWkgMRaZ5WOs=", + "dev": true + }, + "request": { + "version": "2.88.0", + "resolved": "https://registry.npmjs.org/request/-/request-2.88.0.tgz", + "integrity": "sha512-NAqBSrijGLZdM0WZNsInLJpkJokL72XYjUpnB0iwsRgxh7dB6COrHnTBNwN0E+lHDAJzu7kLAkDeY08z2/A0hg==", + "dev": true, + "requires": { + "aws-sign2": "~0.7.0", + "aws4": "^1.8.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.6", + "extend": "~3.0.2", + "forever-agent": "~0.6.1", + "form-data": "~2.3.2", + "har-validator": "~5.1.0", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.19", + "oauth-sign": "~0.9.0", + "performance-now": "^2.1.0", + "qs": "~6.5.2", + "safe-buffer": "^5.1.2", + "tough-cookie": "~2.4.3", + "tunnel-agent": "^0.6.0", + "uuid": "^3.3.2" + } + }, + "requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8=", + "dev": true + }, + "resolve-options": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/resolve-options/-/resolve-options-1.1.0.tgz", + "integrity": "sha1-MrueOcBtZzONyTeMDW1gdFZq0TE=", + "dev": true, + "requires": { + "value-or-function": "^3.0.0" + } + }, + "rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true + }, + "semver": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.6.0.tgz", + "integrity": "sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg==" + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + }, + "source-map-support": { + "version": "0.5.10", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.10.tgz", + "integrity": "sha512-YfQ3tQFTK/yzlGJuX8pTwa4tifQj4QS2Mj7UegOu8jAz59MqIiMGPXxQhVQiIMNzayuUSF/jEuVnfFF5JqybmQ==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "split": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/split/-/split-0.3.3.tgz", + "integrity": "sha1-zQ7qXmOiEd//frDwkcQTPi0N0o8=", + "dev": true, + "requires": { + "through": "2" + } + }, + "sshpk": { + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz", + "integrity": "sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==", + "dev": true, + "requires": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + } + }, + "stat-mode": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/stat-mode/-/stat-mode-0.2.2.tgz", + "integrity": "sha1-5sgLYjEj19gM8TLOU480YokHJQI=", + "dev": true + }, + "stream-combiner": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/stream-combiner/-/stream-combiner-0.0.4.tgz", + "integrity": "sha1-TV5DPBhSYd3mI8o/RMWGvPXErRQ=", + "dev": true, + "requires": { + "duplexer": "~0.1.1" + } + }, + "stream-shift": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.0.tgz", + "integrity": "sha1-1cdSgl5TZ+eG944Y5EXqIjoVWVI=", + "dev": true + }, + "streamfilter": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/streamfilter/-/streamfilter-1.0.7.tgz", + "integrity": "sha512-Gk6KZM+yNA1JpW0KzlZIhjo3EaBJDkYfXtYSbOwNIQ7Zd6006E6+sCFlW1NDvFG/vnXhKmw6TJJgiEQg/8lXfQ==", + "dev": true, + "requires": { + "readable-stream": "^2.0.2" + } + }, + "streamifier": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/streamifier/-/streamifier-0.1.1.tgz", + "integrity": "sha1-l+mNj6TRBdYqJpHR3AfoINuN/E8=", + "dev": true + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "supports-color": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-4.4.0.tgz", + "integrity": "sha512-rKC3+DyXWgK0ZLKwmRsrkyHVZAjNkfzeehuFWdGGcqGDTZFH73+RH6S/RDAAxl9GusSjZSUWYLmT9N5pzXFOXQ==", + "dev": true, + "requires": { + "has-flag": "^2.0.0" + } + }, + "tar": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/tar/-/tar-2.2.1.tgz", + "integrity": "sha1-jk0qJWwOIYXGsYrWlK7JaLg8sdE=", + "dev": true, + "requires": { + "block-stream": "*", + "fstream": "^1.0.2", + "inherits": "2" + } + }, + "through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU=", + "dev": true + }, + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "dev": true, + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "through2-filter": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/through2-filter/-/through2-filter-3.0.0.tgz", + "integrity": "sha512-jaRjI2WxN3W1V8/FMZ9HKIBXixtiqs3SQSX4/YGIiP3gL6djW48VoZq9tDqeCWs3MT8YY5wb/zli8VW8snY1CA==", + "dev": true, + "requires": { + "through2": "~2.0.0", + "xtend": "~4.0.0" + } + }, + "to-absolute-glob": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/to-absolute-glob/-/to-absolute-glob-2.0.2.tgz", + "integrity": "sha1-GGX0PZ50sIItufFFt4z/fQ98hJs=", + "dev": true, + "requires": { + "is-absolute": "^1.0.0", + "is-negated-glob": "^1.0.0" + } + }, + "to-through": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-through/-/to-through-2.0.0.tgz", + "integrity": "sha1-/JKtq6ByZHvAtn1rA2ZKoZUJOvY=", + "dev": true, + "requires": { + "through2": "^2.0.3" + } + }, + "tough-cookie": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.4.3.tgz", + "integrity": "sha512-Q5srk/4vDM54WJsJio3XNn6K2sCG+CQ8G5Wz6bZhRZoAe/+TxjWB/GlFAnYEbkYVlON9FMk/fE3h2RLpPXo4lQ==", + "dev": true, + "requires": { + "psl": "^1.1.24", + "punycode": "^1.4.1" + }, + "dependencies": { + "punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=", + "dev": true + } + } + }, + "tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "dev": true, + "requires": { + "safe-buffer": "^5.0.1" + } + }, + "tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=", + "dev": true + }, + "typescript": { + "version": "3.3.3333", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.3.3333.tgz", + "integrity": "sha512-JjSKsAfuHBE/fB2oZ8NxtRTk5iGcg6hkYXMnZ3Wc+b2RSqejEqTaem11mHASMnFilHrax3sLK0GDzcJrekZYLw==", + "dev": true + }, + "unc-path-regex": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/unc-path-regex/-/unc-path-regex-0.1.2.tgz", + "integrity": "sha1-5z3T17DXxe2G+6xrCufYxqadUPo=", + "dev": true + }, + "unique-stream": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/unique-stream/-/unique-stream-2.3.1.tgz", + "integrity": "sha512-2nY4TnBE70yoxHkDli7DMazpWiP7xMdCYqU2nBRO0UB+ZpEkGsSija7MvmvnZFUeC+mrgiUfcHSr3LmRFIg4+A==", + "dev": true, + "requires": { + "json-stable-stringify-without-jsonify": "^1.0.1", + "through2-filter": "^3.0.0" + } + }, + "uri-js": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz", + "integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==", + "dev": true, + "requires": { + "punycode": "^2.1.0" + } + }, + "url-parse": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.4.4.tgz", + "integrity": "sha512-/92DTTorg4JjktLNLe6GPS2/RvAd/RGr6LuktmWSMLEOa6rjnlrFXNgSbSmkNvCoL2T028A0a1JaJLzRMlFoHg==", + "dev": true, + "requires": { + "querystringify": "^2.0.0", + "requires-port": "^1.0.0" + } + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", + "dev": true + }, + "uuid": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", + "integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==", + "dev": true + }, + "value-or-function": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/value-or-function/-/value-or-function-3.0.0.tgz", + "integrity": "sha1-HCQ6ULWVwb5Up1S/7OhWO5/42BM=", + "dev": true + }, + "verror": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", + "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", + "dev": true, + "requires": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } + }, + "vinyl": { + "version": "0.4.6", + "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-0.4.6.tgz", + "integrity": "sha1-LzVsh6VQolVGHza76ypbqL94SEc=", + "dev": true, + "requires": { + "clone": "^0.2.0", + "clone-stats": "^0.0.1" + } + }, + "vinyl-fs": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/vinyl-fs/-/vinyl-fs-3.0.3.tgz", + "integrity": "sha512-vIu34EkyNyJxmP0jscNzWBSygh7VWhqun6RmqVfXePrOwi9lhvRs//dOaGOTRUQr4tx7/zd26Tk5WeSVZitgng==", + "dev": true, + "requires": { + "fs-mkdirp-stream": "^1.0.0", + "glob-stream": "^6.1.0", + "graceful-fs": "^4.0.0", + "is-valid-glob": "^1.0.0", + "lazystream": "^1.0.0", + "lead": "^1.0.0", + "object.assign": "^4.0.4", + "pumpify": "^1.3.5", + "readable-stream": "^2.3.3", + "remove-bom-buffer": "^3.0.0", + "remove-bom-stream": "^1.2.0", + "resolve-options": "^1.1.0", + "through2": "^2.0.0", + "to-through": "^2.0.0", + "value-or-function": "^3.0.0", + "vinyl": "^2.0.0", + "vinyl-sourcemap": "^1.1.0" + }, + "dependencies": { + "clone": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", + "integrity": "sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18=", + "dev": true + }, + "clone-stats": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-1.0.0.tgz", + "integrity": "sha1-s3gt/4u1R04Yuba/D9/ngvh3doA=", + "dev": true + }, + "vinyl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-2.2.0.tgz", + "integrity": "sha512-MBH+yP0kC/GQ5GwBqrTPTzEfiiLjta7hTtvQtbxBgTeSXsmKQRQecjibMbxIXzVT3Y9KJK+drOz1/k+vsu8Nkg==", + "dev": true, + "requires": { + "clone": "^2.1.1", + "clone-buffer": "^1.0.0", + "clone-stats": "^1.0.0", + "cloneable-readable": "^1.0.0", + "remove-trailing-separator": "^1.0.1", + "replace-ext": "^1.0.0" + } + } + } + }, + "vinyl-source-stream": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vinyl-source-stream/-/vinyl-source-stream-1.1.2.tgz", + "integrity": "sha1-YrU6E1YQqJbpjKlr7jqH8Aio54A=", + "dev": true, + "requires": { + "through2": "^2.0.3", + "vinyl": "^0.4.3" + } + }, + "vinyl-sourcemap": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/vinyl-sourcemap/-/vinyl-sourcemap-1.1.0.tgz", + "integrity": "sha1-kqgAWTo4cDqM2xHYswCtS+Y7PhY=", + "dev": true, + "requires": { + "append-buffer": "^1.0.2", + "convert-source-map": "^1.5.0", + "graceful-fs": "^4.1.6", + "normalize-path": "^2.1.1", + "now-and-later": "^2.0.0", + "remove-bom-buffer": "^3.0.0", + "vinyl": "^2.0.0" + }, + "dependencies": { + "clone": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz", + "integrity": "sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18=", + "dev": true + }, + "clone-stats": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/clone-stats/-/clone-stats-1.0.0.tgz", + "integrity": "sha1-s3gt/4u1R04Yuba/D9/ngvh3doA=", + "dev": true + }, + "vinyl": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/vinyl/-/vinyl-2.2.0.tgz", + "integrity": "sha512-MBH+yP0kC/GQ5GwBqrTPTzEfiiLjta7hTtvQtbxBgTeSXsmKQRQecjibMbxIXzVT3Y9KJK+drOz1/k+vsu8Nkg==", + "dev": true, + "requires": { + "clone": "^2.1.1", + "clone-buffer": "^1.0.0", + "clone-stats": "^1.0.0", + "cloneable-readable": "^1.0.0", + "remove-trailing-separator": "^1.0.1", + "replace-ext": "^1.0.0" + } + } + } + }, + "vscode": { + "version": "1.1.30", + "resolved": "https://registry.npmjs.org/vscode/-/vscode-1.1.30.tgz", + "integrity": "sha512-YDj5w0TGOcS8XLIdekT4q6LlLV6hv1ZvuT2aGT3KJll4gMz6dUPDgo2VVAf0i0E8igbbZthwvmaUGRwW9yPIaw==", + "dev": true, + "requires": { + "glob": "^7.1.2", + "gulp-chmod": "^2.0.0", + "gulp-filter": "^5.0.1", + "gulp-gunzip": "1.0.0", + "gulp-remote-src-vscode": "^0.5.1", + "gulp-untar": "^0.0.7", + "gulp-vinyl-zip": "^2.1.2", + "mocha": "^4.0.1", + "request": "^2.88.0", + "semver": "^5.4.1", + "source-map-support": "^0.5.0", + "url-parse": "^1.4.3", + "vinyl-fs": "^3.0.3", + "vinyl-source-stream": "^1.1.0" + } + }, + "vscode-jsonrpc": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-4.0.0.tgz", + "integrity": "sha512-perEnXQdQOJMTDFNv+UF3h1Y0z4iSiaN9jIlb0OqIYgosPCZGYh/MCUlkFtV2668PL69lRDO32hmvL2yiidUYg==" + }, + "vscode-languageclient": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-5.2.1.tgz", + "integrity": "sha512-7jrS/9WnV0ruqPamN1nE7qCxn0phkH5LjSgSp9h6qoJGoeAKzwKz/PF6M+iGA/aklx4GLZg1prddhEPQtuXI1Q==", + "requires": { + "semver": "^5.5.0", + "vscode-languageserver-protocol": "3.14.1" + } + }, + "vscode-languageserver-protocol": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.14.1.tgz", + "integrity": "sha512-IL66BLb2g20uIKog5Y2dQ0IiigW0XKrvmWiOvc0yXw80z3tMEzEnHjaGAb3ENuU7MnQqgnYJ1Cl2l9RvNgDi4g==", + "requires": { + "vscode-jsonrpc": "^4.0.0", + "vscode-languageserver-types": "3.14.0" + } + }, + "vscode-languageserver-types": { + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.14.0.tgz", + "integrity": "sha512-lTmS6AlAlMHOvPQemVwo3CezxBp0sNB95KNPkqp3Nxd5VFEnuG1ByM0zlRWos0zjO3ZWtkvhal0COgiV1xIA4A==" + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + }, + "yauzl": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz", + "integrity": "sha1-x+sXyT4RLLEIb6bY5R+wZnt5pfk=", + "dev": true, + "requires": { + "buffer-crc32": "~0.2.3", + "fd-slicer": "~1.1.0" + } + }, + "yazl": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/yazl/-/yazl-2.5.1.tgz", + "integrity": "sha512-phENi2PLiHnHb6QBVot+dJnaAZ0xosj7p3fWl+znIjBDlnMI2PsZCJZ306BPTFOaHf5qdDEI8x5qFrSOBN5vrw==", + "dev": true, + "requires": { + "buffer-crc32": "~0.2.3" + } + } + } +} diff --git a/client/package.json b/client/package.json new file mode 100644 index 000000000..894cc66d3 --- /dev/null +++ b/client/package.json @@ -0,0 +1,55 @@ +{ + "name": "pyright", + "displayName": "Pyright", + "description": "VS Code language support for Python", + "version": "0.1.0", + "licensce": "MIT", + "author": { + "name": "Microsoft Corporation" + }, + "publisher": "Microsoft", + "repository": { + "type": "git", + "url": "https://github.com/Microsoft/pyright" + }, + "engines": { + "vscode": "^1.26.0" + }, + "keywords": [ + "python" + ], + "categories": [ + "Programming Languages" + ], + "activationEvents": [ + "onLanguage:python" + ], + "main": "./out/src/extension", + "contributes": { + "languages": [ + { + "id": "python", + "aliases": [ + "Python" + ], + "extensions": [ + ".py", + ".pyi" + ] + } + ] + }, + "scripts": { + "vscode:prepublish": "npm run build", + "build": "tsc -p ./", + "update-vscode": "node ./node_modules/vscode/bin/install", + "postinstall": "node ./node_modules/vscode/bin/install" + }, + "devDependencies": { + "typescript": "^3.2.2", + "vscode": "^1.1.26" + }, + "dependencies": { + "vscode-languageclient": "^5.1.1" + } +} diff --git a/client/src/extension.ts b/client/src/extension.ts new file mode 100644 index 000000000..920474cb1 --- /dev/null +++ b/client/src/extension.ts @@ -0,0 +1,46 @@ +/* +* extension.ts +* +* Provides client for Pyright Python language server. This portion runs +* in the context of the VS Code process and talks to the server, which +* runs in another process. +*/ + +import * as path from 'path'; +import { ExtensionContext, workspace } from 'vscode'; +import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind } from 'vscode-languageclient'; + +export function activate(context: ExtensionContext) { + let serverModule = context.asAbsolutePath(path.join('server', 'server.js')); + let debugOptions = { execArgv: ["--nolazy", "--inspect=6600"] }; + + // If the extension is launched in debug mode, then the debug server options are used. + // Otherwise the run options are used. + let serverOptions: ServerOptions = { + run : { module: serverModule, transport: TransportKind.ipc }, + debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions } + } + + // Options to control the language client + let clientOptions: LanguageClientOptions = { + // Register the server for plain text documents + documentSelector: [{ + scheme: 'file', + language: 'python' + }], + synchronize: { + // Synchronize the setting section 'languageServerExample' to the server + configurationSection: 'python', + // Notify the server about file changes to '.clientrc files contain in the workspace + fileEvents: workspace.createFileSystemWatcher('**/.clientrc') + } + } + + // Create the language client and start the client. + let languageClient = new LanguageClient('python', 'Python', serverOptions, clientOptions); + let disposable = languageClient.start(); + + // Push the disposable to the context's subscriptions so that the + // client can be deactivated on extension deactivation. + context.subscriptions.push(disposable); +} diff --git a/client/tsconfig.json b/client/tsconfig.json new file mode 100644 index 000000000..d7eadbd18 --- /dev/null +++ b/client/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "noUnusedLocals": true, + "noImplicitAny": true, + "noImplicitReturns": true, + "strictNullChecks": true, + "skipLibCheck": true, + "target": "es6", + "module": "commonjs", + "moduleResolution": "node", + "rootDir": ".", + "outDir": "out", + "lib": [ "es2016" ], + "sourceMap": true + }, + "exclude": [ + "node_modules", + "server" + ] +} diff --git a/client/typeshed-fallback/LICENSE b/client/typeshed-fallback/LICENSE new file mode 100644 index 000000000..e5833ae42 --- /dev/null +++ b/client/typeshed-fallback/LICENSE @@ -0,0 +1,238 @@ +The "typeshed" project is licensed under the terms of the Apache license, as +reproduced below. + += = = = = + +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + += = = = = + +Parts of typeshed are licensed under different licenses (like the MIT +license), reproduced below. + += = = = = + +The MIT License + +Copyright (c) 2015 Jukka Lehtosalo and contributors + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + += = = = = + diff --git a/client/typeshed-fallback/README.md b/client/typeshed-fallback/README.md new file mode 100644 index 000000000..9423259ee --- /dev/null +++ b/client/typeshed-fallback/README.md @@ -0,0 +1,144 @@ +# typeshed + +[![Build Status](https://travis-ci.org/python/typeshed.svg?branch=master)](https://travis-ci.org/python/typeshed) +[![Chat at https://gitter.im/python/typing](https://badges.gitter.im/python/typing.svg)](https://gitter.im/python/typing?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +## About + +Typeshed contains external type annotations for the Python standard library +and Python builtins, as well as third party packages. + +This data can e.g. be used for static analysis, type checking or type inference. + +For information on how to use `typeshed`, read below. Information for +contributors can be found in [CONTRIBUTING.md](CONTRIBUTING.md). **Please read +it before submitting pull requests.** + +Typeshed supports Python versions 2.7 and 3.4 and up. + +## Using + +If you're just using mypy (or pytype or PyCharm), as opposed to +developing it, you don't need to interact with the typeshed repo at +all: a copy of typeshed is bundled with mypy. + +When you use a checked-out clone of the mypy repo, a copy of typeshed +should be included as a submodule, using + + $ git clone --recurse-submodules https://github.com/python/mypy.git + +or + + $ git clone https://github.com/python/mypy.git + $ cd mypy + $ git submodule init + $ git submodule update + +and occasionally you will have to repeat the final command (`git +submodule update`) to pull in changes made in the upstream typeshed +repo. + +PyCharm and pytype similarly include a copy of typeshed. The one in +pytype can be updated in the same way if you are working with the +pytype repo. + +## Format + +Each Python module is represented by a `.pyi` "stub". This is a normal Python +file (i.e., it can be interpreted by Python 3), except all the methods are empty. +Python function annotations ([PEP 3107](https://www.python.org/dev/peps/pep-3107/)) +are used to describe the types the function has. + +See [PEP 484](http://www.python.org/dev/peps/pep-0484/) for the exact +syntax of the stub files and [CONTRIBUTING.md](CONTRIBUTING.md) for the +coding style used in typeshed. + +## Directory structure + +### stdlib + +This contains stubs for modules the Python standard library -- which +includes pure Python modules, dynamically loaded extension modules, +hard-linked extension modules, and the builtins. + +### third_party + +Modules that are not shipped with Python but have a type description in Python +go into `third_party`. Since these modules can behave differently for different +versions of Python, `third_party` has version subdirectories, just like +`stdlib`. + +NOTE: When you're contributing a new stub for a package that you did +not develop, please obtain consent of the package owner (this is +specified in [PEP +484](https://www.python.org/dev/peps/pep-0484/#the-typeshed-repo)). +The best way to obtain consent is to file an issue in the third-party +package's tracker and include the link to a positive response in your PR +for typeshed. + +For more information on directory structure and stub versioning, see +[the relevant section of CONTRIBUTING.md]( +https://github.com/python/typeshed/blob/master/CONTRIBUTING.md#stub-versioning). + +## Contributing + +Please read [CONTRIBUTING.md](CONTRIBUTING.md) before submitting pull +requests. If you have questions related to contributing, drop by the [typing Gitter](https://gitter.im/python/typing). + +## Running the tests + +The tests are automatically run by Travis CI on every PR and push to +the repo. There are several sets of tests: `tests/mypy_test.py` +runs tests against [mypy](https://github.com/python/mypy/), while +`tests/pytype_test.py` runs tests against +[pytype](https://github.com/google/pytype/). + +Both sets of tests are shallow -- they verify that all stubs can be +imported but they don't check whether stubs match their implementation +(in the Python standard library or a third-party package). Also note +that each set of tests has a blacklist of modules that are not tested +at all. The blacklists also live in the tests directory. + +In addition, you can run `tests/mypy_selftest.py` to run mypy's own +test suite using the typeshed code in your repo. This will sometimes +catch issues with incorrectly typed stubs, but is much slower than the +other tests. + +To manually run the mypy tests, you need to have Python 3.5 or higher; +Python 3.6.1 or higher is recommended. + +Run: +``` +$ python3.6 -m venv .venv3 +$ source .venv3/bin/activate +(.venv3)$ pip3 install -r requirements-tests-py3.txt +``` +This will install mypy (you need the latest master branch from GitHub), +typed-ast, flake8, and pytype. You can then run mypy, flake8, and pytype tests +by invoking: +``` +(.venv3)$ python3 tests/mypy_test.py +... +(.venv3)$ python3 tests/mypy_selftest.py +... +(.venv3)$ flake8 +... +(.venv3)$ python3 tests/pytype_test.py +... +``` +Note that flake8 only works with Python 3.6 or higher, and that to run the +pytype tests, you will need Python 2.7 and Python 3.6 interpreters. Pytype will +find these automatically if they're in `PATH`, but otherwise you must point to +them with the `--python27-exe` and `--python36-exe` arguments, respectively. + +For mypy, if you are in the typeshed repo that is submodule of the +mypy repo (so `..` refers to the mypy repo), there's a shortcut to run +the mypy tests that avoids installing mypy: +```bash +$ PYTHONPATH=../.. python3 tests/mypy_test.py +``` +You can mypy tests to a single version by passing `-p2` or `-p3.5` e.g. +```bash +$ PYTHONPATH=../.. python3 tests/mypy_test.py -p3.5 +running mypy --python-version 3.5 --strict-optional # with 342 files +``` diff --git a/client/typeshed-fallback/stdlib/2/BaseHTTPServer.pyi b/client/typeshed-fallback/stdlib/2/BaseHTTPServer.pyi new file mode 100644 index 000000000..8bb34b887 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/BaseHTTPServer.pyi @@ -0,0 +1,47 @@ +# Stubs for BaseHTTPServer (Python 2.7) + +from typing import Any, BinaryIO, Mapping, Optional, Tuple, Union +import SocketServer +import mimetools + +class HTTPServer(SocketServer.TCPServer): + server_name = ... # type: str + server_port = ... # type: int + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: type) -> None: ... + +class BaseHTTPRequestHandler: + client_address = ... # type: Tuple[str, int] + server = ... # type: SocketServer.BaseServer + close_connection = ... # type: bool + command = ... # type: str + path = ... # type: str + request_version = ... # type: str + headers = ... # type: mimetools.Message + rfile = ... # type: BinaryIO + wfile = ... # type: BinaryIO + server_version = ... # type: str + sys_version = ... # type: str + error_message_format = ... # type: str + error_content_type = ... # type: str + protocol_version = ... # type: str + MessageClass = ... # type: type + responses = ... # type: Mapping[int, Tuple[str, str]] + def __init__(self, request: bytes, client_address: Tuple[str, int], + server: SocketServer.BaseServer) -> None: ... + def handle(self) -> None: ... + def handle_one_request(self) -> None: ... + def send_error(self, code: int, message: Optional[str] = ...) -> None: ... + def send_response(self, code: int, + message: Optional[str] = ...) -> None: ... + def send_header(self, keyword: str, value: str) -> None: ... + def end_headers(self) -> None: ... + def flush_headers(self) -> None: ... + def log_request(self, code: Union[int, str] = ..., + size: Union[int, str] = ...) -> None: ... + def log_error(self, format: str, *args: Any) -> None: ... + def log_message(self, format: str, *args: Any) -> None: ... + def version_string(self) -> str: ... + def date_time_string(self, timestamp: Optional[int] = ...) -> str: ... + def log_date_time_string(self) -> str: ... + def address_string(self) -> str: ... diff --git a/client/typeshed-fallback/stdlib/2/ConfigParser.pyi b/client/typeshed-fallback/stdlib/2/ConfigParser.pyi new file mode 100644 index 000000000..6e6a70e1d --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/ConfigParser.pyi @@ -0,0 +1,97 @@ +from typing import Any, IO, Sequence, Tuple, Union, List, Dict, Protocol + +DEFAULTSECT = ... # type: str +MAX_INTERPOLATION_DEPTH = ... # type: int + +class Error(Exception): + message = ... # type: Any + def __init__(self, msg: str = ...) -> None: ... + def _get_message(self) -> None: ... + def _set_message(self, value: str) -> None: ... + def __repr__(self) -> str: ... + def __str__(self) -> str: ... + +class NoSectionError(Error): + section = ... # type: str + def __init__(self, section: str) -> None: ... + +class DuplicateSectionError(Error): + section = ... # type: str + def __init__(self, section: str) -> None: ... + +class NoOptionError(Error): + section = ... # type: str + option = ... # type: str + def __init__(self, option: str, section: str) -> None: ... + +class InterpolationError(Error): + section = ... # type: str + option = ... # type: str + msg = ... # type: str + def __init__(self, option: str, section: str, msg: str) -> None: ... + +class InterpolationMissingOptionError(InterpolationError): + reference = ... # type: str + def __init__(self, option: str, section: str, rawval: str, reference: str) -> None: ... + +class InterpolationSyntaxError(InterpolationError): ... + +class InterpolationDepthError(InterpolationError): + def __init__(self, option: str, section: str, rawval: str) -> None: ... + +class ParsingError(Error): + filename = ... # type: str + errors = ... # type: List[Tuple[Any, Any]] + def __init__(self, filename: str) -> None: ... + def append(self, lineno: Any, line: Any) -> None: ... + +class MissingSectionHeaderError(ParsingError): + lineno = ... # type: Any + line = ... # type: Any + def __init__(self, filename: str, lineno: Any, line: Any) -> None: ... + +class _Readable(Protocol): + def readline(self) -> str: ... + +class RawConfigParser: + _dict = ... # type: Any + _sections = ... # type: dict + _defaults = ... # type: dict + _optcre = ... # type: Any + SECTCRE = ... # type: Any + OPTCRE = ... # type: Any + OPTCRE_NV = ... # type: Any + def __init__(self, defaults: Dict[Any, Any] = ..., dict_type: Any = ..., allow_no_value: bool = ...) -> None: ... + def defaults(self) -> Dict[Any, Any]: ... + def sections(self) -> List[str]: ... + def add_section(self, section: str) -> None: ... + def has_section(self, section: str) -> bool: ... + def options(self, section: str) -> List[str]: ... + def read(self, filenames: Union[str, Sequence[str]]) -> List[str]: ... + def readfp(self, fp: _Readable, filename: str = ...) -> None: ... + def get(self, section: str, option: str) -> str: ... + def items(self, section: str) -> List[Tuple[Any, Any]]: ... + def _get(self, section: str, conv: type, option: str) -> Any: ... + def getint(self, section: str, option: str) -> int: ... + def getfloat(self, section: str, option: str) -> float: ... + _boolean_states = ... # type: Dict[str, bool] + def getboolean(self, section: str, option: str) -> bool: ... + def optionxform(self, optionstr: str) -> str: ... + def has_option(self, section: str, option: str) -> bool: ... + def set(self, section: str, option: str, value: Any = ...) -> None: ... + def write(self, fp: IO[str]) -> None: ... + def remove_option(self, section: str, option: Any) -> bool: ... + def remove_section(self, section: str) -> bool: ... + def _read(self, fp: IO[str], fpname: str) -> None: ... + +class ConfigParser(RawConfigParser): + _KEYCRE = ... # type: Any + def get(self, section: str, option: str, raw: bool = ..., vars: dict = ...) -> Any: ... + def items(self, section: str, raw: bool = ..., vars: dict = ...) -> List[Tuple[str, Any]]: ... + def _interpolate(self, section: str, option: str, rawval: Any, vars: Any) -> str: ... + def _interpolation_replace(self, match: Any) -> str: ... + +class SafeConfigParser(ConfigParser): + _interpvar_re = ... # type: Any + def _interpolate(self, section: str, option: str, rawval: Any, vars: Any) -> str: ... + def _interpolate_some(self, option: str, accum: list, rest: str, section: str, map: dict, depth: int) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/Cookie.pyi b/client/typeshed-fallback/stdlib/2/Cookie.pyi new file mode 100644 index 000000000..234c0d006 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/Cookie.pyi @@ -0,0 +1,40 @@ +from typing import Any, Optional + +class CookieError(Exception): ... + +class Morsel(dict): + key = ... # type: Any + def __init__(self): ... + def __setitem__(self, K, V): ... + def isReservedKey(self, K): ... + value = ... # type: Any + coded_value = ... # type: Any + def set(self, key, val, coded_val, LegalChars=..., idmap=..., translate=...): ... + def output(self, attrs: Optional[Any] = ..., header=...): ... + def js_output(self, attrs: Optional[Any] = ...): ... + def OutputString(self, attrs: Optional[Any] = ...): ... + +class BaseCookie(dict): + def value_decode(self, val): ... + def value_encode(self, val): ... + def __init__(self, input: Optional[Any] = ...): ... + def __setitem__(self, key, value): ... + def output(self, attrs: Optional[Any] = ..., header=..., sep=...): ... + def js_output(self, attrs: Optional[Any] = ...): ... + def load(self, rawdata): ... + +class SimpleCookie(BaseCookie): + def value_decode(self, val): ... + def value_encode(self, val): ... + +class SerialCookie(BaseCookie): + def __init__(self, input: Optional[Any] = ...): ... + def value_decode(self, val): ... + def value_encode(self, val): ... + +class SmartCookie(BaseCookie): + def __init__(self, input: Optional[Any] = ...): ... + def value_decode(self, val): ... + def value_encode(self, val): ... + +Cookie = ... # type: Any diff --git a/client/typeshed-fallback/stdlib/2/HTMLParser.pyi b/client/typeshed-fallback/stdlib/2/HTMLParser.pyi new file mode 100644 index 000000000..989e14c80 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/HTMLParser.pyi @@ -0,0 +1,31 @@ +from typing import List, Tuple, AnyStr +from markupbase import ParserBase + +class HTMLParser(ParserBase): + def __init__(self) -> None: ... + def feed(self, feed: AnyStr) -> None: ... + def close(self) -> None: ... + def reset(self) -> None: ... + + def get_starttag_text(self) -> AnyStr: ... + def set_cdata_mode(self, AnyStr) -> None: ... + def clear_cdata_mode(self) -> None: ... + + def handle_startendtag(self, tag: AnyStr, attrs: List[Tuple[AnyStr, AnyStr]]): ... + def handle_starttag(self, tag: AnyStr, attrs: List[Tuple[AnyStr, AnyStr]]): ... + def handle_endtag(self, tag: AnyStr): ... + def handle_charref(self, name: AnyStr): ... + def handle_entityref(self, name: AnyStr): ... + def handle_data(self, data: AnyStr): ... + def handle_comment(self, data: AnyStr): ... + def handle_decl(self, decl: AnyStr): ... + def handle_pi(self, data: AnyStr): ... + + def unknown_decl(self, data: AnyStr): ... + + def unescape(self, s: AnyStr) -> AnyStr: ... + +class HTMLParseError(Exception): + msg = ... # type: str + lineno = ... # type: int + offset = ... # type: int diff --git a/client/typeshed-fallback/stdlib/2/Queue.pyi b/client/typeshed-fallback/stdlib/2/Queue.pyi new file mode 100644 index 000000000..831b96cc4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/Queue.pyi @@ -0,0 +1,29 @@ +# Stubs for Queue (Python 2) + +from typing import Any, TypeVar, Generic, Optional + +_T = TypeVar('_T') + +class Empty(Exception): ... +class Full(Exception): ... + +class Queue(Generic[_T]): + maxsize = ... # type: Any + mutex = ... # type: Any + not_empty = ... # type: Any + not_full = ... # type: Any + all_tasks_done = ... # type: Any + unfinished_tasks = ... # type: Any + def __init__(self, maxsize: int = ...) -> None: ... + def task_done(self) -> None: ... + def join(self) -> None: ... + def qsize(self) -> int: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def put(self, item: _T, block: bool = ..., timeout: Optional[float] = ...) -> None: ... + def put_nowait(self, item: _T) -> None: ... + def get(self, block: bool = ..., timeout: Optional[float] = ...) -> _T: ... + def get_nowait(self) -> _T: ... + +class PriorityQueue(Queue): ... +class LifoQueue(Queue): ... diff --git a/client/typeshed-fallback/stdlib/2/SimpleHTTPServer.pyi b/client/typeshed-fallback/stdlib/2/SimpleHTTPServer.pyi new file mode 100644 index 000000000..5bfed2a5f --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/SimpleHTTPServer.pyi @@ -0,0 +1,16 @@ +# Stubs for SimpleHTTPServer (Python 2) + +from typing import Any, AnyStr, IO, Mapping, Optional, Union +import BaseHTTPServer +from StringIO import StringIO + +class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): + server_version = ... # type: str + def do_GET(self) -> None: ... + def do_HEAD(self) -> None: ... + def send_head(self) -> Optional[IO[str]]: ... + def list_directory(self, path: Union[str, unicode]) -> Optional[StringIO]: ... + def translate_path(self, path: AnyStr) -> AnyStr: ... + def copyfile(self, source: IO[AnyStr], outputfile: IO[AnyStr]): ... + def guess_type(self, path: Union[str, unicode]) -> str: ... + extensions_map = ... # type: Mapping[str, str] diff --git a/client/typeshed-fallback/stdlib/2/SocketServer.pyi b/client/typeshed-fallback/stdlib/2/SocketServer.pyi new file mode 100644 index 000000000..9e6c10b5d --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/SocketServer.pyi @@ -0,0 +1,99 @@ +# NB: SocketServer.pyi and socketserver.pyi must remain consistent! +# Stubs for socketserver + +from typing import Any, BinaryIO, Optional, Tuple, Type +from socket import SocketType +import sys +import types + +class BaseServer: + address_family = ... # type: int + RequestHandlerClass = ... # type: type + server_address = ... # type: Tuple[str, int] + socket = ... # type: SocketType + allow_reuse_address = ... # type: bool + request_queue_size = ... # type: int + socket_type = ... # type: int + timeout = ... # type: Optional[float] + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: type) -> None: ... + def fileno(self) -> int: ... + def handle_request(self) -> None: ... + def serve_forever(self, poll_interval: float = ...) -> None: ... + def shutdown(self) -> None: ... + def server_close(self) -> None: ... + def finish_request(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... + def get_request(self) -> None: ... + def handle_error(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... + def handle_timeout(self) -> None: ... + def process_request(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... + def server_activate(self) -> None: ... + def server_bind(self) -> None: ... + def verify_request(self, request: bytes, + client_address: Tuple[str, int]) -> bool: ... + if sys.version_info >= (3, 6): + def __enter__(self) -> BaseServer: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[types.TracebackType]) -> bool: ... + if sys.version_info >= (3, 3): + def service_actions(self) -> None: ... + +class TCPServer(BaseServer): + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: type, + bind_and_activate: bool = ...) -> None: ... + +class UDPServer(BaseServer): + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: type, + bind_and_activate: bool = ...) -> None: ... + +if sys.platform != 'win32': + class UnixStreamServer(BaseServer): + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: type, + bind_and_activate: bool = ...) -> None: ... + + class UnixDatagramServer(BaseServer): + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: type, + bind_and_activate: bool = ...) -> None: ... + +class ForkingMixIn: ... +class ThreadingMixIn: ... + +class ForkingTCPServer(ForkingMixIn, TCPServer): ... +class ForkingUDPServer(ForkingMixIn, UDPServer): ... +class ThreadingTCPServer(ThreadingMixIn, TCPServer): ... +class ThreadingUDPServer(ThreadingMixIn, UDPServer): ... +if sys.platform != 'win32': + class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): ... + class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): ... + + +class BaseRequestHandler: + # Those are technically of types, respectively: + # * Union[SocketType, Tuple[bytes, SocketType]] + # * Union[Tuple[str, int], str] + # But there are some concerns that having unions here would cause + # too much inconvenience to people using it (see + # https://github.com/python/typeshed/pull/384#issuecomment-234649696) + request = ... # type: Any + client_address = ... # type: Any + + server = ... # type: BaseServer + def setup(self) -> None: ... + def handle(self) -> None: ... + def finish(self) -> None: ... + +class StreamRequestHandler(BaseRequestHandler): + rfile = ... # type: BinaryIO + wfile = ... # type: BinaryIO + +class DatagramRequestHandler(BaseRequestHandler): + rfile = ... # type: BinaryIO + wfile = ... # type: BinaryIO diff --git a/client/typeshed-fallback/stdlib/2/StringIO.pyi b/client/typeshed-fallback/stdlib/2/StringIO.pyi new file mode 100644 index 000000000..0526edff2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/StringIO.pyi @@ -0,0 +1,30 @@ +# Stubs for StringIO (Python 2) + +from typing import Any, IO, AnyStr, Iterator, Iterable, Generic, List, Optional + +class StringIO(IO[AnyStr], Generic[AnyStr]): + closed = ... # type: bool + softspace = ... # type: int + len = ... # type: int + name = ... # type: str + def __init__(self, buf: AnyStr = ...) -> None: ... + def __iter__(self) -> Iterator[AnyStr]: ... + def next(self) -> AnyStr: ... + def close(self) -> None: ... + def isatty(self) -> bool: ... + def seek(self, pos: int, mode: int = ...) -> int: ... + def tell(self) -> int: ... + def read(self, n: int = ...) -> AnyStr: ... + def readline(self, length: int = ...) -> AnyStr: ... + def readlines(self, sizehint: int = ...) -> List[AnyStr]: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def write(self, s: AnyStr) -> int: ... + def writelines(self, iterable: Iterable[AnyStr]) -> None: ... + def flush(self) -> None: ... + def getvalue(self) -> AnyStr: ... + def __enter__(self) -> Any: ... + def __exit__(self, type: Any, value: Any, traceback: Any) -> Any: ... + def fileno(self) -> int: ... + def readable(self) -> bool: ... + def seekable(self) -> bool: ... + def writable(self) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/2/UserDict.pyi b/client/typeshed-fallback/stdlib/2/UserDict.pyi new file mode 100644 index 000000000..33ebd1a51 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/UserDict.pyi @@ -0,0 +1,44 @@ +from typing import (Any, Container, Dict, Generic, Iterable, Iterator, List, + Mapping, Optional, Sized, Tuple, TypeVar, Union, overload) + +_KT = TypeVar('_KT') +_VT = TypeVar('_VT') +_T = TypeVar('_T') + +class UserDict(Dict[_KT, _VT], Generic[_KT, _VT]): + data = ... # type: Mapping[_KT, _VT] + + def __init__(self, initialdata: Mapping[_KT, _VT] = ...) -> None: ... + + # TODO: __iter__ is not available for UserDict + +class IterableUserDict(UserDict[_KT, _VT], Generic[_KT, _VT]): + ... + +class DictMixin(Iterable[_KT], Container[_KT], Sized, Generic[_KT, _VT]): + def has_key(self, key: _KT) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_KT]: ... + + # From typing.Mapping[_KT, _VT] + # (can't inherit because of keys()) + @overload + def get(self, k: _KT) -> Optional[_VT]: ... + @overload + def get(self, k: _KT, default: Union[_VT, _T]) -> Union[_VT, _T]: ... + def values(self) -> List[_VT]: ... + def items(self) -> List[Tuple[_KT, _VT]]: ... + def iterkeys(self) -> Iterator[_KT]: ... + def itervalues(self) -> Iterator[_VT]: ... + def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... + def __contains__(self, o: Any) -> bool: ... + + # From typing.MutableMapping[_KT, _VT] + def clear(self) -> None: ... + def pop(self, k: _KT, default: _VT = ...) -> _VT: ... + def popitem(self) -> Tuple[_KT, _VT]: ... + def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ... + @overload + def update(self, m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def update(self, m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/UserList.pyi b/client/typeshed-fallback/stdlib/2/UserList.pyi new file mode 100644 index 000000000..b8466eed1 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/UserList.pyi @@ -0,0 +1,18 @@ +from typing import Iterable, MutableSequence, TypeVar, Union, overload + +_T = TypeVar("_T") +_ULT = TypeVar("_ULT", bound=UserList) + +class UserList(MutableSequence[_T]): + def insert(self, index: int, object: _T) -> None: ... + @overload + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + def __len__(self) -> int: ... + @overload + def __getitem__(self, i: int) -> _T: ... + @overload + def __getitem__(self: _ULT, s: slice) -> _ULT: ... + def sort(self) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/UserString.pyi b/client/typeshed-fallback/stdlib/2/UserString.pyi new file mode 100644 index 000000000..8cbbfc124 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/UserString.pyi @@ -0,0 +1,75 @@ +import collections +from typing import Any, Iterable, List, MutableSequence, Sequence, Optional, overload, Text, TypeVar, Tuple, Union + +_UST = TypeVar("_UST", bound=UserString) +_MST = TypeVar("_MST", bound=MutableString) + +class UserString(Sequence[UserString]): + data: unicode + def __init__(self, seq: object) -> None: ... + def __int__(self) -> int: ... + def __long__(self) -> long: ... + def __float__(self) -> float: ... + def __complex__(self) -> complex: ... + def __hash__(self) -> int: ... + def __len__(self) -> int: ... + @overload + def __getitem__(self: _UST, i: int) -> _UST: ... + @overload + def __getitem__(self: _UST, s: slice) -> _UST: ... + def __add__(self: _UST, other: Any) -> _UST: ... + def __radd__(self: _UST, other: Any) -> _UST: ... + def __mul__(self: _UST, other: int) -> _UST: ... + def __rmul__(self: _UST, other: int) -> _UST: ... + def __mod__(self: _UST, args: Any) -> _UST: ... + def capitalize(self: _UST) -> _UST: ... + def center(self: _UST, width: int, *args: Any) -> _UST: ... + def count(self, sub: int, start: int = ..., end: int = ...) -> int: ... + def decode(self: _UST, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> _UST: ... + def encode(self: _UST, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> _UST: ... + def endswith(self, suffix: Text, start: int = ..., end: int = ...) -> bool: ... + def expandtabs(self: _UST, tabsize: int = ...) -> _UST: ... + def find(self, sub: Text, start: int = ..., end: int = ...) -> int: ... + def index(self, sub: Text, start: int = ..., end: int = ...) -> int: ... + def isalpha(self) -> bool: ... + def isalnum(self) -> bool: ... + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isnumeric(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, seq: Iterable[Text]) -> Text: ... + def ljust(self: _UST, width: int, *args: Any) -> _UST: ... + def lower(self: _UST) -> _UST: ... + def lstrip(self: _UST, chars: Optional[Text] = ...) -> _UST: ... + def partition(self, sep: Text) -> Tuple[Text, Text, Text]: ... + def replace(self: _UST, old: Text, new: Text, maxsplit: int = ...) -> _UST: ... + def rfind(self, sub: Text, start: int = ..., end: int = ...) -> int: ... + def rindex(self, sub: Text, start: int = ..., end: int = ...) -> int: ... + def rjust(self: _UST, width: int, *args: Any) -> _UST: ... + def rpartition(self, sep: Text) -> Tuple[Text, Text, Text]: ... + def rstrip(self: _UST, chars: Optional[Text] = ...) -> _UST: ... + def split(self, sep: Optional[Text] = ..., maxsplit: int = ...) -> List[Text]: ... + def rsplit(self, sep: Optional[Text] = ..., maxsplit: int = ...) -> List[Text]: ... + def splitlines(self, keepends: int = ...) -> List[Text]: ... + def startswith(self, suffix: Text, start: int = ..., end: int = ...) -> bool: ... + def strip(self: _UST, chars: Optional[Text] = ...) -> _UST: ... + def swapcase(self: _UST) -> _UST: ... + def title(self: _UST) -> _UST: ... + def translate(self: _UST, *args: Any) -> _UST: ... + def upper(self: _UST) -> _UST: ... + def zfill(self: _UST, width: int) -> _UST: ... + +class MutableString(UserString, MutableSequence[MutableString]): # type: ignore + @overload + def __getitem__(self: _MST, i: int) -> _MST: ... + @overload + def __getitem__(self: _MST, s: slice) -> _MST: ... + def __setitem__(self, index: Union[int, slice], sub: Any) -> None: ... + def __delitem__(self, index: Union[int, slice]) -> None: ... + def immutable(self) -> UserString: ... + def __iadd__(self: _MST, other: Any) -> _MST: ... + def __imul__(self, n: int) -> _MST: ... + def insert(self, index: int, value: Any) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/__builtin__.pyi b/client/typeshed-fallback/stdlib/2/__builtin__.pyi new file mode 100644 index 000000000..db00c557e --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/__builtin__.pyi @@ -0,0 +1,1611 @@ +# True and False are deliberately omitted because they are keywords in +# Python 3, and stub files conform to Python 3 syntax. + +from typing import ( + TypeVar, Iterator, Iterable, NoReturn, overload, Container, + Sequence, MutableSequence, Mapping, MutableMapping, Tuple, List, Any, Dict, Callable, Generic, + Set, AbstractSet, FrozenSet, MutableSet, Sized, Reversible, SupportsInt, SupportsFloat, SupportsAbs, + SupportsComplex, SupportsRound, IO, BinaryIO, Union, + ItemsView, KeysView, ValuesView, ByteString, Optional, AnyStr, Type, Text, +) +from abc import abstractmethod, ABCMeta +from ast import mod +from types import TracebackType, CodeType +import sys + +if sys.version_info >= (3,): + from typing import SupportsBytes + +_T = TypeVar('_T') +_T_co = TypeVar('_T_co', covariant=True) +_KT = TypeVar('_KT') +_VT = TypeVar('_VT') +_S = TypeVar('_S') +_T1 = TypeVar('_T1') +_T2 = TypeVar('_T2') +_T3 = TypeVar('_T3') +_T4 = TypeVar('_T4') +_T5 = TypeVar('_T5') +_TT = TypeVar('_TT', bound='type') + +class object: + __doc__: Optional[str] + __dict__: Dict[str, Any] + __slots__: Union[Text, Iterable[Text]] + __module__: str + if sys.version_info >= (3, 6): + __annotations__: Dict[str, Any] + + @property + def __class__(self: _T) -> Type[_T]: ... + @__class__.setter + def __class__(self, __type: Type[object]) -> None: ... + def __init__(self) -> None: ... + def __new__(cls) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __eq__(self, o: object) -> bool: ... + def __ne__(self, o: object) -> bool: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __hash__(self) -> int: ... + def __format__(self, format_spec: str) -> str: ... + def __getattribute__(self, name: str) -> Any: ... + def __delattr__(self, name: str) -> None: ... + def __sizeof__(self) -> int: ... + def __reduce__(self) -> tuple: ... + def __reduce_ex__(self, protocol: int) -> tuple: ... + if sys.version_info >= (3,): + def __dir__(self) -> Iterable[str]: ... + if sys.version_info >= (3, 6): + def __init_subclass__(cls) -> None: ... + +class staticmethod(object): # Special, only valid as a decorator. + __func__: Callable + if sys.version_info >= (3,): + __isabstractmethod__: bool + + def __init__(self, f: Callable) -> None: ... + def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable: ... + +class classmethod(object): # Special, only valid as a decorator. + __func__: Callable + if sys.version_info >= (3,): + __isabstractmethod__: bool + + def __init__(self, f: Callable) -> None: ... + def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable: ... + +class type(object): + __base__: type + __bases__: Tuple[type, ...] + __basicsize__: int + __dict__: Dict[str, Any] + __dictoffset__: int + __flags__: int + __itemsize__: int + __module__: str + __mro__: Tuple[type, ...] + __name__: str + if sys.version_info >= (3,): + __qualname__: str + __text_signature__: Optional[str] + __weakrefoffset__: int + + @overload + def __init__(self, o: object) -> None: ... + @overload + def __init__(self, name: str, bases: Tuple[type, ...], dict: Dict[str, Any]) -> None: ... + @overload + def __new__(cls, o: object) -> type: ... + @overload + def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ... + def __call__(self, *args: Any, **kwds: Any) -> Any: ... + def __subclasses__(self: _TT) -> List[_TT]: ... + # Note: the documentation doesnt specify what the return type is, the standard + # implementation seems to be returning a list. + def mro(self) -> List[type]: ... + def __instancecheck__(self, instance: Any) -> bool: ... + def __subclasscheck__(self, subclass: type) -> bool: ... + if sys.version_info >= (3,): + @classmethod + def __prepare__(metacls, __name: str, __bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, Any]: ... + +class super(object): + if sys.version_info >= (3,): + @overload + def __init__(self, t: Any, obj: Any) -> None: ... + @overload + def __init__(self, t: Any) -> None: ... + @overload + def __init__(self) -> None: ... + else: + @overload + def __init__(self, t: Any, obj: Any) -> None: ... + @overload + def __init__(self, t: Any) -> None: ... + +class int: + @overload + def __init__(self, x: Union[Text, bytes, SupportsInt] = ...) -> None: ... + @overload + def __init__(self, x: Union[Text, bytes, bytearray], base: int) -> None: ... + + @property + def real(self) -> int: ... + @property + def imag(self) -> int: ... + @property + def numerator(self) -> int: ... + @property + def denominator(self) -> int: ... + def conjugate(self) -> int: ... + + def bit_length(self) -> int: ... + if sys.version_info >= (3,): + def to_bytes(self, length: int, byteorder: str, *, signed: bool = ...) -> bytes: ... + @classmethod + def from_bytes(cls, bytes: Sequence[int], byteorder: str, *, + signed: bool = ...) -> int: ... # TODO buffer object argument + + def __add__(self, x: int) -> int: ... + def __sub__(self, x: int) -> int: ... + def __mul__(self, x: int) -> int: ... + def __floordiv__(self, x: int) -> int: ... + if sys.version_info < (3,): + def __div__(self, x: int) -> int: ... + def __truediv__(self, x: int) -> float: ... + def __mod__(self, x: int) -> int: ... + def __divmod__(self, x: int) -> Tuple[int, int]: ... + def __radd__(self, x: int) -> int: ... + def __rsub__(self, x: int) -> int: ... + def __rmul__(self, x: int) -> int: ... + def __rfloordiv__(self, x: int) -> int: ... + if sys.version_info < (3,): + def __rdiv__(self, x: int) -> int: ... + def __rtruediv__(self, x: int) -> float: ... + def __rmod__(self, x: int) -> int: ... + def __rdivmod__(self, x: int) -> Tuple[int, int]: ... + def __pow__(self, x: int) -> Any: ... # Return type can be int or float, depending on x. + def __rpow__(self, x: int) -> Any: ... + def __and__(self, n: int) -> int: ... + def __or__(self, n: int) -> int: ... + def __xor__(self, n: int) -> int: ... + def __lshift__(self, n: int) -> int: ... + def __rshift__(self, n: int) -> int: ... + def __rand__(self, n: int) -> int: ... + def __ror__(self, n: int) -> int: ... + def __rxor__(self, n: int) -> int: ... + def __rlshift__(self, n: int) -> int: ... + def __rrshift__(self, n: int) -> int: ... + def __neg__(self) -> int: ... + def __pos__(self) -> int: ... + def __invert__(self) -> int: ... + if sys.version_info >= (3,): + def __round__(self, ndigits: Optional[int] = ...) -> int: ... + def __getnewargs__(self) -> Tuple[int]: ... + + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: int) -> bool: ... + def __le__(self, x: int) -> bool: ... + def __gt__(self, x: int) -> bool: ... + def __ge__(self, x: int) -> bool: ... + + def __str__(self) -> str: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + def __abs__(self) -> int: ... + def __hash__(self) -> int: ... + if sys.version_info >= (3,): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + def __index__(self) -> int: ... + +class float: + def __init__(self, x: Union[SupportsFloat, Text, bytes, bytearray] = ...) -> None: ... + def as_integer_ratio(self) -> Tuple[int, int]: ... + def hex(self) -> str: ... + def is_integer(self) -> bool: ... + @classmethod + def fromhex(cls, s: str) -> float: ... + + @property + def real(self) -> float: ... + @property + def imag(self) -> float: ... + def conjugate(self) -> float: ... + + def __add__(self, x: float) -> float: ... + def __sub__(self, x: float) -> float: ... + def __mul__(self, x: float) -> float: ... + def __floordiv__(self, x: float) -> float: ... + if sys.version_info < (3,): + def __div__(self, x: float) -> float: ... + def __truediv__(self, x: float) -> float: ... + def __mod__(self, x: float) -> float: ... + def __divmod__(self, x: float) -> Tuple[float, float]: ... + def __pow__(self, x: float) -> float: ... # In Python 3, returns complex if self is negative and x is not whole + def __radd__(self, x: float) -> float: ... + def __rsub__(self, x: float) -> float: ... + def __rmul__(self, x: float) -> float: ... + def __rfloordiv__(self, x: float) -> float: ... + if sys.version_info < (3,): + def __rdiv__(self, x: float) -> float: ... + def __rtruediv__(self, x: float) -> float: ... + def __rmod__(self, x: float) -> float: ... + def __rdivmod__(self, x: float) -> Tuple[float, float]: ... + def __rpow__(self, x: float) -> float: ... + def __getnewargs__(self) -> Tuple[float]: ... + if sys.version_info >= (3,): + @overload + def __round__(self) -> int: ... + @overload + def __round__(self, ndigits: None) -> int: ... + @overload + def __round__(self, ndigits: int) -> float: ... + + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: float) -> bool: ... + def __le__(self, x: float) -> bool: ... + def __gt__(self, x: float) -> bool: ... + def __ge__(self, x: float) -> bool: ... + def __neg__(self) -> float: ... + def __pos__(self) -> float: ... + + def __str__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __abs__(self) -> float: ... + def __hash__(self) -> int: ... + if sys.version_info >= (3,): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + +class complex: + @overload + def __init__(self, re: float = ..., im: float = ...) -> None: ... + @overload + def __init__(self, s: str) -> None: ... + @overload + def __init__(self, s: SupportsComplex) -> None: ... + + @property + def real(self) -> float: ... + @property + def imag(self) -> float: ... + + def conjugate(self) -> complex: ... + + def __add__(self, x: complex) -> complex: ... + def __sub__(self, x: complex) -> complex: ... + def __mul__(self, x: complex) -> complex: ... + def __pow__(self, x: complex) -> complex: ... + if sys.version_info < (3,): + def __div__(self, x: complex) -> complex: ... + def __truediv__(self, x: complex) -> complex: ... + def __radd__(self, x: complex) -> complex: ... + def __rsub__(self, x: complex) -> complex: ... + def __rmul__(self, x: complex) -> complex: ... + def __rpow__(self, x: complex) -> complex: ... + if sys.version_info < (3,): + def __rdiv__(self, x: complex) -> complex: ... + def __rtruediv__(self, x: complex) -> complex: ... + + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __neg__(self) -> complex: ... + def __pos__(self) -> complex: ... + + def __str__(self) -> str: ... + def __complex__(self) -> complex: ... + def __abs__(self) -> float: ... + def __hash__(self) -> int: ... + if sys.version_info >= (3,): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + +if sys.version_info >= (3,): + _str_base = object +else: + class basestring(metaclass=ABCMeta): ... + + class unicode(basestring, Sequence[unicode]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, o: object) -> None: ... + @overload + def __init__(self, o: str, encoding: unicode = ..., errors: unicode = ...) -> None: ... + def capitalize(self) -> unicode: ... + def center(self, width: int, fillchar: unicode = ...) -> unicode: ... + def count(self, x: unicode) -> int: ... + def decode(self, encoding: unicode = ..., errors: unicode = ...) -> unicode: ... + def encode(self, encoding: unicode = ..., errors: unicode = ...) -> str: ... + def endswith(self, suffix: Union[unicode, Tuple[unicode, ...]], start: int = ..., + end: int = ...) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> unicode: ... + def find(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def format(self, *args: Any, **kwargs: Any) -> unicode: ... + def format_map(self, map: Mapping[unicode, Any]) -> unicode: ... + def index(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + def isidentifier(self) -> bool: ... + def islower(self) -> bool: ... + def isnumeric(self) -> bool: ... + def isprintable(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, iterable: Iterable[unicode]) -> unicode: ... + def ljust(self, width: int, fillchar: unicode = ...) -> unicode: ... + def lower(self) -> unicode: ... + def lstrip(self, chars: unicode = ...) -> unicode: ... + def partition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def replace(self, old: unicode, new: unicode, count: int = ...) -> unicode: ... + def rfind(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def rindex(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def rjust(self, width: int, fillchar: unicode = ...) -> unicode: ... + def rpartition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def rsplit(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... + def rstrip(self, chars: unicode = ...) -> unicode: ... + def split(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... + def splitlines(self, keepends: bool = ...) -> List[unicode]: ... + def startswith(self, prefix: Union[unicode, Tuple[unicode, ...]], start: int = ..., + end: int = ...) -> bool: ... + def strip(self, chars: unicode = ...) -> unicode: ... + def swapcase(self) -> unicode: ... + def title(self) -> unicode: ... + def translate(self, table: Union[Dict[int, Any], unicode]) -> unicode: ... + def upper(self) -> unicode: ... + def zfill(self, width: int) -> unicode: ... + + @overload + def __getitem__(self, i: int) -> unicode: ... + @overload + def __getitem__(self, s: slice) -> unicode: ... + def __getslice__(self, start: int, stop: int) -> unicode: ... + def __add__(self, s: unicode) -> unicode: ... + def __mul__(self, n: int) -> unicode: ... + def __rmul__(self, n: int) -> unicode: ... + def __mod__(self, x: Any) -> unicode: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: unicode) -> bool: ... + def __le__(self, x: unicode) -> bool: ... + def __gt__(self, x: unicode) -> bool: ... + def __ge__(self, x: unicode) -> bool: ... + + def __len__(self) -> int: ... + def __contains__(self, s: object) -> bool: ... + def __iter__(self) -> Iterator[unicode]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __hash__(self) -> int: ... + def __getnewargs__(self) -> Tuple[unicode]: ... + + _str_base = basestring + +class str(Sequence[str], _str_base): + if sys.version_info >= (3,): + @overload + def __init__(self, o: object = ...) -> None: ... + @overload + def __init__(self, o: bytes, encoding: str = ..., errors: str = ...) -> None: ... + else: + def __init__(self, o: object = ...) -> None: ... + + def capitalize(self) -> str: ... + if sys.version_info >= (3, 3): + def casefold(self) -> str: ... + def center(self, width: int, fillchar: str = ...) -> str: ... + def count(self, x: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + if sys.version_info < (3,): + def decode(self, encoding: Text = ..., errors: Text = ...) -> unicode: ... + def encode(self, encoding: Text = ..., errors: Text = ...) -> bytes: ... + if sys.version_info >= (3,): + def endswith(self, suffix: Union[Text, Tuple[Text, ...]], start: Optional[int] = ..., + end: Optional[int] = ...) -> bool: ... + else: + def endswith(self, suffix: Union[Text, Tuple[Text, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> str: ... + def find(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def format(self, *args: Any, **kwargs: Any) -> str: ... + if sys.version_info >= (3,): + def format_map(self, map: Mapping[str, Any]) -> str: ... + def index(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + if sys.version_info >= (3, 7): + def isascii(self) -> bool: ... + if sys.version_info >= (3,): + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + if sys.version_info >= (3,): + def isidentifier(self) -> bool: ... + def islower(self) -> bool: ... + if sys.version_info >= (3,): + def isnumeric(self) -> bool: ... + def isprintable(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + if sys.version_info >= (3,): + def join(self, iterable: Iterable[str]) -> str: ... + else: + def join(self, iterable: Iterable[AnyStr]) -> AnyStr: ... + def ljust(self, width: int, fillchar: str = ...) -> str: ... + def lower(self) -> str: ... + if sys.version_info >= (3,): + def lstrip(self, chars: Optional[str] = ...) -> str: ... + def partition(self, sep: str) -> Tuple[str, str, str]: ... + def replace(self, old: str, new: str, count: int = ...) -> str: ... + else: + @overload + def lstrip(self, chars: str = ...) -> str: ... + @overload + def lstrip(self, chars: unicode) -> unicode: ... + @overload + def partition(self, sep: bytearray) -> Tuple[str, bytearray, str]: ... + @overload + def partition(self, sep: str) -> Tuple[str, str, str]: ... + @overload + def partition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def replace(self, old: AnyStr, new: AnyStr, count: int = ...) -> AnyStr: ... + def rfind(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rindex(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rjust(self, width: int, fillchar: str = ...) -> str: ... + if sys.version_info >= (3,): + def rpartition(self, sep: str) -> Tuple[str, str, str]: ... + def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + def rstrip(self, chars: Optional[str] = ...) -> str: ... + def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + else: + @overload + def rpartition(self, sep: bytearray) -> Tuple[str, bytearray, str]: ... + @overload + def rpartition(self, sep: str) -> Tuple[str, str, str]: ... + @overload + def rpartition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + @overload + def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + @overload + def rsplit(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... + @overload + def rstrip(self, chars: str = ...) -> str: ... + @overload + def rstrip(self, chars: unicode) -> unicode: ... + @overload + def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + @overload + def split(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... + def splitlines(self, keepends: bool = ...) -> List[str]: ... + if sys.version_info >= (3,): + def startswith(self, prefix: Union[Text, Tuple[Text, ...]], start: Optional[int] = ..., + end: Optional[int] = ...) -> bool: ... + def strip(self, chars: Optional[str] = ...) -> str: ... + else: + def startswith(self, prefix: Union[Text, Tuple[Text, ...]]) -> bool: ... + @overload + def strip(self, chars: str = ...) -> str: ... + @overload + def strip(self, chars: unicode) -> unicode: ... + def swapcase(self) -> str: ... + def title(self) -> str: ... + if sys.version_info >= (3,): + def translate(self, table: Union[Mapping[int, Union[int, str, None]], Sequence[Union[int, str, None]]]) -> str: ... + else: + def translate(self, table: Optional[AnyStr], deletechars: AnyStr = ...) -> AnyStr: ... + def upper(self) -> str: ... + def zfill(self, width: int) -> str: ... + if sys.version_info >= (3,): + @staticmethod + @overload + def maketrans(x: Union[Dict[int, _T], Dict[str, _T], Dict[Union[str, int], _T]]) -> Dict[int, _T]: ... + @staticmethod + @overload + def maketrans(x: str, y: str, z: str = ...) -> Dict[int, Union[int, None]]: ... + + if sys.version_info >= (3,): + def __add__(self, s: str) -> str: ... + else: + def __add__(self, s: AnyStr) -> AnyStr: ... + def __contains__(self, o: object) -> bool: ... + def __eq__(self, x: object) -> bool: ... + def __ge__(self, x: Text) -> bool: ... + def __getitem__(self, i: Union[int, slice]) -> str: ... + def __gt__(self, x: Text) -> bool: ... + def __hash__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + def __le__(self, x: Text) -> bool: ... + def __len__(self) -> int: ... + def __lt__(self, x: Text) -> bool: ... + def __mod__(self, x: Any) -> str: ... + def __mul__(self, n: int) -> str: ... + def __ne__(self, x: object) -> bool: ... + def __repr__(self) -> str: ... + def __rmul__(self, n: int) -> str: ... + def __str__(self) -> str: ... + def __getnewargs__(self) -> Tuple[str]: ... + + if sys.version_info < (3,): + def __getslice__(self, start: int, stop: int) -> str: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + +if sys.version_info >= (3,): + class bytes(ByteString): + @overload + def __init__(self, ints: Iterable[int]) -> None: ... + @overload + def __init__(self, string: str, encoding: str, + errors: str = ...) -> None: ... + @overload + def __init__(self, length: int) -> None: ... + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, o: SupportsBytes) -> None: ... + def capitalize(self) -> bytes: ... + def center(self, width: int, fillchar: bytes = ...) -> bytes: ... + def count(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def decode(self, encoding: str = ..., errors: str = ...) -> str: ... + def endswith(self, suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> bytes: ... + def find(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + if sys.version_info >= (3, 5): + def hex(self) -> str: ... + def index(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + if sys.version_info >= (3, 7): + def isascii(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, iterable: Iterable[Union[ByteString, memoryview]]) -> bytes: ... + def ljust(self, width: int, fillchar: bytes = ...) -> bytes: ... + def lower(self) -> bytes: ... + def lstrip(self, chars: Optional[bytes] = ...) -> bytes: ... + def partition(self, sep: bytes) -> Tuple[bytes, bytes, bytes]: ... + def replace(self, old: bytes, new: bytes, count: int = ...) -> bytes: ... + def rfind(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def rindex(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def rjust(self, width: int, fillchar: bytes = ...) -> bytes: ... + def rpartition(self, sep: bytes) -> Tuple[bytes, bytes, bytes]: ... + def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... + def rstrip(self, chars: Optional[bytes] = ...) -> bytes: ... + def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... + def splitlines(self, keepends: bool = ...) -> List[bytes]: ... + def startswith( + self, + prefix: Union[bytes, Tuple[bytes, ...]], + start: Optional[int] = ..., + end: Optional[int] = ..., + ) -> bool: ... + def strip(self, chars: Optional[bytes] = ...) -> bytes: ... + def swapcase(self) -> bytes: ... + def title(self) -> bytes: ... + def translate(self, table: Optional[bytes], delete: bytes = ...) -> bytes: ... + def upper(self) -> bytes: ... + def zfill(self, width: int) -> bytes: ... + @classmethod + def fromhex(cls, s: str) -> bytes: ... + @classmethod + def maketrans(cls, frm: bytes, to: bytes) -> bytes: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __hash__(self) -> int: ... + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> bytes: ... + def __add__(self, s: bytes) -> bytes: ... + def __mul__(self, n: int) -> bytes: ... + def __rmul__(self, n: int) -> bytes: ... + if sys.version_info >= (3, 5): + def __mod__(self, value: Any) -> bytes: ... + def __contains__(self, o: object) -> bool: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: bytes) -> bool: ... + def __le__(self, x: bytes) -> bool: ... + def __gt__(self, x: bytes) -> bool: ... + def __ge__(self, x: bytes) -> bool: ... + def __getnewargs__(self) -> Tuple[bytes]: ... +else: + bytes = str + +class bytearray(MutableSequence[int], ByteString): + if sys.version_info >= (3,): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, ints: Iterable[int]) -> None: ... + @overload + def __init__(self, string: Text, encoding: Text, errors: Text = ...) -> None: ... + @overload + def __init__(self, length: int) -> None: ... + else: + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, ints: Iterable[int]) -> None: ... + @overload + def __init__(self, string: str) -> None: ... + @overload + def __init__(self, string: Text, encoding: Text, errors: Text = ...) -> None: ... + @overload + def __init__(self, length: int) -> None: ... + def capitalize(self) -> bytearray: ... + def center(self, width: int, fillchar: bytes = ...) -> bytearray: ... + if sys.version_info >= (3,): + def count(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def copy(self) -> bytearray: ... + else: + def count(self, x: str) -> int: ... + def decode(self, encoding: Text = ..., errors: Text = ...) -> str: ... + def endswith(self, suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> bytearray: ... + if sys.version_info >= (3,): + def find(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + if sys.version_info >= (3, 5): + def hex(self) -> str: ... + def index(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + else: + def find(self, sub: str, start: int = ..., end: int = ...) -> int: ... + def index(self, sub: str, start: int = ..., end: int = ...) -> int: ... + def insert(self, index: int, object: int) -> None: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + if sys.version_info >= (3, 7): + def isascii(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + if sys.version_info >= (3,): + def join(self, iterable: Iterable[Union[ByteString, memoryview]]) -> bytearray: ... + def ljust(self, width: int, fillchar: bytes = ...) -> bytearray: ... + else: + def join(self, iterable: Iterable[str]) -> bytearray: ... + def ljust(self, width: int, fillchar: str = ...) -> bytearray: ... + def lower(self) -> bytearray: ... + def lstrip(self, chars: Optional[bytes] = ...) -> bytearray: ... + def partition(self, sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... + def replace(self, old: bytes, new: bytes, count: int = ...) -> bytearray: ... + if sys.version_info >= (3,): + def rfind(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def rindex(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + else: + def rfind(self, sub: bytes, start: int = ..., end: int = ...) -> int: ... + def rindex(self, sub: bytes, start: int = ..., end: int = ...) -> int: ... + def rjust(self, width: int, fillchar: bytes = ...) -> bytearray: ... + def rpartition(self, sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... + def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... + def rstrip(self, chars: Optional[bytes] = ...) -> bytearray: ... + def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... + def splitlines(self, keepends: bool = ...) -> List[bytearray]: ... + def startswith( + self, + prefix: Union[bytes, Tuple[bytes, ...]], + start: Optional[int] = ..., + end: Optional[int] = ..., + ) -> bool: ... + def strip(self, chars: Optional[bytes] = ...) -> bytearray: ... + def swapcase(self) -> bytearray: ... + def title(self) -> bytearray: ... + if sys.version_info >= (3,): + def translate(self, table: Optional[bytes], delete: bytes = ...) -> bytearray: ... + else: + def translate(self, table: str) -> bytearray: ... + def upper(self) -> bytearray: ... + def zfill(self, width: int) -> bytearray: ... + @staticmethod + def fromhex(s: str) -> bytearray: ... + if sys.version_info >= (3,): + @classmethod + def maketrans(cls, frm: bytes, to: bytes) -> bytes: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __hash__(self) -> int: ... + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> bytearray: ... + @overload + def __setitem__(self, i: int, x: int) -> None: ... + @overload + def __setitem__(self, s: slice, x: Union[Iterable[int], bytes]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + if sys.version_info < (3,): + def __getslice__(self, start: int, stop: int) -> bytearray: ... + def __setslice__(self, start: int, stop: int, x: Union[Sequence[int], str]) -> None: ... + def __delslice__(self, start: int, stop: int) -> None: ... + def __add__(self, s: bytes) -> bytearray: ... + if sys.version_info >= (3,): + def __iadd__(self, s: Iterable[int]) -> bytearray: ... + def __mul__(self, n: int) -> bytearray: ... + if sys.version_info >= (3,): + def __rmul__(self, n: int) -> bytearray: ... + def __imul__(self, n: int) -> bytearray: ... + if sys.version_info >= (3, 5): + def __mod__(self, value: Any) -> bytes: ... + def __contains__(self, o: object) -> bool: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: bytes) -> bool: ... + def __le__(self, x: bytes) -> bool: ... + def __gt__(self, x: bytes) -> bool: ... + def __ge__(self, x: bytes) -> bool: ... + +if sys.version_info >= (3,): + _mv_container_type = int +else: + _mv_container_type = str + +class memoryview(Sized, Container[_mv_container_type]): + format: str + itemsize: int + shape: Optional[Tuple[int, ...]] + strides: Optional[Tuple[int, ...]] + suboffsets: Optional[Tuple[int, ...]] + readonly: bool + ndim: int + + if sys.version_info >= (3,): + c_contiguous: bool + f_contiguous: bool + contiguous: bool + def __init__(self, obj: Union[bytes, bytearray, memoryview]) -> None: ... + def __enter__(self) -> memoryview: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> bool: ... + else: + def __init__(self, obj: Union[bytes, bytearray, buffer, memoryview]) -> None: ... + + @overload + def __getitem__(self, i: int) -> _mv_container_type: ... + @overload + def __getitem__(self, s: slice) -> memoryview: ... + + def __contains__(self, x: object) -> bool: ... + def __iter__(self) -> Iterator[_mv_container_type]: ... + def __len__(self) -> int: ... + + @overload + def __setitem__(self, i: int, o: bytes) -> None: ... + @overload + def __setitem__(self, s: slice, o: Sequence[bytes]) -> None: ... + @overload + def __setitem__(self, s: slice, o: memoryview) -> None: ... + + def tobytes(self) -> bytes: ... + def tolist(self) -> List[int]: ... + + if sys.version_info >= (3, 5): + def hex(self) -> str: ... + +class bool(int): + def __init__(self, o: object = ...) -> None: ... + @overload + def __and__(self, x: bool) -> bool: ... + @overload + def __and__(self, x: int) -> int: ... + @overload + def __or__(self, x: bool) -> bool: ... + @overload + def __or__(self, x: int) -> int: ... + @overload + def __xor__(self, x: bool) -> bool: ... + @overload + def __xor__(self, x: int) -> int: ... + @overload + def __rand__(self, x: bool) -> bool: ... + @overload + def __rand__(self, x: int) -> int: ... + @overload + def __ror__(self, x: bool) -> bool: ... + @overload + def __ror__(self, x: int) -> int: ... + @overload + def __rxor__(self, x: bool) -> bool: ... + @overload + def __rxor__(self, x: int) -> int: ... + def __getnewargs__(self) -> Tuple[int]: ... + +class slice(object): + start: Optional[int] + step: Optional[int] + stop: Optional[int] + @overload + def __init__(self, stop: Optional[int]) -> None: ... + @overload + def __init__(self, start: Optional[int], stop: Optional[int], step: Optional[int] = ...) -> None: ... + def indices(self, len: int) -> Tuple[int, int, int]: ... + +class tuple(Sequence[_T_co], Generic[_T_co]): + def __new__(cls: Type[_T], iterable: Iterable[_T_co] = ...) -> _T: ... + def __len__(self) -> int: ... + def __contains__(self, x: object) -> bool: ... + @overload + def __getitem__(self, x: int) -> _T_co: ... + @overload + def __getitem__(self, x: slice) -> Tuple[_T_co, ...]: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __lt__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __le__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __gt__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __ge__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __add__(self, x: Tuple[_T_co, ...]) -> Tuple[_T_co, ...]: ... + def __mul__(self, n: int) -> Tuple[_T_co, ...]: ... + def __rmul__(self, n: int) -> Tuple[_T_co, ...]: ... + def count(self, x: Any) -> int: ... + if sys.version_info >= (3, 5): + def index(self, x: Any, start: int = ..., end: int = ...) -> int: ... + else: + def index(self, x: Any) -> int: ... + +class function: + # TODO not defined in builtins! + __name__: str + __module__: str + if sys.version_info >= (3,): + __qualname__: str + __code__: CodeType + __annotations__: Dict[str, Any] + +class list(MutableSequence[_T], Generic[_T]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T]) -> None: ... + if sys.version_info >= (3,): + def clear(self) -> None: ... + def copy(self) -> List[_T]: ... + def append(self, object: _T) -> None: ... + def extend(self, iterable: Iterable[_T]) -> None: ... + def pop(self, index: int = ...) -> _T: ... + def index(self, object: _T, start: int = ..., stop: int = ...) -> int: ... + def count(self, object: _T) -> int: ... + def insert(self, index: int, object: _T) -> None: ... + def remove(self, object: _T) -> None: ... + def reverse(self) -> None: ... + if sys.version_info >= (3,): + def sort(self, *, key: Optional[Callable[[_T], Any]] = ..., reverse: bool = ...) -> None: ... + else: + def sort(self, cmp: Callable[[_T, _T], Any] = ..., key: Callable[[_T], Any] = ..., reverse: bool = ...) -> None: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + def __hash__(self) -> int: ... + @overload + def __getitem__(self, i: int) -> _T: ... + @overload + def __getitem__(self, s: slice) -> List[_T]: ... + @overload + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + if sys.version_info < (3,): + def __getslice__(self, start: int, stop: int) -> List[_T]: ... + def __setslice__(self, start: int, stop: int, o: Sequence[_T]) -> None: ... + def __delslice__(self, start: int, stop: int) -> None: ... + def __add__(self, x: List[_T]) -> List[_T]: ... + def __iadd__(self: _S, x: Iterable[_T]) -> _S: ... + def __mul__(self, n: int) -> List[_T]: ... + def __rmul__(self, n: int) -> List[_T]: ... + if sys.version_info >= (3,): + def __imul__(self: _S, n: int) -> _S: ... + def __contains__(self, o: object) -> bool: ... + def __reversed__(self) -> Iterator[_T]: ... + def __gt__(self, x: List[_T]) -> bool: ... + def __ge__(self, x: List[_T]) -> bool: ... + def __lt__(self, x: List[_T]) -> bool: ... + def __le__(self, x: List[_T]) -> bool: ... + +class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): + # NOTE: Keyword arguments are special. If they are used, _KT must include + # str, but we have no way of enforcing it here. + @overload + def __init__(self, **kwargs: _VT) -> None: ... + @overload + def __init__(self, map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def __init__(self, iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + + def __new__(cls: Type[_T1], *args: Any, **kwargs: Any) -> _T1: ... + + if sys.version_info < (3,): + def has_key(self, k: _KT) -> bool: ... + def clear(self) -> None: ... + def copy(self) -> Dict[_KT, _VT]: ... + def popitem(self) -> Tuple[_KT, _VT]: ... + def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ... + @overload + def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + @overload + def update(self, **kwargs: _VT) -> None: ... + if sys.version_info >= (3,): + def keys(self) -> KeysView[_KT]: ... + def values(self) -> ValuesView[_VT]: ... + def items(self) -> ItemsView[_KT, _VT]: ... + else: + def iterkeys(self) -> Iterator[_KT]: ... + def itervalues(self) -> Iterator[_VT]: ... + def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... + def viewkeys(self) -> KeysView[_KT]: ... + def viewvalues(self) -> ValuesView[_VT]: ... + def viewitems(self) -> ItemsView[_KT, _VT]: ... + @staticmethod + @overload + def fromkeys(seq: Iterable[_T]) -> Dict[_T, Any]: ... # TODO: Actually a class method (mypy/issues#328) + @staticmethod + @overload + def fromkeys(seq: Iterable[_T], value: _S) -> Dict[_T, _S]: ... + def __len__(self) -> int: ... + def __getitem__(self, k: _KT) -> _VT: ... + def __setitem__(self, k: _KT, v: _VT) -> None: ... + def __delitem__(self, v: _KT) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + def __str__(self) -> str: ... + +class set(MutableSet[_T], Generic[_T]): + def __init__(self, iterable: Iterable[_T] = ...) -> None: ... + def add(self, element: _T) -> None: ... + def clear(self) -> None: ... + def copy(self) -> Set[_T]: ... + def difference(self, *s: Iterable[Any]) -> Set[_T]: ... + def difference_update(self, *s: Iterable[Any]) -> None: ... + def discard(self, element: _T) -> None: ... + def intersection(self, *s: Iterable[Any]) -> Set[_T]: ... + def intersection_update(self, *s: Iterable[Any]) -> None: ... + def isdisjoint(self, s: Iterable[Any]) -> bool: ... + def issubset(self, s: Iterable[Any]) -> bool: ... + def issuperset(self, s: Iterable[Any]) -> bool: ... + def pop(self) -> _T: ... + def remove(self, element: _T) -> None: ... + def symmetric_difference(self, s: Iterable[_T]) -> Set[_T]: ... + def symmetric_difference_update(self, s: Iterable[_T]) -> None: ... + def union(self, *s: Iterable[_T]) -> Set[_T]: ... + def update(self, *s: Iterable[_T]) -> None: ... + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + def __and__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __iand__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __or__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __ior__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __sub__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __isub__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __xor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __ixor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __le__(self, s: AbstractSet[object]) -> bool: ... + def __lt__(self, s: AbstractSet[object]) -> bool: ... + def __ge__(self, s: AbstractSet[object]) -> bool: ... + def __gt__(self, s: AbstractSet[object]) -> bool: ... + +class frozenset(AbstractSet[_T], Generic[_T]): + def __init__(self, iterable: Iterable[_T] = ...) -> None: ... + def copy(self) -> FrozenSet[_T]: ... + def difference(self, *s: Iterable[object]) -> FrozenSet[_T]: ... + def intersection(self, *s: Iterable[object]) -> FrozenSet[_T]: ... + def isdisjoint(self, s: Iterable[_T]) -> bool: ... + def issubset(self, s: Iterable[object]) -> bool: ... + def issuperset(self, s: Iterable[object]) -> bool: ... + def symmetric_difference(self, s: Iterable[_T]) -> FrozenSet[_T]: ... + def union(self, *s: Iterable[_T]) -> FrozenSet[_T]: ... + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + def __and__(self, s: AbstractSet[_T]) -> FrozenSet[_T]: ... + def __or__(self, s: AbstractSet[_S]) -> FrozenSet[Union[_T, _S]]: ... + def __sub__(self, s: AbstractSet[_T]) -> FrozenSet[_T]: ... + def __xor__(self, s: AbstractSet[_S]) -> FrozenSet[Union[_T, _S]]: ... + def __le__(self, s: AbstractSet[object]) -> bool: ... + def __lt__(self, s: AbstractSet[object]) -> bool: ... + def __ge__(self, s: AbstractSet[object]) -> bool: ... + def __gt__(self, s: AbstractSet[object]) -> bool: ... + +class enumerate(Iterator[Tuple[int, _T]], Generic[_T]): + def __init__(self, iterable: Iterable[_T], start: int = ...) -> None: ... + def __iter__(self) -> Iterator[Tuple[int, _T]]: ... + if sys.version_info >= (3,): + def __next__(self) -> Tuple[int, _T]: ... + else: + def next(self) -> Tuple[int, _T]: ... + +if sys.version_info >= (3,): + class range(Sequence[int]): + start: int + stop: int + step: int + @overload + def __init__(self, stop: int) -> None: ... + @overload + def __init__(self, start: int, stop: int, step: int = ...) -> None: ... + def count(self, value: int) -> int: ... + def index(self, value: int, start: int = ..., stop: Optional[int] = ...) -> int: ... + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[int]: ... + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> range: ... + def __repr__(self) -> str: ... + def __reversed__(self) -> Iterator[int]: ... +else: + class xrange(Sized, Iterable[int], Reversible[int]): + @overload + def __init__(self, stop: int) -> None: ... + @overload + def __init__(self, start: int, stop: int, step: int = ...) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __getitem__(self, i: int) -> int: ... + def __reversed__(self) -> Iterator[int]: ... + +class property(object): + def __init__(self, fget: Optional[Callable[[Any], Any]] = ..., + fset: Optional[Callable[[Any, Any], None]] = ..., + fdel: Optional[Callable[[Any], None]] = ..., + doc: Optional[str] = ...) -> None: ... + def getter(self, fget: Callable[[Any], Any]) -> property: ... + def setter(self, fset: Callable[[Any, Any], None]) -> property: ... + def deleter(self, fdel: Callable[[Any], None]) -> property: ... + def __get__(self, obj: Any, type: Optional[type] = ...) -> Any: ... + def __set__(self, obj: Any, value: Any) -> None: ... + def __delete__(self, obj: Any) -> None: ... + def fget(self) -> Any: ... + def fset(self, value: Any) -> None: ... + def fdel(self) -> None: ... + +if sys.version_info < (3,): + long = int + +NotImplemented: Any + +def abs(n: SupportsAbs[_T]) -> _T: ... +def all(i: Iterable[object]) -> bool: ... +def any(i: Iterable[object]) -> bool: ... +if sys.version_info < (3,): + def apply(func: Callable[..., _T], args: Optional[Sequence[Any]] = ..., kwds: Optional[Mapping[str, Any]] = ...) -> _T: ... +if sys.version_info >= (3,): + def ascii(o: object) -> str: ... +def bin(number: int) -> str: ... +if sys.version_info >= (3, 7): + def breakpoint(*args: Any, **kws: Any) -> None: ... +def callable(o: object) -> bool: ... +def chr(code: int) -> str: ... +if sys.version_info < (3,): + def cmp(x: Any, y: Any) -> int: ... + _N1 = TypeVar('_N1', bool, int, float, complex) + def coerce(x: _N1, y: _N1) -> Tuple[_N1, _N1]: ... +if sys.version_info >= (3, 6): + # This class is to be exported as PathLike from os, + # but we define it here as _PathLike to avoid import cycle issues. + # See https://github.com/python/typeshed/pull/991#issuecomment-288160993 + class _PathLike(Generic[AnyStr]): + def __fspath__(self) -> AnyStr: ... + def compile(source: Union[str, bytes, mod], filename: Union[str, bytes, _PathLike], mode: str, flags: int = ..., dont_inherit: int = ..., optimize: int = ...) -> Any: ... +elif sys.version_info >= (3,): + def compile(source: Union[str, bytes, mod], filename: Union[str, bytes], mode: str, flags: int = ..., dont_inherit: int = ..., optimize: int = ...) -> Any: ... +else: + def compile(source: Union[Text, mod], filename: Text, mode: Text, flags: int = ..., dont_inherit: int = ...) -> Any: ... +if sys.version_info >= (3,): + def copyright() -> None: ... + def credits() -> None: ... +def delattr(o: Any, name: Text) -> None: ... +def dir(o: object = ...) -> List[str]: ... +_N2 = TypeVar('_N2', int, float) +def divmod(a: _N2, b: _N2) -> Tuple[_N2, _N2]: ... +def eval(source: Union[Text, bytes, CodeType], globals: Optional[Dict[str, Any]] = ..., locals: Optional[Mapping[str, Any]] = ...) -> Any: ... +if sys.version_info >= (3,): + def exec(object: Union[str, bytes, CodeType], globals: Optional[Dict[str, Any]] = ..., locals: Optional[Mapping[str, Any]] = ...) -> Any: ... +else: + def execfile(filename: str, globals: Optional[Dict[str, Any]] = ..., locals: Optional[Dict[str, Any]] = ...) -> None: ... +def exit(code: Any = ...) -> NoReturn: ... +if sys.version_info >= (3,): + @overload + def filter(__function: None, __iterable: Iterable[Optional[_T]]) -> Iterator[_T]: ... + @overload + def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> Iterator[_T]: ... +else: + @overload + def filter(__function: Callable[[AnyStr], Any], # type: ignore + __iterable: AnyStr) -> AnyStr: ... + @overload + def filter(__function: None, # type: ignore + __iterable: Tuple[Optional[_T], ...]) -> Tuple[_T, ...]: ... + @overload + def filter(__function: Callable[[_T], Any], # type: ignore + __iterable: Tuple[_T, ...]) -> Tuple[_T, ...]: ... + @overload + def filter(__function: None, + __iterable: Iterable[Optional[_T]]) -> List[_T]: ... + @overload + def filter(__function: Callable[[_T], Any], + __iterable: Iterable[_T]) -> List[_T]: ... +def format(o: object, format_spec: str = ...) -> str: ... # TODO unicode +def getattr(o: Any, name: Text, default: Any = ...) -> Any: ... +def globals() -> Dict[str, Any]: ... +def hasattr(o: Any, name: Text) -> bool: ... +def hash(o: object) -> int: ... +if sys.version_info >= (3,): + def help(*args: Any, **kwds: Any) -> None: ... +def hex(i: int) -> str: ... # TODO __index__ +def id(o: object) -> int: ... +if sys.version_info >= (3,): + def input(prompt: Any = ...) -> str: ... +else: + def input(prompt: Any = ...) -> Any: ... + def intern(string: str) -> str: ... +@overload +def iter(iterable: Iterable[_T]) -> Iterator[_T]: ... +@overload +def iter(function: Callable[[], _T], sentinel: _T) -> Iterator[_T]: ... +def isinstance(o: object, t: Union[type, Tuple[Union[type, Tuple], ...]]) -> bool: ... +def issubclass(cls: type, classinfo: Union[type, Tuple[Union[type, Tuple], ...]]) -> bool: ... +def len(o: Sized) -> int: ... +if sys.version_info >= (3,): + def license() -> None: ... +def locals() -> Dict[str, Any]: ... +if sys.version_info >= (3,): + @overload + def map(func: Callable[[_T1], _S], iter1: Iterable[_T1]) -> Iterator[_S]: ... + @overload + def map(func: Callable[[_T1, _T2], _S], iter1: Iterable[_T1], + iter2: Iterable[_T2]) -> Iterator[_S]: ... + @overload + def map(func: Callable[[_T1, _T2, _T3], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> Iterator[_S]: ... + @overload + def map(func: Callable[[_T1, _T2, _T3, _T4], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> Iterator[_S]: ... + @overload + def map(func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5]) -> Iterator[_S]: ... + @overload + def map(func: Callable[..., _S], + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + *iterables: Iterable[Any]) -> Iterator[_S]: ... +else: + @overload + def map(func: None, iter1: Iterable[_T1]) -> List[_T1]: ... + @overload + def map(func: None, + iter1: Iterable[_T1], + iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... + @overload + def map(func: None, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... + @overload + def map(func: None, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def map(func: None, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5]) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def map(func: None, + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + *iterables: Iterable[Any]) -> List[Tuple[Any, ...]]: ... + @overload + def map(func: Callable[[_T1], _S], iter1: Iterable[_T1]) -> List[_S]: ... + @overload + def map(func: Callable[[_T1, _T2], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2]) -> List[_S]: ... + @overload + def map(func: Callable[[_T1, _T2, _T3], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> List[_S]: ... + @overload + def map(func: Callable[[_T1, _T2, _T3, _T4], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> List[_S]: ... + @overload + def map(func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5]) -> List[_S]: ... + @overload + def map(func: Callable[..., _S], + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + *iterables: Iterable[Any]) -> List[_S]: ... +if sys.version_info >= (3,): + @overload + def max(_arg1: _T, _arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... + @overload + def max(_iterable: Iterable[_T], *, key: Callable[[_T], Any] = ..., default: _VT = ...) -> Union[_T, _VT]: ... +else: + @overload + def max(_arg1: _T, _arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... + @overload + def max(_iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... +if sys.version_info >= (3,): + @overload + def min(_arg1: _T, _arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... + @overload + def min(_iterable: Iterable[_T], *, key: Callable[[_T], Any] = ..., default: _VT = ...) -> Union[_T, _VT]: ... +else: + @overload + def min(_arg1: _T, _arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... + @overload + def min(_iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... +@overload +def next(i: Iterator[_T]) -> _T: ... +@overload +def next(i: Iterator[_T], default: _VT) -> Union[_T, _VT]: ... +def oct(i: int) -> str: ... # TODO __index__ + +if sys.version_info >= (3, 6): + def open(file: Union[str, bytes, int, _PathLike], mode: str = ..., buffering: int = ..., encoding: Optional[str] = ..., + errors: Optional[str] = ..., newline: Optional[str] = ..., closefd: bool = ...) -> IO[Any]: ... +elif sys.version_info >= (3,): + def open(file: Union[str, bytes, int], mode: str = ..., buffering: int = ..., encoding: Optional[str] = ..., + errors: Optional[str] = ..., newline: Optional[str] = ..., closefd: bool = ...) -> IO[Any]: ... +else: + def open(file: Union[unicode, int], mode: unicode = ..., buffering: int = ...) -> BinaryIO: ... + +def ord(c: Union[Text, bytes]) -> int: ... +if sys.version_info >= (3,): + def print(*values: Any, sep: Text = ..., end: Text = ..., file: Optional[IO[str]] = ..., flush: bool = ...) -> None: ... +else: + # This is only available after from __future__ import print_function. + def print(*values: Any, sep: Text = ..., end: Text = ..., file: Optional[IO[Any]] = ...) -> None: ... +@overload +def pow(x: int, y: int) -> Any: ... # The return type can be int or float, depending on y +@overload +def pow(x: int, y: int, z: int) -> Any: ... +@overload +def pow(x: float, y: float) -> float: ... +@overload +def pow(x: float, y: float, z: float) -> float: ... +def quit(code: Optional[int] = ...) -> None: ... +if sys.version_info < (3,): + def range(x: int, y: int = ..., step: int = ...) -> List[int]: ... + def raw_input(prompt: Any = ...) -> str: ... + @overload + def reduce(function: Callable[[_T, _S], _T], iterable: Iterable[_S], initializer: _T) -> _T: ... + @overload + def reduce(function: Callable[[_T, _T], _T], iterable: Iterable[_T]) -> _T: ... + def reload(module: Any) -> Any: ... +@overload +def reversed(object: Sequence[_T]) -> Iterator[_T]: ... +@overload +def reversed(object: Reversible[_T]) -> Iterator[_T]: ... +def repr(o: object) -> str: ... +if sys.version_info >= (3,): + @overload + def round(number: float) -> int: ... + @overload + def round(number: float, ndigits: None) -> int: ... + @overload + def round(number: float, ndigits: int) -> float: ... + @overload + def round(number: SupportsRound[_T]) -> int: ... + @overload + def round(number: SupportsRound[_T], ndigits: None) -> int: ... # type: ignore + @overload + def round(number: SupportsRound[_T], ndigits: int) -> _T: ... +else: + @overload + def round(number: float) -> float: ... + @overload + def round(number: float, ndigits: int) -> float: ... + @overload + def round(number: SupportsRound[_T]) -> _T: ... + @overload + def round(number: SupportsRound[_T], ndigits: int) -> _T: ... +def setattr(object: Any, name: Text, value: Any) -> None: ... +if sys.version_info >= (3,): + def sorted(iterable: Iterable[_T], *, + key: Optional[Callable[[_T], Any]] = ..., + reverse: bool = ...) -> List[_T]: ... +else: + def sorted(iterable: Iterable[_T], *, + cmp: Callable[[_T, _T], int] = ..., + key: Callable[[_T], Any] = ..., + reverse: bool = ...) -> List[_T]: ... +@overload +def sum(iterable: Iterable[_T]) -> Union[_T, int]: ... +@overload +def sum(iterable: Iterable[_T], start: _S) -> Union[_T, _S]: ... +if sys.version_info < (3,): + def unichr(i: int) -> unicode: ... +def vars(object: Any = ...) -> Dict[str, Any]: ... +if sys.version_info >= (3,): + @overload + def zip(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... + @overload + def zip(iter1: Iterable[_T1], iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... + @overload + def zip(iter1: Iterable[_T1], iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... + @overload + def zip(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def zip(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], + iter4: Iterable[_T4], iter5: Iterable[_T5]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def zip(iter1: Iterable[Any], iter2: Iterable[Any], iter3: Iterable[Any], + iter4: Iterable[Any], iter5: Iterable[Any], iter6: Iterable[Any], + *iterables: Iterable[Any]) -> Iterator[Tuple[Any, ...]]: ... +else: + @overload + def zip(iter1: Iterable[_T1]) -> List[Tuple[_T1]]: ... + @overload + def zip(iter1: Iterable[_T1], + iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... + @overload + def zip(iter1: Iterable[_T1], iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... + @overload + def zip(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def zip(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], + iter4: Iterable[_T4], iter5: Iterable[_T5]) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def zip(iter1: Iterable[Any], iter2: Iterable[Any], iter3: Iterable[Any], + iter4: Iterable[Any], iter5: Iterable[Any], iter6: Iterable[Any], + *iterables: Iterable[Any]) -> List[Tuple[Any, ...]]: ... +def __import__(name: Text, globals: Dict[str, Any] = ..., locals: Dict[str, Any] = ..., + fromlist: List[str] = ..., level: int = ...) -> Any: ... + +# Actually the type of Ellipsis is , but since it's +# not exposed anywhere under that name, we make it private here. +class ellipsis: ... +Ellipsis: ellipsis + +if sys.version_info < (3,): + # TODO: buffer support is incomplete; e.g. some_string.startswith(some_buffer) doesn't type check. + _AnyBuffer = TypeVar('_AnyBuffer', str, unicode, bytearray, buffer) + + class buffer(Sized): + def __init__(self, object: _AnyBuffer, offset: int = ..., size: int = ...) -> None: ... + def __add__(self, other: _AnyBuffer) -> str: ... + def __cmp__(self, other: _AnyBuffer) -> bool: ... + def __getitem__(self, key: Union[int, slice]) -> str: ... + def __getslice__(self, i: int, j: int) -> str: ... + def __len__(self) -> int: ... + def __mul__(self, x: int) -> str: ... + +class BaseException(object): + args: Tuple[Any, ...] + if sys.version_info < (3,): + message: Any + if sys.version_info >= (3,): + __cause__: Optional[BaseException] + __context__: Optional[BaseException] + __traceback__: Optional[TracebackType] + def __init__(self, *args: object) -> None: ... + if sys.version_info < (3,): + def __getitem__(self, i: int) -> Any: ... + def __getslice__(self, start: int, stop: int) -> Tuple[Any, ...]: ... + if sys.version_info >= (3,): + def with_traceback(self, tb: Optional[TracebackType]) -> BaseException: ... + +class GeneratorExit(BaseException): ... +class KeyboardInterrupt(BaseException): ... +class SystemExit(BaseException): + code: int +class Exception(BaseException): ... +class StopIteration(Exception): + if sys.version_info >= (3,): + value: Any +if sys.version_info >= (3,): + _StandardError = Exception + class OSError(Exception): + errno: int + strerror: str + # filename, filename2 are actually Union[str, bytes, None] + filename: Any + filename2: Any + EnvironmentError = OSError + IOError = OSError +else: + class StandardError(Exception): ... + _StandardError = StandardError + class EnvironmentError(StandardError): + errno: int + strerror: str + # TODO can this be unicode? + filename: str + class OSError(EnvironmentError): ... + class IOError(EnvironmentError): ... + +class ArithmeticError(_StandardError): ... +class AssertionError(_StandardError): ... +class AttributeError(_StandardError): ... +class BufferError(_StandardError): ... +class EOFError(_StandardError): ... +class ImportError(_StandardError): + if sys.version_info >= (3,): + name: str + path: str +class LookupError(_StandardError): ... +class MemoryError(_StandardError): ... +class NameError(_StandardError): ... +class ReferenceError(_StandardError): ... +class RuntimeError(_StandardError): ... +if sys.version_info >= (3, 5): + class StopAsyncIteration(Exception): + value: Any +class SyntaxError(_StandardError): + msg: str + lineno: int + offset: Optional[int] + text: str + filename: str +class SystemError(_StandardError): ... +class TypeError(_StandardError): ... +class ValueError(_StandardError): ... + +class FloatingPointError(ArithmeticError): ... +class OverflowError(ArithmeticError): ... +class ZeroDivisionError(ArithmeticError): ... + +if sys.version_info >= (3, 6): + class ModuleNotFoundError(ImportError): ... + +class IndexError(LookupError): ... +class KeyError(LookupError): ... + +class UnboundLocalError(NameError): ... + +class WindowsError(OSError): + winerror: int +if sys.version_info >= (3,): + class BlockingIOError(OSError): + characters_written: int + class ChildProcessError(OSError): ... + class ConnectionError(OSError): ... + class BrokenPipeError(ConnectionError): ... + class ConnectionAbortedError(ConnectionError): ... + class ConnectionRefusedError(ConnectionError): ... + class ConnectionResetError(ConnectionError): ... + class FileExistsError(OSError): ... + class FileNotFoundError(OSError): ... + class InterruptedError(OSError): ... + class IsADirectoryError(OSError): ... + class NotADirectoryError(OSError): ... + class PermissionError(OSError): ... + class ProcessLookupError(OSError): ... + class TimeoutError(OSError): ... + +class NotImplementedError(RuntimeError): ... +if sys.version_info >= (3, 5): + class RecursionError(RuntimeError): ... + +class IndentationError(SyntaxError): ... +class TabError(IndentationError): ... + +class UnicodeError(ValueError): ... +class UnicodeDecodeError(UnicodeError): + encoding: str + object: bytes + start: int + end: int + reason: str + def __init__(self, __encoding: str, __object: bytes, __start: int, __end: int, + __reason: str) -> None: ... +class UnicodeEncodeError(UnicodeError): + encoding: str + object: Text + start: int + end: int + reason: str + def __init__(self, __encoding: str, __object: Text, __start: int, __end: int, + __reason: str) -> None: ... +class UnicodeTranslateError(UnicodeError): ... + +class Warning(Exception): ... +class UserWarning(Warning): ... +class DeprecationWarning(Warning): ... +class SyntaxWarning(Warning): ... +class RuntimeWarning(Warning): ... +class FutureWarning(Warning): ... +class PendingDeprecationWarning(Warning): ... +class ImportWarning(Warning): ... +class UnicodeWarning(Warning): ... +class BytesWarning(Warning): ... +if sys.version_info >= (3, 2): + class ResourceWarning(Warning): ... + +if sys.version_info < (3,): + class file(BinaryIO): + @overload + def __init__(self, file: str, mode: str = ..., buffering: int = ...) -> None: ... + @overload + def __init__(self, file: unicode, mode: str = ..., buffering: int = ...) -> None: ... + @overload + def __init__(self, file: int, mode: str = ..., buffering: int = ...) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def next(self) -> str: ... + def read(self, n: int = ...) -> str: ... + def __enter__(self) -> BinaryIO: ... + def __exit__(self, t: Optional[type] = ..., exc: Optional[BaseException] = ..., tb: Optional[Any] = ...) -> bool: ... + def flush(self) -> None: ... + def fileno(self) -> int: ... + def isatty(self) -> bool: ... + def close(self) -> None: ... + + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + def readline(self, limit: int = ...) -> str: ... + def readlines(self, hint: int = ...) -> List[str]: ... + def write(self, data: str) -> int: ... + def writelines(self, data: Iterable[str]) -> None: ... + def truncate(self, pos: Optional[int] = ...) -> int: ... diff --git a/client/typeshed-fallback/stdlib/2/_ast.pyi b/client/typeshed-fallback/stdlib/2/_ast.pyi new file mode 100644 index 000000000..8cbf6d67b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/_ast.pyi @@ -0,0 +1,328 @@ +import typing +from typing import Optional + +__version__ = ... # type: str + +PyCF_ONLY_AST = ... # type: int + +_identifier = str + +class AST: + _attributes = ... # type: typing.Tuple[str, ...] + _fields = ... # type: typing.Tuple[str, ...] + def __init__(self, *args, **kwargs) -> None: ... + +class mod(AST): + ... + +class Module(mod): + body = ... # type: typing.List[stmt] + +class Interactive(mod): + body = ... # type: typing.List[stmt] + +class Expression(mod): + body = ... # type: expr + +class Suite(mod): + body = ... # type: typing.List[stmt] + + +class stmt(AST): + lineno = ... # type: int + col_offset = ... # type: int + +class FunctionDef(stmt): + name = ... # type: _identifier + args = ... # type: arguments + body = ... # type: typing.List[stmt] + decorator_list = ... # type: typing.List[expr] + +class ClassDef(stmt): + name = ... # type: _identifier + bases = ... # type: typing.List[expr] + body = ... # type: typing.List[stmt] + decorator_list = ... # type: typing.List[expr] + +class Return(stmt): + value = ... # type: Optional[expr] + +class Delete(stmt): + targets = ... # type: typing.List[expr] + +class Assign(stmt): + targets = ... # type: typing.List[expr] + value = ... # type: expr + +class AugAssign(stmt): + target = ... # type: expr + op = ... # type: operator + value = ... # type: expr + +class Print(stmt): + dest = ... # type: Optional[expr] + values = ... # type: typing.List[expr] + nl = ... # type: bool + +class For(stmt): + target = ... # type: expr + iter = ... # type: expr + body = ... # type: typing.List[stmt] + orelse = ... # type: typing.List[stmt] + +class While(stmt): + test = ... # type: expr + body = ... # type: typing.List[stmt] + orelse = ... # type: typing.List[stmt] + +class If(stmt): + test = ... # type: expr + body = ... # type: typing.List[stmt] + orelse = ... # type: typing.List[stmt] + +class With(stmt): + context_expr = ... # type: expr + optional_vars = ... # type: Optional[expr] + body = ... # type: typing.List[stmt] + +class Raise(stmt): + type = ... # type: Optional[expr] + inst = ... # type: Optional[expr] + tback = ... # type: Optional[expr] + +class TryExcept(stmt): + body = ... # type: typing.List[stmt] + handlers = ... # type: typing.List[ExceptHandler] + orelse = ... # type: typing.List[stmt] + +class TryFinally(stmt): + body = ... # type: typing.List[stmt] + finalbody = ... # type: typing.List[stmt] + +class Assert(stmt): + test = ... # type: expr + msg = ... # type: Optional[expr] + +class Import(stmt): + names = ... # type: typing.List[alias] + +class ImportFrom(stmt): + module = ... # type: Optional[_identifier] + names = ... # type: typing.List[alias] + level = ... # type: Optional[int] + +class Exec(stmt): + body = ... # type: expr + globals = ... # type: Optional[expr] + locals = ... # type: Optional[expr] + +class Global(stmt): + names = ... # type: typing.List[_identifier] + +class Expr(stmt): + value = ... # type: expr + +class Pass(stmt): ... +class Break(stmt): ... +class Continue(stmt): ... + + +class slice(AST): + ... + +_slice = slice # this lets us type the variable named 'slice' below + +class Slice(slice): + lower = ... # type: Optional[expr] + upper = ... # type: Optional[expr] + step = ... # type: Optional[expr] + +class ExtSlice(slice): + dims = ... # type: typing.List[slice] + +class Index(slice): + value = ... # type: expr + +class Ellipsis(slice): ... + + +class expr(AST): + lineno = ... # type: int + col_offset = ... # type: int + +class BoolOp(expr): + op = ... # type: boolop + values = ... # type: typing.List[expr] + +class BinOp(expr): + left = ... # type: expr + op = ... # type: operator + right = ... # type: expr + +class UnaryOp(expr): + op = ... # type: unaryop + operand = ... # type: expr + +class Lambda(expr): + args = ... # type: arguments + body = ... # type: expr + +class IfExp(expr): + test = ... # type: expr + body = ... # type: expr + orelse = ... # type: expr + +class Dict(expr): + keys = ... # type: typing.List[expr] + values = ... # type: typing.List[expr] + +class Set(expr): + elts = ... # type: typing.List[expr] + +class ListComp(expr): + elt = ... # type: expr + generators = ... # type: typing.List[comprehension] + +class SetComp(expr): + elt = ... # type: expr + generators = ... # type: typing.List[comprehension] + +class DictComp(expr): + key = ... # type: expr + value = ... # type: expr + generators = ... # type: typing.List[comprehension] + +class GeneratorExp(expr): + elt = ... # type: expr + generators = ... # type: typing.List[comprehension] + +class Yield(expr): + value = ... # type: Optional[expr] + +class Compare(expr): + left = ... # type: expr + ops = ... # type: typing.List[cmpop] + comparators = ... # type: typing.List[expr] + +class Call(expr): + func = ... # type: expr + args = ... # type: typing.List[expr] + keywords = ... # type: typing.List[keyword] + starargs = ... # type: Optional[expr] + kwargs = ... # type: Optional[expr] + +class Repr(expr): + value = ... # type: expr + +class Num(expr): + n = ... # type: float + +class Str(expr): + s = ... # type: str + +class Attribute(expr): + value = ... # type: expr + attr = ... # type: _identifier + ctx = ... # type: expr_context + +class Subscript(expr): + value = ... # type: expr + slice = ... # type: _slice + ctx = ... # type: expr_context + +class Name(expr): + id = ... # type: _identifier + ctx = ... # type: expr_context + +class List(expr): + elts = ... # type: typing.List[expr] + ctx = ... # type: expr_context + +class Tuple(expr): + elts = ... # type: typing.List[expr] + ctx = ... # type: expr_context + + +class expr_context(AST): + ... + +class AugLoad(expr_context): ... +class AugStore(expr_context): ... +class Del(expr_context): ... +class Load(expr_context): ... +class Param(expr_context): ... +class Store(expr_context): ... + + +class boolop(AST): + ... + +class And(boolop): ... +class Or(boolop): ... + +class operator(AST): + ... + +class Add(operator): ... +class BitAnd(operator): ... +class BitOr(operator): ... +class BitXor(operator): ... +class Div(operator): ... +class FloorDiv(operator): ... +class LShift(operator): ... +class Mod(operator): ... +class Mult(operator): ... +class Pow(operator): ... +class RShift(operator): ... +class Sub(operator): ... + +class unaryop(AST): + ... + +class Invert(unaryop): ... +class Not(unaryop): ... +class UAdd(unaryop): ... +class USub(unaryop): ... + +class cmpop(AST): + ... + +class Eq(cmpop): ... +class Gt(cmpop): ... +class GtE(cmpop): ... +class In(cmpop): ... +class Is(cmpop): ... +class IsNot(cmpop): ... +class Lt(cmpop): ... +class LtE(cmpop): ... +class NotEq(cmpop): ... +class NotIn(cmpop): ... + + +class comprehension(AST): + target = ... # type: expr + iter = ... # type: expr + ifs = ... # type: typing.List[expr] + + +class ExceptHandler(AST): + type = ... # type: Optional[expr] + name = ... # type: Optional[expr] + body = ... # type: typing.List[stmt] + lineno = ... # type: int + col_offset = ... # type: int + + +class arguments(AST): + args = ... # type: typing.List[expr] + vararg = ... # type: Optional[_identifier] + kwarg = ... # type: Optional[_identifier] + defaults = ... # type: typing.List[expr] + +class keyword(AST): + arg = ... # type: _identifier + value = ... # type: expr + +class alias(AST): + name = ... # type: _identifier + asname = ... # type: Optional[_identifier] diff --git a/client/typeshed-fallback/stdlib/2/_collections.pyi b/client/typeshed-fallback/stdlib/2/_collections.pyi new file mode 100644 index 000000000..fb90bc86f --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/_collections.pyi @@ -0,0 +1,41 @@ +"""Stub file for the '_collections' module.""" + +from typing import Any, Generic, Iterator, TypeVar, Optional, Union + +class defaultdict(dict): + default_factory = ... # type: None + def __init__(self, default: Any = ..., init: Any = ...) -> None: ... + def __missing__(self, key) -> Any: + raise KeyError() + def __copy__(self) -> defaultdict: ... + def copy(self) -> defaultdict: ... + +_T = TypeVar('_T') +_T2 = TypeVar('_T2') + +class deque(Generic[_T]): + maxlen = ... # type: Optional[int] + def __init__(self, iterable: Iterator[_T] = ..., maxlen: int = ...) -> None: ... + def append(self, x: _T) -> None: ... + def appendleft(self, x: _T) -> None: ... + def clear(self) -> None: ... + def count(self, x: Any) -> int: ... + def extend(self, iterable: Iterator[_T]) -> None: ... + def extendleft(self, iterable: Iterator[_T]) -> None: ... + def pop(self) -> _T: + raise IndexError() + def popleft(self) -> _T: + raise IndexError() + def remove(self, value: _T) -> None: + raise IndexError() + def reverse(self) -> None: ... + def rotate(self, n: int = ...) -> None: ... + def __contains__(self, o: Any) -> bool: ... + def __copy__(self) -> deque[_T]: ... + def __getitem__(self, i: int) -> _T: + raise IndexError() + def __iadd__(self, other: deque[_T2]) -> deque[Union[_T, _T2]]: ... + def __iter__(self) -> Iterator[_T]: ... + def __len__(self) -> int: ... + def __reversed__(self) -> Iterator[_T]: ... + def __setitem__(self, i: int, x: _T) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/_functools.pyi b/client/typeshed-fallback/stdlib/2/_functools.pyi new file mode 100644 index 000000000..555d3e1ae --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/_functools.pyi @@ -0,0 +1,20 @@ +"""Stub file for the '_functools' module.""" + +from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Tuple, overload + +_T = TypeVar("_T") +_S = TypeVar("_S") + +@overload +def reduce(function: Callable[[_T, _T], _T], + sequence: Iterable[_T]) -> _T: ... +@overload +def reduce(function: Callable[[_T, _S], _T], + sequence: Iterable[_S], initial: _T) -> _T: ... + +class partial(object): + func = ... # type: Callable[..., Any] + args = ... # type: Tuple[Any, ...] + keywords = ... # type: Dict[str, Any] + def __init__(self, func: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... diff --git a/client/typeshed-fallback/stdlib/2/_hotshot.pyi b/client/typeshed-fallback/stdlib/2/_hotshot.pyi new file mode 100644 index 000000000..8a9c8d72b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/_hotshot.pyi @@ -0,0 +1,34 @@ +"""Stub file for the '_hotshot' module.""" +# This is an autogenerated file. It serves as a starting point +# for a more precise manual annotation of this module. +# Feel free to edit the source below, but remove this header when you do. + +from typing import Any, List, Tuple, Dict, Generic + +def coverage(a: str) -> Any: ... + +def logreader(a: str) -> LogReaderType: + raise IOError() + raise RuntimeError() + +def profiler(a: str, *args, **kwargs) -> Any: + raise IOError() + +def resolution() -> tuple: ... + + +class LogReaderType(object): + def close(self) -> None: ... + def fileno(self) -> int: + raise ValueError() + +class ProfilerType(object): + def addinfo(self, a: str, b: str) -> None: ... + def close(self) -> None: ... + def fileno(self) -> int: + raise ValueError() + def runcall(self, *args, **kwargs) -> Any: ... + def runcode(self, a, b, *args, **kwargs) -> Any: + raise TypeError() + def start(self) -> None: ... + def stop(self) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/_io.pyi b/client/typeshed-fallback/stdlib/2/_io.pyi new file mode 100644 index 000000000..caadf2a21 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/_io.pyi @@ -0,0 +1,183 @@ +from typing import Any, AnyStr, BinaryIO, IO, Text, TextIO, Iterable, Iterator, List, Optional, Type, Tuple, TypeVar, Union +from mmap import mmap +from types import TracebackType + +_bytearray_like = Union[bytearray, mmap] + +DEFAULT_BUFFER_SIZE = ... # type: int + +class BlockingIOError(IOError): + characters_written = ... # type: int + +class UnsupportedOperation(ValueError, IOError): ... + +_T = TypeVar("_T") + +class _IOBase(BinaryIO): + @property + def closed(self) -> bool: ... + def _checkClosed(self) -> None: ... + def _checkReadable(self) -> None: ... + def _checkSeekable(self) -> None: ... + def _checkWritable(self) -> None: ... + # All these methods are concrete here (you can instantiate this) + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def writable(self) -> bool: ... + def __enter__(self: _T) -> _T: ... + def __exit__(self, t: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[Any]) -> bool: ... + def __iter__(self: _T) -> _T: ... + # The parameter type of writelines[s]() is determined by that of write(): + def writelines(self, lines: Iterable[bytes]) -> None: ... + # The return type of readline[s]() and next() is determined by that of read(): + def readline(self, limit: int = ...) -> bytes: ... + def readlines(self, hint: int = ...) -> List[bytes]: ... + def next(self) -> bytes: ... + # These don't actually exist but we need to pretend that it does + # so that this class is concrete. + def write(self, s: bytes) -> int: ... + def read(self, n: int = ...) -> bytes: ... + +class _BufferedIOBase(_IOBase): + def read1(self, n: int) -> bytes: ... + def read(self, size: int = ...) -> bytes: ... + def readinto(self, buffer: _bytearray_like) -> int: ... + def write(self, s: bytes) -> int: ... + def detach(self) -> _IOBase: ... + +class BufferedRWPair(_BufferedIOBase): + def __init__(self, reader: _RawIOBase, writer: _RawIOBase, + buffer_size: int = ..., max_buffer_size: int = ...) -> None: ... + def peek(self, n: int = ...) -> bytes: ... + def __enter__(self) -> BufferedRWPair: ... + +class BufferedRandom(_BufferedIOBase): + mode = ... # type: str + name = ... # type: str + raw = ... # type: _IOBase + def __init__(self, raw: _IOBase, + buffer_size: int = ..., + max_buffer_size: int = ...) -> None: ... + def peek(self, n: int = ...) -> bytes: ... + +class BufferedReader(_BufferedIOBase): + mode = ... # type: str + name = ... # type: str + raw = ... # type: _IOBase + def __init__(self, raw: _IOBase, buffer_size: int = ...) -> None: ... + def peek(self, n: int = ...) -> bytes: ... + +class BufferedWriter(_BufferedIOBase): + name = ... # type: str + raw = ... # type: _IOBase + mode = ... # type: str + def __init__(self, raw: _IOBase, + buffer_size: int = ..., + max_buffer_size: int = ...) -> None: ... + +class BytesIO(_BufferedIOBase): + def __init__(self, initial_bytes: bytes = ...) -> None: ... + def __setstate__(self, tuple) -> None: ... + def __getstate__(self) -> tuple: ... + # BytesIO does not contain a "name" field. This workaround is necessary + # to allow BytesIO sub-classes to add this field, as it is defined + # as a read-only property on IO[]. + name: Any + def getvalue(self) -> bytes: ... + def write(self, s: bytes) -> int: ... + def writelines(self, lines: Iterable[bytes]) -> None: ... + def read1(self, size: int) -> bytes: ... + def next(self) -> bytes: ... + +class _RawIOBase(_IOBase): + def readall(self) -> str: ... + def read(self, n: int = ...) -> str: ... + +class FileIO(_RawIOBase, BytesIO): + mode = ... # type: str + closefd = ... # type: bool + def __init__(self, file: Union[str, int], mode: str = ..., closefd: bool = ...) -> None: ... + def readinto(self, buffer: _bytearray_like) -> int: ... + def write(self, pbuf: str) -> int: ... + +class IncrementalNewlineDecoder(object): + newlines = ... # type: Union[str, unicode] + def __init__(self, decoder, translate, z=...) -> None: ... + def decode(self, input, final) -> Any: ... + def getstate(self) -> Tuple[Any, int]: ... + def setstate(self, state: Tuple[Any, int]) -> None: ... + def reset(self) -> None: ... + + +# Note: In the actual _io.py, _TextIOBase inherits from _IOBase. +class _TextIOBase(TextIO): + errors = ... # type: Optional[str] + # TODO: On _TextIOBase, this is always None. But it's unicode/bytes in subclasses. + newlines = ... # type: Union[None, unicode, bytes] + encoding = ... # type: str + @property + def closed(self) -> bool: ... + def _checkClosed(self) -> None: ... + def _checkReadable(self) -> None: ... + def _checkSeekable(self) -> None: ... + def _checkWritable(self) -> None: ... + def close(self) -> None: ... + def detach(self) -> IO: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def next(self) -> unicode: ... + def read(self, size: int = ...) -> unicode: ... + def readable(self) -> bool: ... + def readline(self, limit: int = ...) -> unicode: ... + def readlines(self, hint: int = ...) -> list[unicode]: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def writable(self) -> bool: ... + def write(self, pbuf: unicode) -> int: ... + def writelines(self, lines: Iterable[unicode]) -> None: ... + def __enter__(self: _T) -> _T: ... + def __exit__(self, t: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[Any]) -> bool: ... + def __iter__(self: _T) -> _T: ... + +class StringIO(_TextIOBase): + line_buffering = ... # type: bool + def __init__(self, + initial_value: Optional[unicode] = ..., + newline: Optional[unicode] = ...) -> None: ... + def __setstate__(self, state: tuple) -> None: ... + def __getstate__(self) -> tuple: ... + # StringIO does not contain a "name" field. This workaround is necessary + # to allow StringIO sub-classes to add this field, as it is defined + # as a read-only property on IO[]. + name: Any + def getvalue(self) -> unicode: ... + +class TextIOWrapper(_TextIOBase): + name = ... # type: str + line_buffering = ... # type: bool + buffer = ... # type: BinaryIO + _CHUNK_SIZE = ... # type: int + def __init__(self, buffer: IO, + encoding: Optional[Text] = ..., + errors: Optional[Text] = ..., + newline: Optional[Text] = ..., + line_buffering: bool = ..., + write_through: bool = ...) -> None: ... + +def open(file: Union[str, unicode, int], + mode: Text = ..., + buffering: int = ..., + encoding: Optional[Text] = ..., + errors: Optional[Text] = ..., + newline: Optional[Text] = ..., + closefd: bool = ...) -> IO[Any]: ... diff --git a/client/typeshed-fallback/stdlib/2/_json.pyi b/client/typeshed-fallback/stdlib/2/_json.pyi new file mode 100644 index 000000000..028b7b229 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/_json.pyi @@ -0,0 +1,17 @@ +"""Stub file for the '_json' module.""" +# This is an autogenerated file. It serves as a starting point +# for a more precise manual annotation of this module. +# Feel free to edit the source below, but remove this header when you do. + +from typing import Any, List, Tuple, Dict, Generic + +def encode_basestring_ascii(*args, **kwargs) -> str: + raise TypeError() + +def scanstring(a, b, *args, **kwargs) -> tuple: + raise TypeError() + + +class Encoder(object): ... + +class Scanner(object): ... diff --git a/client/typeshed-fallback/stdlib/2/_md5.pyi b/client/typeshed-fallback/stdlib/2/_md5.pyi new file mode 100644 index 000000000..fb2dd8696 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/_md5.pyi @@ -0,0 +1,13 @@ +blocksize = ... # type: int +digest_size = ... # type: int + +class MD5Type(object): + name = ... # type: str + block_size = ... # type: int + digest_size = ... # type: int + def copy(self) -> MD5Type: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... + +def new(arg: str = ...) -> MD5Type: ... diff --git a/client/typeshed-fallback/stdlib/2/_sha.pyi b/client/typeshed-fallback/stdlib/2/_sha.pyi new file mode 100644 index 000000000..203cea803 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/_sha.pyi @@ -0,0 +1,15 @@ +blocksize = ... # type: int +block_size = ... # type: int +digest_size = ... # type: int + +class sha(object): # not actually exposed + name = ... # type: str + block_size = ... # type: int + digest_size = ... # type: int + digestsize = ... # type: int + def copy(self) -> sha: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... + +def new(arg: str = ...) -> sha: ... diff --git a/client/typeshed-fallback/stdlib/2/_sha256.pyi b/client/typeshed-fallback/stdlib/2/_sha256.pyi new file mode 100644 index 000000000..f882fc1bc --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/_sha256.pyi @@ -0,0 +1,23 @@ +from typing import Optional + +class sha224(object): + name = ... # type: str + block_size = ... # type: int + digest_size = ... # type: int + digestsize = ... # type: int + def __init__(self, init: Optional[str]) -> None: ... + def copy(self) -> sha224: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... + +class sha256(object): + name = ... # type: str + block_size = ... # type: int + digest_size = ... # type: int + digestsize = ... # type: int + def __init__(self, init: Optional[str]) -> None: ... + def copy(self) -> sha256: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/_sha512.pyi b/client/typeshed-fallback/stdlib/2/_sha512.pyi new file mode 100644 index 000000000..60da9f889 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/_sha512.pyi @@ -0,0 +1,23 @@ +from typing import Optional + +class sha384(object): + name = ... # type: str + block_size = ... # type: int + digest_size = ... # type: int + digestsize = ... # type: int + def __init__(self, init: Optional[str]) -> None: ... + def copy(self) -> sha384: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... + +class sha512(object): + name = ... # type: str + block_size = ... # type: int + digest_size = ... # type: int + digestsize = ... # type: int + def __init__(self, init: Optional[str]) -> None: ... + def copy(self) -> sha512: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def update(self, arg: str) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/_socket.pyi b/client/typeshed-fallback/stdlib/2/_socket.pyi new file mode 100644 index 000000000..c27261983 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/_socket.pyi @@ -0,0 +1,287 @@ +from typing import Tuple, Union, IO, Any, Optional, overload + +AF_APPLETALK = ... # type: int +AF_ASH = ... # type: int +AF_ATMPVC = ... # type: int +AF_ATMSVC = ... # type: int +AF_AX25 = ... # type: int +AF_BLUETOOTH = ... # type: int +AF_BRIDGE = ... # type: int +AF_DECnet = ... # type: int +AF_ECONET = ... # type: int +AF_INET = ... # type: int +AF_INET6 = ... # type: int +AF_IPX = ... # type: int +AF_IRDA = ... # type: int +AF_KEY = ... # type: int +AF_LLC = ... # type: int +AF_NETBEUI = ... # type: int +AF_NETLINK = ... # type: int +AF_NETROM = ... # type: int +AF_PACKET = ... # type: int +AF_PPPOX = ... # type: int +AF_ROSE = ... # type: int +AF_ROUTE = ... # type: int +AF_SECURITY = ... # type: int +AF_SNA = ... # type: int +AF_TIPC = ... # type: int +AF_UNIX = ... # type: int +AF_UNSPEC = ... # type: int +AF_WANPIPE = ... # type: int +AF_X25 = ... # type: int +AI_ADDRCONFIG = ... # type: int +AI_ALL = ... # type: int +AI_CANONNAME = ... # type: int +AI_NUMERICHOST = ... # type: int +AI_NUMERICSERV = ... # type: int +AI_PASSIVE = ... # type: int +AI_V4MAPPED = ... # type: int +BDADDR_ANY = ... # type: str +BDADDR_LOCAL = ... # type: str +BTPROTO_HCI = ... # type: int +BTPROTO_L2CAP = ... # type: int +BTPROTO_RFCOMM = ... # type: int +BTPROTO_SCO = ... # type: int +EAI_ADDRFAMILY = ... # type: int +EAI_AGAIN = ... # type: int +EAI_BADFLAGS = ... # type: int +EAI_FAIL = ... # type: int +EAI_FAMILY = ... # type: int +EAI_MEMORY = ... # type: int +EAI_NODATA = ... # type: int +EAI_NONAME = ... # type: int +EAI_OVERFLOW = ... # type: int +EAI_SERVICE = ... # type: int +EAI_SOCKTYPE = ... # type: int +EAI_SYSTEM = ... # type: int +EBADF = ... # type: int +EINTR = ... # type: int +HCI_DATA_DIR = ... # type: int +HCI_FILTER = ... # type: int +HCI_TIME_STAMP = ... # type: int +INADDR_ALLHOSTS_GROUP = ... # type: int +INADDR_ANY = ... # type: int +INADDR_BROADCAST = ... # type: int +INADDR_LOOPBACK = ... # type: int +INADDR_MAX_LOCAL_GROUP = ... # type: int +INADDR_NONE = ... # type: int +INADDR_UNSPEC_GROUP = ... # type: int +IPPORT_RESERVED = ... # type: int +IPPORT_USERRESERVED = ... # type: int +IPPROTO_AH = ... # type: int +IPPROTO_DSTOPTS = ... # type: int +IPPROTO_EGP = ... # type: int +IPPROTO_ESP = ... # type: int +IPPROTO_FRAGMENT = ... # type: int +IPPROTO_GRE = ... # type: int +IPPROTO_HOPOPTS = ... # type: int +IPPROTO_ICMP = ... # type: int +IPPROTO_ICMPV6 = ... # type: int +IPPROTO_IDP = ... # type: int +IPPROTO_IGMP = ... # type: int +IPPROTO_IP = ... # type: int +IPPROTO_IPIP = ... # type: int +IPPROTO_IPV6 = ... # type: int +IPPROTO_NONE = ... # type: int +IPPROTO_PIM = ... # type: int +IPPROTO_PUP = ... # type: int +IPPROTO_RAW = ... # type: int +IPPROTO_ROUTING = ... # type: int +IPPROTO_RSVP = ... # type: int +IPPROTO_TCP = ... # type: int +IPPROTO_TP = ... # type: int +IPPROTO_UDP = ... # type: int +IPV6_CHECKSUM = ... # type: int +IPV6_DSTOPTS = ... # type: int +IPV6_HOPLIMIT = ... # type: int +IPV6_HOPOPTS = ... # type: int +IPV6_JOIN_GROUP = ... # type: int +IPV6_LEAVE_GROUP = ... # type: int +IPV6_MULTICAST_HOPS = ... # type: int +IPV6_MULTICAST_IF = ... # type: int +IPV6_MULTICAST_LOOP = ... # type: int +IPV6_NEXTHOP = ... # type: int +IPV6_PKTINFO = ... # type: int +IPV6_RECVDSTOPTS = ... # type: int +IPV6_RECVHOPLIMIT = ... # type: int +IPV6_RECVHOPOPTS = ... # type: int +IPV6_RECVPKTINFO = ... # type: int +IPV6_RECVRTHDR = ... # type: int +IPV6_RECVTCLASS = ... # type: int +IPV6_RTHDR = ... # type: int +IPV6_RTHDRDSTOPTS = ... # type: int +IPV6_RTHDR_TYPE_0 = ... # type: int +IPV6_TCLASS = ... # type: int +IPV6_UNICAST_HOPS = ... # type: int +IPV6_V6ONLY = ... # type: int +IP_ADD_MEMBERSHIP = ... # type: int +IP_DEFAULT_MULTICAST_LOOP = ... # type: int +IP_DEFAULT_MULTICAST_TTL = ... # type: int +IP_DROP_MEMBERSHIP = ... # type: int +IP_HDRINCL = ... # type: int +IP_MAX_MEMBERSHIPS = ... # type: int +IP_MULTICAST_IF = ... # type: int +IP_MULTICAST_LOOP = ... # type: int +IP_MULTICAST_TTL = ... # type: int +IP_OPTIONS = ... # type: int +IP_RECVOPTS = ... # type: int +IP_RECVRETOPTS = ... # type: int +IP_RETOPTS = ... # type: int +IP_TOS = ... # type: int +IP_TTL = ... # type: int +MSG_CTRUNC = ... # type: int +MSG_DONTROUTE = ... # type: int +MSG_DONTWAIT = ... # type: int +MSG_EOR = ... # type: int +MSG_OOB = ... # type: int +MSG_PEEK = ... # type: int +MSG_TRUNC = ... # type: int +MSG_WAITALL = ... # type: int +MethodType = ... # type: type +NETLINK_DNRTMSG = ... # type: int +NETLINK_FIREWALL = ... # type: int +NETLINK_IP6_FW = ... # type: int +NETLINK_NFLOG = ... # type: int +NETLINK_ROUTE = ... # type: int +NETLINK_USERSOCK = ... # type: int +NETLINK_XFRM = ... # type: int +NI_DGRAM = ... # type: int +NI_MAXHOST = ... # type: int +NI_MAXSERV = ... # type: int +NI_NAMEREQD = ... # type: int +NI_NOFQDN = ... # type: int +NI_NUMERICHOST = ... # type: int +NI_NUMERICSERV = ... # type: int +PACKET_BROADCAST = ... # type: int +PACKET_FASTROUTE = ... # type: int +PACKET_HOST = ... # type: int +PACKET_LOOPBACK = ... # type: int +PACKET_MULTICAST = ... # type: int +PACKET_OTHERHOST = ... # type: int +PACKET_OUTGOING = ... # type: int +PF_PACKET = ... # type: int +SHUT_RD = ... # type: int +SHUT_RDWR = ... # type: int +SHUT_WR = ... # type: int +SOCK_DGRAM = ... # type: int +SOCK_RAW = ... # type: int +SOCK_RDM = ... # type: int +SOCK_SEQPACKET = ... # type: int +SOCK_STREAM = ... # type: int +SOL_HCI = ... # type: int +SOL_IP = ... # type: int +SOL_SOCKET = ... # type: int +SOL_TCP = ... # type: int +SOL_TIPC = ... # type: int +SOL_UDP = ... # type: int +SOMAXCONN = ... # type: int +SO_ACCEPTCONN = ... # type: int +SO_BROADCAST = ... # type: int +SO_DEBUG = ... # type: int +SO_DONTROUTE = ... # type: int +SO_ERROR = ... # type: int +SO_KEEPALIVE = ... # type: int +SO_LINGER = ... # type: int +SO_OOBINLINE = ... # type: int +SO_RCVBUF = ... # type: int +SO_RCVLOWAT = ... # type: int +SO_RCVTIMEO = ... # type: int +SO_REUSEADDR = ... # type: int +SO_REUSEPORT = ... # type: int +SO_SNDBUF = ... # type: int +SO_SNDLOWAT = ... # type: int +SO_SNDTIMEO = ... # type: int +SO_TYPE = ... # type: int +SSL_ERROR_EOF = ... # type: int +SSL_ERROR_INVALID_ERROR_CODE = ... # type: int +SSL_ERROR_SSL = ... # type: int +SSL_ERROR_SYSCALL = ... # type: int +SSL_ERROR_WANT_CONNECT = ... # type: int +SSL_ERROR_WANT_READ = ... # type: int +SSL_ERROR_WANT_WRITE = ... # type: int +SSL_ERROR_WANT_X509_LOOKUP = ... # type: int +SSL_ERROR_ZERO_RETURN = ... # type: int +TCP_CORK = ... # type: int +TCP_DEFER_ACCEPT = ... # type: int +TCP_INFO = ... # type: int +TCP_KEEPCNT = ... # type: int +TCP_KEEPIDLE = ... # type: int +TCP_KEEPINTVL = ... # type: int +TCP_LINGER2 = ... # type: int +TCP_MAXSEG = ... # type: int +TCP_NODELAY = ... # type: int +TCP_QUICKACK = ... # type: int +TCP_SYNCNT = ... # type: int +TCP_WINDOW_CLAMP = ... # type: int +TIPC_ADDR_ID = ... # type: int +TIPC_ADDR_NAME = ... # type: int +TIPC_ADDR_NAMESEQ = ... # type: int +TIPC_CFG_SRV = ... # type: int +TIPC_CLUSTER_SCOPE = ... # type: int +TIPC_CONN_TIMEOUT = ... # type: int +TIPC_CRITICAL_IMPORTANCE = ... # type: int +TIPC_DEST_DROPPABLE = ... # type: int +TIPC_HIGH_IMPORTANCE = ... # type: int +TIPC_IMPORTANCE = ... # type: int +TIPC_LOW_IMPORTANCE = ... # type: int +TIPC_MEDIUM_IMPORTANCE = ... # type: int +TIPC_NODE_SCOPE = ... # type: int +TIPC_PUBLISHED = ... # type: int +TIPC_SRC_DROPPABLE = ... # type: int +TIPC_SUBSCR_TIMEOUT = ... # type: int +TIPC_SUB_CANCEL = ... # type: int +TIPC_SUB_PORTS = ... # type: int +TIPC_SUB_SERVICE = ... # type: int +TIPC_TOP_SRV = ... # type: int +TIPC_WAIT_FOREVER = ... # type: int +TIPC_WITHDRAWN = ... # type: int +TIPC_ZONE_SCOPE = ... # type: int + +# PyCapsule +CAPI = ... # type: Any + +has_ipv6 = ... # type: bool + +class error(IOError): ... +class gaierror(error): ... +class timeout(error): ... + +class SocketType(object): + family = ... # type: int + type = ... # type: int + proto = ... # type: int + timeout = ... # type: float + + def __init__(self, family: int = ..., type: int = ..., proto: int = ...) -> None: ... + def accept(self) -> Tuple[SocketType, tuple]: ... + def bind(self, address: tuple) -> None: ... + def close(self) -> None: ... + def connect(self, address: tuple) -> None: + raise gaierror + raise timeout + def connect_ex(self, address: tuple) -> int: ... + def dup(self) -> SocketType: ... + def fileno(self) -> int: ... + def getpeername(self) -> tuple: ... + def getsockname(self) -> tuple: ... + def getsockopt(self, level: int, option: int, buffersize: int = ...) -> str: ... + def gettimeout(self) -> float: ... + def listen(self, backlog: int) -> None: + raise error + def makefile(self, mode: str = ..., buffersize: int = ...) -> IO[Any]: ... + def recv(self, buffersize: int, flags: int = ...) -> str: ... + def recv_into(self, buffer: bytearray, nbytes: int = ..., flags: int = ...) -> int: ... + def recvfrom(self, buffersize: int, flags: int = ...) -> tuple: + raise error + def recvfrom_into(self, buffer: bytearray, nbytes: int = ..., + flags: int = ...) -> int: ... + def send(self, data: str, flags: int = ...) -> int: ... + def sendall(self, data: str, flags: int = ...) -> None: ... + @overload + def sendto(self, data: str, address: tuple) -> int: ... + @overload + def sendto(self, data: str, flags: int, address: tuple) -> int: ... + def setblocking(self, flag: bool) -> None: ... + def setsockopt(self, level: int, option: int, value: Union[int, str]) -> None: ... + def settimeout(self, value: Optional[float]) -> None: ... + def shutdown(self, flag: int) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/_sre.pyi b/client/typeshed-fallback/stdlib/2/_sre.pyi new file mode 100644 index 000000000..1b6b5bc23 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/_sre.pyi @@ -0,0 +1,53 @@ +"""Stub file for the '_sre' module.""" + +from typing import Any, Union, Iterable, Optional, Mapping, Sequence, Dict, List, Tuple, overload + +CODESIZE = ... # type: int +MAGIC = ... # type: int +MAXREPEAT = ... # type: long +copyright = ... # type: str + +class SRE_Match(object): + def start(self, group: int = ...) -> int: + raise IndexError() + def end(self, group: int = ...) -> int: + raise IndexError() + def expand(self, s: str) -> Any: ... + @overload + def group(self) -> str: ... + @overload + def group(self, group: int = ...) -> Optional[str]: ... + def groupdict(self) -> Dict[int, Optional[str]]: ... + def groups(self) -> Tuple[Optional[str], ...]: ... + def span(self) -> Tuple[int, int]: + raise IndexError() + +class SRE_Scanner(object): + pattern = ... # type: str + def match(self) -> SRE_Match: ... + def search(self) -> SRE_Match: ... + +class SRE_Pattern(object): + pattern = ... # type: str + flags = ... # type: int + groups = ... # type: int + groupindex = ... # type: Mapping[str, int] + indexgroup = ... # type: Sequence[int] + def findall(self, source: str, pos: int = ..., endpos: int = ...) -> List[Union[tuple, str]]: ... + def finditer(self, source: str, pos: int = ..., endpos: int = ...) -> Iterable[Union[tuple, str]]: ... + def match(self, pattern, pos: int = ..., endpos: int = ...) -> SRE_Match: ... + def scanner(self, s: str, start: int = ..., end: int = ...) -> SRE_Scanner: ... + def search(self, pattern, pos: int = ..., endpos: int = ...) -> SRE_Match: ... + def split(self, source: str, maxsplit: int = ...) -> List[Optional[str]]: ... + def sub(self, repl: str, string: str, count: int = ...) -> tuple: ... + def subn(self, repl: str, string: str, count: int = ...) -> tuple: ... + +def compile(pattern: str, flags: int, code: List[int], + groups: int = ..., + groupindex: Mapping[str, int] = ..., + indexgroup: Sequence[int] = ...) -> SRE_Pattern: + raise OverflowError() + +def getcodesize() -> int: ... + +def getlower(a: int, b: int) -> int: ... diff --git a/client/typeshed-fallback/stdlib/2/_struct.pyi b/client/typeshed-fallback/stdlib/2/_struct.pyi new file mode 100644 index 000000000..add6f842d --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/_struct.pyi @@ -0,0 +1,22 @@ +"""Stub file for the '_struct' module.""" + +from typing import Any, AnyStr, Tuple + +class error(Exception): ... + +class Struct(object): + size = ... # type: int + format = ... # type: str + + def __init__(self, fmt: str) -> None: ... + def pack_into(self, buffer: bytearray, offset: int, obj: Any) -> None: ... + def pack(self, *args) -> str: ... + def unpack(self, s: str) -> Tuple[Any, ...]: ... + def unpack_from(self, buffer: bytearray, offset: int = ...) -> Tuple[Any, ...]: ... + +def _clearcache() -> None: ... +def calcsize(fmt: str) -> int: ... +def pack(fmt: AnyStr, obj: Any) -> str: ... +def pack_into(fmt: AnyStr, buffer: bytearray, offset: int, obj: Any) -> None: ... +def unpack(fmt: AnyStr, data: str) -> Tuple[Any, ...]: ... +def unpack_from(fmt: AnyStr, buffer: bytearray, offset: int = ...) -> Tuple[Any, ...]: ... diff --git a/client/typeshed-fallback/stdlib/2/_symtable.pyi b/client/typeshed-fallback/stdlib/2/_symtable.pyi new file mode 100644 index 000000000..fd8b691f1 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/_symtable.pyi @@ -0,0 +1,39 @@ +from typing import List, Dict + +CELL = ... # type: int +DEF_BOUND = ... # type: int +DEF_FREE = ... # type: int +DEF_FREE_CLASS = ... # type: int +DEF_GLOBAL = ... # type: int +DEF_IMPORT = ... # type: int +DEF_LOCAL = ... # type: int +DEF_PARAM = ... # type: int +FREE = ... # type: int +GLOBAL_EXPLICIT = ... # type: int +GLOBAL_IMPLICIT = ... # type: int +LOCAL = ... # type: int +OPT_BARE_EXEC = ... # type: int +OPT_EXEC = ... # type: int +OPT_IMPORT_STAR = ... # type: int +SCOPE_MASK = ... # type: int +SCOPE_OFF = ... # type: int +TYPE_CLASS = ... # type: int +TYPE_FUNCTION = ... # type: int +TYPE_MODULE = ... # type: int +USE = ... # type: int + +class _symtable_entry(object): + ... + +class symtable(object): + children = ... # type: List[_symtable_entry] + id = ... # type: int + lineno = ... # type: int + name = ... # type: str + nested = ... # type: int + optimized = ... # type: int + symbols = ... # type: Dict[str, int] + type = ... # type: int + varnames = ... # type: List[str] + + def __init__(self, src: str, filename: str, startstr: str) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/_threading_local.pyi b/client/typeshed-fallback/stdlib/2/_threading_local.pyi new file mode 100644 index 000000000..512bf5874 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/_threading_local.pyi @@ -0,0 +1,14 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/_threading_local.py +from typing import Any, List + +__all__: List[str] + +class _localbase(object): ... + +class local(_localbase): + def __getattribute__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __delattr__(self, name: str) -> None: ... + def __del__(self) -> None: ... + +def _patch(self: local) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/_warnings.pyi b/client/typeshed-fallback/stdlib/2/_warnings.pyi new file mode 100644 index 000000000..63fd9d486 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/_warnings.pyi @@ -0,0 +1,11 @@ +from typing import Any, List, Optional, Type + +default_action = ... # type: str +filters = ... # type: List[tuple] +once_registry = ... # type: dict + +def warn(message: Warning, category: Optional[Type[Warning]] = ..., stacklevel: int = ...) -> None: ... +def warn_explicit(message: Warning, category: Optional[Type[Warning]], + filename: str, lineno: int, + module: Any = ..., registry: dict = ..., + module_globals: dict = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/abc.pyi b/client/typeshed-fallback/stdlib/2/abc.pyi new file mode 100644 index 000000000..244392c7b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/abc.pyi @@ -0,0 +1,29 @@ +from typing import Any, Dict, Set, Tuple, Type +import _weakrefset + +# NOTE: mypy has special processing for ABCMeta and abstractmethod. + +def abstractmethod(funcobj: Any) -> Any: ... + +class ABCMeta(type): + # TODO: FrozenSet + __abstractmethods__ = ... # type: Set[Any] + _abc_cache = ... # type: _weakrefset.WeakSet + _abc_invalidation_counter = ... # type: int + _abc_negative_cache = ... # type: _weakrefset.WeakSet + _abc_negative_cache_version = ... # type: int + _abc_registry = ... # type: _weakrefset.WeakSet + def __init__(self, name: str, bases: Tuple[type, ...], namespace: Dict[Any, Any]) -> None: ... + def __instancecheck__(cls: ABCMeta, instance: Any) -> Any: ... + def __subclasscheck__(cls: ABCMeta, subclass: Any) -> Any: ... + def _dump_registry(cls: ABCMeta, *args: Any, **kwargs: Any) -> None: ... + def register(cls: ABCMeta, subclass: Type[Any]) -> None: ... + +# TODO: The real abc.abstractproperty inherits from "property". +class abstractproperty(object): + def __new__(cls, func: Any) -> Any: ... + __isabstractmethod__ = ... # type: bool + doc = ... # type: Any + fdel = ... # type: Any + fget = ... # type: Any + fset = ... # type: Any diff --git a/client/typeshed-fallback/stdlib/2/ast.pyi b/client/typeshed-fallback/stdlib/2/ast.pyi new file mode 100644 index 000000000..03682ef0c --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/ast.pyi @@ -0,0 +1,32 @@ +# Python 2.7 ast + +# Rename typing to _typing, as not to conflict with typing imported +# from _ast below when loaded in an unorthodox way by the Dropbox +# internal Bazel integration. +import typing as _typing +from typing import Any, Iterator, Optional, Union + +from _ast import * +from _ast import AST, Module + +__version__ = ... # type: str +PyCF_ONLY_AST = ... # type: int + + +def parse(source: Union[str, unicode], filename: Union[str, unicode] = ..., mode: Union[str, unicode] = ...) -> Module: ... +def copy_location(new_node: AST, old_node: AST) -> AST: ... +def dump(node: AST, annotate_fields: bool = ..., include_attributes: bool = ...) -> str: ... +def fix_missing_locations(node: AST) -> AST: ... +def get_docstring(node: AST, clean: bool = ...) -> str: ... +def increment_lineno(node: AST, n: int = ...) -> AST: ... +def iter_child_nodes(node: AST) -> Iterator[AST]: ... +def iter_fields(node: AST) -> Iterator[_typing.Tuple[str, Any]]: ... +def literal_eval(node_or_string: Union[str, unicode, AST]) -> Any: ... +def walk(node: AST) -> Iterator[AST]: ... + +class NodeVisitor(): + def visit(self, node: AST) -> Any: ... + def generic_visit(self, node: AST) -> Any: ... + +class NodeTransformer(NodeVisitor): + def generic_visit(self, node: AST) -> Optional[AST]: ... diff --git a/client/typeshed-fallback/stdlib/2/atexit.pyi b/client/typeshed-fallback/stdlib/2/atexit.pyi new file mode 100644 index 000000000..13d2602b0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/atexit.pyi @@ -0,0 +1,5 @@ +from typing import TypeVar, Any + +_FT = TypeVar('_FT') + +def register(func: _FT, *args: Any, **kargs: Any) -> _FT: ... diff --git a/client/typeshed-fallback/stdlib/2/cPickle.pyi b/client/typeshed-fallback/stdlib/2/cPickle.pyi new file mode 100644 index 000000000..fb129d1b5 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/cPickle.pyi @@ -0,0 +1,32 @@ +from typing import Any, IO, List + +HIGHEST_PROTOCOL = ... # type: int +compatible_formats = ... # type: List[str] +format_version = ... # type: str + +class Pickler: + def __init__(self, file: IO[str], protocol: int = ...) -> None: ... + + def dump(self, obj: Any) -> None: ... + + def clear_memo(self) -> None: ... + + +class Unpickler: + def __init__(self, file: IO[str]) -> None: ... + + def load(self) -> Any: ... + + def noload(self) -> Any: ... + + +def dump(obj: Any, file: IO[str], protocol: int = ...) -> None: ... +def dumps(obj: Any, protocol: int = ...) -> str: ... +def load(file: IO[str]) -> Any: ... +def loads(str: str) -> Any: ... + +class PickleError(Exception): ... +class UnpicklingError(PickleError): ... +class BadPickleGet(UnpicklingError): ... +class PicklingError(PickleError): ... +class UnpickleableError(PicklingError): ... diff --git a/client/typeshed-fallback/stdlib/2/cStringIO.pyi b/client/typeshed-fallback/stdlib/2/cStringIO.pyi new file mode 100644 index 000000000..380e3a4be --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/cStringIO.pyi @@ -0,0 +1,54 @@ +# Stubs for cStringIO (Python 2.7) +# See https://docs.python.org/2/library/stringio.html + +from abc import ABCMeta +from typing import overload, IO, List, Iterable, Iterator, Optional, Union +from types import TracebackType + +# TODO the typing.IO[] generics should be split into input and output. + +# This class isn't actually abstract, but you can't instantiate it +# directly, so we might as well treat it as abstract in the stub. +class InputType(IO[str], Iterator[str], metaclass=ABCMeta): + def getvalue(self) -> str: ... + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def read(self, size: int = ...) -> str: ... + def readline(self, size: int = ...) -> str: ... + def readlines(self, hint: int = ...) -> List[str]: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def __iter__(self) -> InputType: ... + def next(self) -> str: ... + def reset(self) -> None: ... + + +class OutputType(IO[str], Iterator[str], metaclass=ABCMeta): + @property + def softspace(self) -> int: ... + def getvalue(self) -> str: ... + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def read(self, size: int = ...) -> str: ... + def readline(self, size: int = ...) -> str: ... + def readlines(self, hint: int = ...) -> List[str]: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def __iter__(self) -> OutputType: ... + def next(self) -> str: ... + def reset(self) -> None: ... + def write(self, b: Union[str, unicode]) -> int: ... + def writelines(self, lines: Iterable[Union[str, unicode]]) -> None: ... + +@overload +def StringIO() -> OutputType: ... +@overload +def StringIO(s: str) -> InputType: ... diff --git a/client/typeshed-fallback/stdlib/2/collections.pyi b/client/typeshed-fallback/stdlib/2/collections.pyi new file mode 100644 index 000000000..3af54ea5b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/collections.pyi @@ -0,0 +1,126 @@ +# These are not exported. +from typing import Dict, Generic, TypeVar, Tuple, overload, Type, Optional, List, Union, Reversible + +# These are exported. +from typing import ( + Callable as Callable, + Container as Container, + Hashable as Hashable, + ItemsView as ItemsView, + Iterable as Iterable, + Iterator as Iterator, + KeysView as KeysView, + Mapping as Mapping, + MappingView as MappingView, + MutableMapping as MutableMapping, + MutableSequence as MutableSequence, + MutableSet as MutableSet, + Sequence as Sequence, + AbstractSet as Set, + Sized as Sized, + ValuesView as ValuesView, +) + +_S = TypeVar('_S') +_T = TypeVar('_T') +_KT = TypeVar('_KT') +_VT = TypeVar('_VT') + +# namedtuple is special-cased in the type checker; the initializer is ignored. +def namedtuple(typename: Union[str, unicode], field_names: Union[str, unicode, Iterable[Union[str, unicode]]], + verbose: bool = ..., rename: bool = ...) -> Type[tuple]: ... + +class deque(Sized, Iterable[_T], Reversible[_T], Generic[_T]): + def __init__(self, iterable: Iterable[_T] = ..., + maxlen: int = ...) -> None: ... + @property + def maxlen(self) -> Optional[int]: ... + def append(self, x: _T) -> None: ... + def appendleft(self, x: _T) -> None: ... + def clear(self) -> None: ... + def count(self, x: _T) -> int: ... + def extend(self, iterable: Iterable[_T]) -> None: ... + def extendleft(self, iterable: Iterable[_T]) -> None: ... + def pop(self) -> _T: ... + def popleft(self) -> _T: ... + def remove(self, value: _T) -> None: ... + def reverse(self) -> None: ... + def rotate(self, n: int) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + def __hash__(self) -> int: ... + def __getitem__(self, i: int) -> _T: ... + def __setitem__(self, i: int, x: _T) -> None: ... + def __contains__(self, o: _T) -> bool: ... + def __reversed__(self) -> Iterator[_T]: ... + def __iadd__(self: _S, iterable: Iterable[_T]) -> _S: ... + +_CounterT = TypeVar('_CounterT', bound=Counter) + +class Counter(Dict[_T, int], Generic[_T]): + @overload + def __init__(self, **kwargs: int) -> None: ... + @overload + def __init__(self, mapping: Mapping[_T, int]) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T]) -> None: ... + def copy(self: _CounterT) -> _CounterT: ... + def elements(self) -> Iterator[_T]: ... + def most_common(self, n: Optional[int] = ...) -> List[Tuple[_T, int]]: ... + @overload + def subtract(self, __mapping: Mapping[_T, int]) -> None: ... + @overload + def subtract(self, iterable: Iterable[_T]) -> None: ... + # The Iterable[Tuple[...]] argument type is not actually desirable + # (the tuples will be added as keys, breaking type safety) but + # it's included so that the signature is compatible with + # Dict.update. Not sure if we should use '# type: ignore' instead + # and omit the type from the union. + @overload + def update(self, __m: Mapping[_T, int], **kwargs: int) -> None: ... + @overload + def update(self, __m: Union[Iterable[_T], Iterable[Tuple[_T, int]]], **kwargs: int) -> None: ... + @overload + def update(self, **kwargs: int) -> None: ... + + def __add__(self, other: Counter[_T]) -> Counter[_T]: ... + def __sub__(self, other: Counter[_T]) -> Counter[_T]: ... + def __and__(self, other: Counter[_T]) -> Counter[_T]: ... + def __or__(self, other: Counter[_T]) -> Counter[_T]: ... + def __iadd__(self, other: Counter[_T]) -> Counter[_T]: ... + def __isub__(self, other: Counter[_T]) -> Counter[_T]: ... + def __iand__(self, other: Counter[_T]) -> Counter[_T]: ... + def __ior__(self, other: Counter[_T]) -> Counter[_T]: ... + +_OrderedDictT = TypeVar('_OrderedDictT', bound=OrderedDict) + +class OrderedDict(Dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): + def popitem(self, last: bool = ...) -> Tuple[_KT, _VT]: ... + def copy(self: _OrderedDictT) -> _OrderedDictT: ... + def __reversed__(self) -> Iterator[_KT]: ... + +_DefaultDictT = TypeVar('_DefaultDictT', bound=defaultdict) + +class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): + default_factory = ... # type: Callable[[], _VT] + @overload + def __init__(self, **kwargs: _VT) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]]) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], + map: Mapping[_KT, _VT]) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], + map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], + iterable: Iterable[Tuple[_KT, _VT]]) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], + iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __missing__(self, key: _KT) -> _VT: ... + def copy(self: _DefaultDictT) -> _DefaultDictT: ... diff --git a/client/typeshed-fallback/stdlib/2/commands.pyi b/client/typeshed-fallback/stdlib/2/commands.pyi new file mode 100644 index 000000000..e321f0844 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/commands.pyi @@ -0,0 +1,12 @@ +from typing import overload, AnyStr, Text, Tuple + +def getstatus(file: Text) -> str: ... +def getoutput(cmd: Text) -> str: ... +def getstatusoutput(cmd: Text) -> Tuple[int, str]: ... + +@overload +def mk2arg(head: bytes, x: bytes) -> bytes: ... +@overload +def mk2arg(head: Text, x: Text) -> Text: ... + +def mkarg(x: AnyStr) -> AnyStr: ... diff --git a/client/typeshed-fallback/stdlib/2/compileall.pyi b/client/typeshed-fallback/stdlib/2/compileall.pyi new file mode 100644 index 000000000..c3e861e1e --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/compileall.pyi @@ -0,0 +1,10 @@ +# Stubs for compileall (Python 2) + +from typing import Optional, Pattern, Union + +_Path = Union[str, bytes] + +# rx can be any object with a 'search' method; once we have Protocols we can change the type +def compile_dir(dir: _Path, maxlevels: int = ..., ddir: Optional[_Path] = ..., force: bool = ..., rx: Optional[Pattern] = ..., quiet: int = ...) -> int: ... +def compile_file(fullname: _Path, ddir: Optional[_Path] = ..., force: bool = ..., rx: Optional[Pattern] = ..., quiet: int = ...) -> int: ... +def compile_path(skip_curdir: bool = ..., maxlevels: int = ..., force: bool = ..., quiet: int = ...) -> int: ... diff --git a/client/typeshed-fallback/stdlib/2/cookielib.pyi b/client/typeshed-fallback/stdlib/2/cookielib.pyi new file mode 100644 index 000000000..cc3bbadf3 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/cookielib.pyi @@ -0,0 +1,110 @@ +from typing import Any, Optional + +class Cookie: + version = ... # type: Any + name = ... # type: Any + value = ... # type: Any + port = ... # type: Any + port_specified = ... # type: Any + domain = ... # type: Any + domain_specified = ... # type: Any + domain_initial_dot = ... # type: Any + path = ... # type: Any + path_specified = ... # type: Any + secure = ... # type: Any + expires = ... # type: Any + discard = ... # type: Any + comment = ... # type: Any + comment_url = ... # type: Any + rfc2109 = ... # type: Any + def __init__(self, version, name, value, port, port_specified, domain, domain_specified, domain_initial_dot, path, + path_specified, secure, expires, discard, comment, comment_url, rest, rfc2109: bool = ...): ... + def has_nonstandard_attr(self, name): ... + def get_nonstandard_attr(self, name, default: Optional[Any] = ...): ... + def set_nonstandard_attr(self, name, value): ... + def is_expired(self, now: Optional[Any] = ...): ... + +class CookiePolicy: + def set_ok(self, cookie, request): ... + def return_ok(self, cookie, request): ... + def domain_return_ok(self, domain, request): ... + def path_return_ok(self, path, request): ... + +class DefaultCookiePolicy(CookiePolicy): + DomainStrictNoDots = ... # type: Any + DomainStrictNonDomain = ... # type: Any + DomainRFC2965Match = ... # type: Any + DomainLiberal = ... # type: Any + DomainStrict = ... # type: Any + netscape = ... # type: Any + rfc2965 = ... # type: Any + rfc2109_as_netscape = ... # type: Any + hide_cookie2 = ... # type: Any + strict_domain = ... # type: Any + strict_rfc2965_unverifiable = ... # type: Any + strict_ns_unverifiable = ... # type: Any + strict_ns_domain = ... # type: Any + strict_ns_set_initial_dollar = ... # type: Any + strict_ns_set_path = ... # type: Any + def __init__(self, blocked_domains: Optional[Any] = ..., allowed_domains: Optional[Any] = ..., netscape: bool = ..., + rfc2965: bool = ..., rfc2109_as_netscape: Optional[Any] = ..., hide_cookie2: bool = ..., + strict_domain: bool = ..., strict_rfc2965_unverifiable: bool = ..., strict_ns_unverifiable: bool = ..., + strict_ns_domain=..., strict_ns_set_initial_dollar: bool = ..., strict_ns_set_path: bool = ...): ... + def blocked_domains(self): ... + def set_blocked_domains(self, blocked_domains): ... + def is_blocked(self, domain): ... + def allowed_domains(self): ... + def set_allowed_domains(self, allowed_domains): ... + def is_not_allowed(self, domain): ... + def set_ok(self, cookie, request): ... + def set_ok_version(self, cookie, request): ... + def set_ok_verifiability(self, cookie, request): ... + def set_ok_name(self, cookie, request): ... + def set_ok_path(self, cookie, request): ... + def set_ok_domain(self, cookie, request): ... + def set_ok_port(self, cookie, request): ... + def return_ok(self, cookie, request): ... + def return_ok_version(self, cookie, request): ... + def return_ok_verifiability(self, cookie, request): ... + def return_ok_secure(self, cookie, request): ... + def return_ok_expires(self, cookie, request): ... + def return_ok_port(self, cookie, request): ... + def return_ok_domain(self, cookie, request): ... + def domain_return_ok(self, domain, request): ... + def path_return_ok(self, path, request): ... + +class Absent: ... + +class CookieJar: + non_word_re = ... # type: Any + quote_re = ... # type: Any + strict_domain_re = ... # type: Any + domain_re = ... # type: Any + dots_re = ... # type: Any + magic_re = ... # type: Any + def __init__(self, policy: Optional[Any] = ...): ... + def set_policy(self, policy): ... + def add_cookie_header(self, request): ... + def make_cookies(self, response, request): ... + def set_cookie_if_ok(self, cookie, request): ... + def set_cookie(self, cookie): ... + def extract_cookies(self, response, request): ... + def clear(self, domain: Optional[Any] = ..., path: Optional[Any] = ..., name: Optional[Any] = ...): ... + def clear_session_cookies(self): ... + def clear_expired_cookies(self): ... + def __iter__(self): ... + def __len__(self): ... + +class LoadError(IOError): ... + +class FileCookieJar(CookieJar): + filename = ... # type: Any + delayload = ... # type: Any + def __init__(self, filename: Optional[Any] = ..., delayload: bool = ..., policy: Optional[Any] = ...): ... + def save(self, filename: Optional[Any] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...): ... + def load(self, filename: Optional[Any] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...): ... + def revert(self, filename: Optional[Any] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...): ... + +MozillaCookieJar = FileCookieJar +LWPCookieJar = FileCookieJar +def lwp_cookie_str(cookie: Cookie) -> str: ... diff --git a/client/typeshed-fallback/stdlib/2/dircache.pyi b/client/typeshed-fallback/stdlib/2/dircache.pyi new file mode 100644 index 000000000..ac6732b6c --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/dircache.pyi @@ -0,0 +1,10 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/dircache.py + +from typing import List, MutableSequence, Text, Union + +def reset() -> None: ... +def listdir(path: Text) -> List[str]: ... + +opendir = listdir + +def annotate(head: Text, list: Union[MutableSequence[str], MutableSequence[Text], MutableSequence[Union[str, Text]]]) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/distutils/__init__.pyi b/client/typeshed-fallback/stdlib/2/distutils/__init__.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2/distutils/emxccompiler.pyi b/client/typeshed-fallback/stdlib/2/distutils/emxccompiler.pyi new file mode 100644 index 000000000..97e4a29ad --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/distutils/emxccompiler.pyi @@ -0,0 +1,5 @@ +# Stubs for emxccompiler + +from distutils.unixccompiler import UnixCCompiler + +class EMXCCompiler(UnixCCompiler): ... diff --git a/client/typeshed-fallback/stdlib/2/dummy_thread.pyi b/client/typeshed-fallback/stdlib/2/dummy_thread.pyi new file mode 100644 index 000000000..28041002a --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/dummy_thread.pyi @@ -0,0 +1,21 @@ +from typing import Any, Callable, Dict, NoReturn, Optional, Tuple + +class error(Exception): + def __init__(self, *args: Any) -> None: ... + +def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: Dict[str, Any] = ...) -> None: ... +def exit() -> NoReturn: ... +def get_ident() -> int: ... +def allocate_lock() -> LockType: ... +def stack_size(size: Optional[int] = ...) -> int: ... + +class LockType(object): + locked_status: bool + def __init__(self) -> None: ... + def acquire(self, waitflag: Optional[bool] = ...) -> bool: ... + def __enter__(self, waitflag: Optional[bool] = ...) -> bool: ... + def __exit__(self, typ: Any, val: Any, tb: Any) -> None: ... + def release(self) -> bool: ... + def locked(self) -> bool: ... + +def interrupt_main() -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/email/MIMEText.pyi b/client/typeshed-fallback/stdlib/2/email/MIMEText.pyi new file mode 100644 index 000000000..3b059778a --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/MIMEText.pyi @@ -0,0 +1,4 @@ +from email.mime.nonmultipart import MIMENonMultipart + +class MIMEText(MIMENonMultipart): + def __init__(self, _text, _subtype=..., _charset=...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/email/__init__.pyi b/client/typeshed-fallback/stdlib/2/email/__init__.pyi new file mode 100644 index 000000000..384d9567f --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/__init__.pyi @@ -0,0 +1,6 @@ +from typing import IO, Any, AnyStr + +def message_from_string(s: AnyStr, *args, **kwargs): ... +def message_from_bytes(s: str, *args, **kwargs): ... +def message_from_file(fp: IO[AnyStr], *args, **kwargs): ... +def message_from_binary_file(fp: IO[str], *args, **kwargs): ... diff --git a/client/typeshed-fallback/stdlib/2/email/_parseaddr.pyi b/client/typeshed-fallback/stdlib/2/email/_parseaddr.pyi new file mode 100644 index 000000000..2cc529a96 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/_parseaddr.pyi @@ -0,0 +1,40 @@ +from typing import Any, Optional + +def parsedate_tz(data): ... +def parsedate(data): ... +def mktime_tz(data): ... +def quote(str): ... + +class AddrlistClass: + specials = ... # type: Any + pos = ... # type: Any + LWS = ... # type: Any + CR = ... # type: Any + FWS = ... # type: Any + atomends = ... # type: Any + phraseends = ... # type: Any + field = ... # type: Any + commentlist = ... # type: Any + def __init__(self, field): ... + def gotonext(self): ... + def getaddrlist(self): ... + def getaddress(self): ... + def getrouteaddr(self): ... + def getaddrspec(self): ... + def getdomain(self): ... + def getdelimited(self, beginchar, endchars, allowcomments: bool = ...): ... + def getquote(self): ... + def getcomment(self): ... + def getdomainliteral(self): ... + def getatom(self, atomends: Optional[Any] = ...): ... + def getphraselist(self): ... + +class AddressList(AddrlistClass): + addresslist = ... # type: Any + def __init__(self, field): ... + def __len__(self): ... + def __add__(self, other): ... + def __iadd__(self, other): ... + def __sub__(self, other): ... + def __isub__(self, other): ... + def __getitem__(self, index): ... diff --git a/client/typeshed-fallback/stdlib/2/email/base64mime.pyi b/client/typeshed-fallback/stdlib/2/email/base64mime.pyi new file mode 100644 index 000000000..f05003b8d --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/base64mime.pyi @@ -0,0 +1,8 @@ +def base64_len(s: bytes) -> int: ... +def header_encode(header, charset=..., keep_eols=..., maxlinelen=..., eol=...): ... +def encode(s, binary=..., maxlinelen=..., eol=...): ... +body_encode = encode +encodestring = encode +def decode(s, convert_eols=...): ... +body_decode = decode +decodestring = decode diff --git a/client/typeshed-fallback/stdlib/2/email/charset.pyi b/client/typeshed-fallback/stdlib/2/email/charset.pyi new file mode 100644 index 000000000..82ba6c0bb --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/charset.pyi @@ -0,0 +1,22 @@ +def add_charset(charset, header_enc=..., body_enc=..., output_charset=...) -> None: ... +def add_alias(alias, canonical) -> None: ... +def add_codec(charset, codecname) -> None: ... + +class Charset: + input_charset = ... + header_encoding = ... + body_encoding = ... + output_charset = ... + input_codec = ... + output_codec = ... + def __init__(self, input_charset=...) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def get_body_encoding(self): ... + def convert(self, s): ... + def to_splittable(self, s): ... + def from_splittable(self, ustr, to_output: bool = ...): ... + def get_output_charset(self): ... + def encoded_header_len(self, s): ... + def header_encode(self, s, convert: bool = ...): ... + def body_encode(self, s, convert: bool = ...): ... diff --git a/client/typeshed-fallback/stdlib/2/email/encoders.pyi b/client/typeshed-fallback/stdlib/2/email/encoders.pyi new file mode 100644 index 000000000..5670cbaf0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/encoders.pyi @@ -0,0 +1,4 @@ +def encode_base64(msg) -> None: ... +def encode_quopri(msg) -> None: ... +def encode_7or8bit(msg) -> None: ... +def encode_noop(msg) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/email/feedparser.pyi b/client/typeshed-fallback/stdlib/2/email/feedparser.pyi new file mode 100644 index 000000000..51f825939 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/feedparser.pyi @@ -0,0 +1,18 @@ +class BufferedSubFile: + def __init__(self) -> None: ... + def push_eof_matcher(self, pred) -> None: ... + def pop_eof_matcher(self): ... + def close(self) -> None: ... + def readline(self): ... + def unreadline(self, line) -> None: ... + def push(self, data): ... + def pushlines(self, lines) -> None: ... + def is_closed(self): ... + def __iter__(self): ... + def next(self): ... + + +class FeedParser: + def __init__(self, _factory=...) -> None: ... + def feed(self, data) -> None: ... + def close(self): ... diff --git a/client/typeshed-fallback/stdlib/2/email/generator.pyi b/client/typeshed-fallback/stdlib/2/email/generator.pyi new file mode 100644 index 000000000..96cfe2d21 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/generator.pyi @@ -0,0 +1,9 @@ +class Generator: + def __init__(self, outfp, mangle_from_: bool = ..., maxheaderlen: int = ...) -> None: ... + def write(self, s) -> None: ... + def flatten(self, msg, unixfrom: bool = ...) -> None: ... + def clone(self, fp): ... + + +class DecodedGenerator(Generator): + def __init__(self, outfp, mangle_from_: bool = ..., maxheaderlen: int = ..., fmt=...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/email/header.pyi b/client/typeshed-fallback/stdlib/2/email/header.pyi new file mode 100644 index 000000000..69c936300 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/header.pyi @@ -0,0 +1,11 @@ +def decode_header(header): ... +def make_header(decoded_seq, maxlinelen=..., header_name=..., continuation_ws=...): ... + +class Header: + def __init__(self, s=..., charset=..., maxlinelen=..., header_name=..., continuation_ws=..., + errors=...) -> None: ... + def __unicode__(self): ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def append(self, s, charset=..., errors=...) -> None: ... + def encode(self, splitchars=...): ... diff --git a/client/typeshed-fallback/stdlib/2/email/iterators.pyi b/client/typeshed-fallback/stdlib/2/email/iterators.pyi new file mode 100644 index 000000000..48aaf06a6 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/iterators.pyi @@ -0,0 +1,5 @@ +from typing import Generator + +def walk(self) -> Generator: ... +def body_line_iterator(msg, decode: bool = ...) -> Generator: ... +def typed_subpart_iterator(msg, maintype=..., subtype=...) -> Generator: ... diff --git a/client/typeshed-fallback/stdlib/2/email/message.pyi b/client/typeshed-fallback/stdlib/2/email/message.pyi new file mode 100644 index 000000000..bd3c6220d --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/message.pyi @@ -0,0 +1,45 @@ +from typing import Generator + +class Message: + preamble = ... + epilogue = ... + defects = ... + def __init__(self): ... + def as_string(self, unixfrom=...): ... + def is_multipart(self) -> bool: ... + def set_unixfrom(self, unixfrom) -> None: ... + def get_unixfrom(self): ... + def attach(self, payload) -> None: ... + def get_payload(self, i=..., decode: bool = ...): ... + def set_payload(self, payload, charset=...) -> None: ... + def set_charset(self, charset): ... + def get_charset(self): ... + def __len__(self): ... + def __getitem__(self, name): ... + def __setitem__(self, name, val) -> None: ... + def __delitem__(self, name) -> None: ... + def __contains__(self, name): ... + def has_key(self, name) -> bool: ... + def keys(self): ... + def values(self): ... + def items(self): ... + def get(self, name, failobj=...): ... + def get_all(self, name, failobj=...): ... + def add_header(self, _name, _value, **_params) -> None: ... + def replace_header(self, _name, _value) -> None: ... + def get_content_type(self): ... + def get_content_maintype(self): ... + def get_content_subtype(self): ... + def get_default_type(self): ... + def set_default_type(self, ctype) -> None: ... + def get_params(self, failobj=..., header=..., unquote: bool = ...): ... + def get_param(self, param, failobj=..., header=..., unquote: bool = ...): ... + def set_param(self, param, value, header=..., requote: bool = ..., charset=..., language=...) -> None: ... + def del_param(self, param, header=..., requote: bool = ...): ... + def set_type(self, type, header=..., requote: bool = ...): ... + def get_filename(self, failobj=...): ... + def get_boundary(self, failobj=...): ... + def set_boundary(self, boundary) -> None: ... + def get_content_charset(self, failobj=...): ... + def get_charsets(self, failobj=...): ... + def walk(self) -> Generator: ... diff --git a/client/typeshed-fallback/stdlib/2/email/mime/__init__.pyi b/client/typeshed-fallback/stdlib/2/email/mime/__init__.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2/email/mime/application.pyi b/client/typeshed-fallback/stdlib/2/email/mime/application.pyi new file mode 100644 index 000000000..99da67287 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/mime/application.pyi @@ -0,0 +1,11 @@ +# Stubs for email.mime.application + +from typing import Callable, Optional, Tuple, Union +from email.mime.nonmultipart import MIMENonMultipart + +_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] + +class MIMEApplication(MIMENonMultipart): + def __init__(self, _data: bytes, _subtype: str = ..., + _encoder: Callable[[MIMEApplication], None] = ..., + **_params: _ParamsType) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/email/mime/audio.pyi b/client/typeshed-fallback/stdlib/2/email/mime/audio.pyi new file mode 100644 index 000000000..406ade11b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/mime/audio.pyi @@ -0,0 +1,5 @@ +from email.mime.nonmultipart import MIMENonMultipart + + +class MIMEAudio(MIMENonMultipart): + def __init__(self, _audiodata, _subtype=..., _encoder=..., **_params) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/email/mime/base.pyi b/client/typeshed-fallback/stdlib/2/email/mime/base.pyi new file mode 100644 index 000000000..4bde4f073 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/mime/base.pyi @@ -0,0 +1,4 @@ +from email import message + +class MIMEBase(message.Message): + def __init__(self, _maintype, _subtype, **_params) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/email/mime/image.pyi b/client/typeshed-fallback/stdlib/2/email/mime/image.pyi new file mode 100644 index 000000000..2dfb098b8 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/mime/image.pyi @@ -0,0 +1,5 @@ +from email.mime.nonmultipart import MIMENonMultipart + + +class MIMEImage(MIMENonMultipart): + def __init__(self, _imagedata, _subtype=..., _encoder=..., **_params) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/email/mime/message.pyi b/client/typeshed-fallback/stdlib/2/email/mime/message.pyi new file mode 100644 index 000000000..33552faf2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/mime/message.pyi @@ -0,0 +1,5 @@ +from email.mime.nonmultipart import MIMENonMultipart + + +class MIMEMessage(MIMENonMultipart): + def __init__(self, _msg, _subtype=...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/email/mime/multipart.pyi b/client/typeshed-fallback/stdlib/2/email/mime/multipart.pyi new file mode 100644 index 000000000..0a7d3fa8a --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/mime/multipart.pyi @@ -0,0 +1,4 @@ +from email.mime.base import MIMEBase + +class MIMEMultipart(MIMEBase): + def __init__(self, _subtype=..., boundary=..., _subparts=..., **_params) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/email/mime/nonmultipart.pyi b/client/typeshed-fallback/stdlib/2/email/mime/nonmultipart.pyi new file mode 100644 index 000000000..04d130e3d --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/mime/nonmultipart.pyi @@ -0,0 +1,4 @@ +from email.mime.base import MIMEBase + +class MIMENonMultipart(MIMEBase): + def attach(self, payload): ... diff --git a/client/typeshed-fallback/stdlib/2/email/mime/text.pyi b/client/typeshed-fallback/stdlib/2/email/mime/text.pyi new file mode 100644 index 000000000..3b059778a --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/mime/text.pyi @@ -0,0 +1,4 @@ +from email.mime.nonmultipart import MIMENonMultipart + +class MIMEText(MIMENonMultipart): + def __init__(self, _text, _subtype=..., _charset=...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/email/parser.pyi b/client/typeshed-fallback/stdlib/2/email/parser.pyi new file mode 100644 index 000000000..4f2282834 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/parser.pyi @@ -0,0 +1,10 @@ +from .feedparser import FeedParser as FeedParser # not in __all__ but listed in documentation + +class Parser: + def __init__(self, *args, **kws) -> None: ... + def parse(self, fp, headersonly: bool = ...): ... + def parsestr(self, text, headersonly: bool = ...): ... + +class HeaderParser(Parser): + def parse(self, fp, headersonly: bool = ...): ... + def parsestr(self, text, headersonly: bool = ...): ... diff --git a/client/typeshed-fallback/stdlib/2/email/quoprimime.pyi b/client/typeshed-fallback/stdlib/2/email/quoprimime.pyi new file mode 100644 index 000000000..3f2963c06 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/quoprimime.pyi @@ -0,0 +1,18 @@ +def header_quopri_check(c): ... +def body_quopri_check(c): ... +def header_quopri_len(s): ... +def body_quopri_len(str): ... +def unquote(s): ... +def quote(c): ... +def header_encode(header, charset: str = ..., keep_eols: bool = ..., maxlinelen: int = ..., eol=...): ... +def encode(body, binary: bool = ..., maxlinelen: int = ..., eol=...): ... + +body_encode = encode +encodestring = encode + +def decode(encoded, eol=...): ... + +body_decode = decode +decodestring = decode + +def header_decode(s): ... diff --git a/client/typeshed-fallback/stdlib/2/email/utils.pyi b/client/typeshed-fallback/stdlib/2/email/utils.pyi new file mode 100644 index 000000000..7b868efce --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/email/utils.pyi @@ -0,0 +1,19 @@ +from email._parseaddr import AddressList as _AddressList +from email._parseaddr import mktime_tz as mktime_tz +from email._parseaddr import parsedate as _parsedate +from email._parseaddr import parsedate_tz as _parsedate_tz +from quopri import decodestring as _qdecode +from typing import Optional, Any + +def formataddr(pair): ... +def getaddresses(fieldvalues): ... +def formatdate(timeval: Optional[Any] = ..., localtime: bool = ..., usegmt: bool = ...): ... +def make_msgid(idstring: Optional[Any] = ...): ... +def parsedate(data): ... +def parsedate_tz(data): ... +def parseaddr(addr): ... +def unquote(str): ... +def decode_rfc2231(s): ... +def encode_rfc2231(s, charset: Optional[Any] = ..., language: Optional[Any] = ...): ... +def decode_params(params): ... +def collapse_rfc2231_value(value, errors=..., fallback_charset=...): ... diff --git a/client/typeshed-fallback/stdlib/2/encodings/__init__.pyi b/client/typeshed-fallback/stdlib/2/encodings/__init__.pyi new file mode 100644 index 000000000..2ae6c0a93 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/encodings/__init__.pyi @@ -0,0 +1,6 @@ +import codecs + +import typing + +def search_function(encoding: str) -> codecs.CodecInfo: + ... diff --git a/client/typeshed-fallback/stdlib/2/encodings/utf_8.pyi b/client/typeshed-fallback/stdlib/2/encodings/utf_8.pyi new file mode 100644 index 000000000..d38bd58d0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/encodings/utf_8.pyi @@ -0,0 +1,15 @@ +import codecs +from typing import Text, Tuple + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: Text, final: bool = ...) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input: bytes, errors: str, final: bool) -> Tuple[Text, int]: ... + +class StreamWriter(codecs.StreamWriter): ... +class StreamReader(codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... +def encode(input: Text, errors: Text = ...) -> bytes: ... +def decode(input: bytes, errors: Text = ...) -> Text: ... diff --git a/client/typeshed-fallback/stdlib/2/exceptions.pyi b/client/typeshed-fallback/stdlib/2/exceptions.pyi new file mode 100644 index 000000000..6e4bafc9a --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/exceptions.pyi @@ -0,0 +1,48 @@ +from __builtin__ import ArithmeticError as ArithmeticError +from __builtin__ import AssertionError as AssertionError +from __builtin__ import AttributeError as AttributeError +from __builtin__ import BaseException as BaseException +from __builtin__ import BufferError as BufferError +from __builtin__ import BytesWarning as BytesWarning +from __builtin__ import DeprecationWarning as DeprecationWarning +from __builtin__ import EOFError as EOFError +from __builtin__ import EnvironmentError as EnvironmentError +from __builtin__ import Exception as Exception +from __builtin__ import FloatingPointError as FloatingPointError +from __builtin__ import FutureWarning as FutureWarning +from __builtin__ import GeneratorExit as GeneratorExit +from __builtin__ import IOError as IOError +from __builtin__ import ImportError as ImportError +from __builtin__ import ImportWarning as ImportWarning +from __builtin__ import IndentationError as IndentationError +from __builtin__ import IndexError as IndexError +from __builtin__ import KeyError as KeyError +from __builtin__ import KeyboardInterrupt as KeyboardInterrupt +from __builtin__ import LookupError as LookupError +from __builtin__ import MemoryError as MemoryError +from __builtin__ import NameError as NameError +from __builtin__ import NotImplementedError as NotImplementedError +from __builtin__ import OSError as OSError +from __builtin__ import OverflowError as OverflowError +from __builtin__ import PendingDeprecationWarning as PendingDeprecationWarning +from __builtin__ import ReferenceError as ReferenceError +from __builtin__ import RuntimeError as RuntimeError +from __builtin__ import RuntimeWarning as RuntimeWarning +from __builtin__ import StandardError as StandardError +from __builtin__ import StopIteration as StopIteration +from __builtin__ import SyntaxError as SyntaxError +from __builtin__ import SyntaxWarning as SyntaxWarning +from __builtin__ import SystemError as SystemError +from __builtin__ import SystemExit as SystemExit +from __builtin__ import TabError as TabError +from __builtin__ import TypeError as TypeError +from __builtin__ import UnboundLocalError as UnboundLocalError +from __builtin__ import UnicodeError as UnicodeError +from __builtin__ import UnicodeDecodeError as UnicodeDecodeError +from __builtin__ import UnicodeEncodeError as UnicodeEncodeError +from __builtin__ import UnicodeTranslateError as UnicodeTranslateError +from __builtin__ import UnicodeWarning as UnicodeWarning +from __builtin__ import UserWarning as UserWarning +from __builtin__ import ValueError as ValueError +from __builtin__ import Warning as Warning +from __builtin__ import ZeroDivisionError as ZeroDivisionError diff --git a/client/typeshed-fallback/stdlib/2/fcntl.pyi b/client/typeshed-fallback/stdlib/2/fcntl.pyi new file mode 100644 index 000000000..c7ff895e4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/fcntl.pyi @@ -0,0 +1,87 @@ +from typing import Any, Union, IO +import io + +FASYNC = ... # type: int +FD_CLOEXEC = ... # type: int + +DN_ACCESS = ... # type: int +DN_ATTRIB = ... # type: int +DN_CREATE = ... # type: int +DN_DELETE = ... # type: int +DN_MODIFY = ... # type: int +DN_MULTISHOT = ... # type: int +DN_RENAME = ... # type: int +F_DUPFD = ... # type: int +F_EXLCK = ... # type: int +F_GETFD = ... # type: int +F_GETFL = ... # type: int +F_GETLEASE = ... # type: int +F_GETLK = ... # type: int +F_GETLK64 = ... # type: int +F_GETOWN = ... # type: int +F_GETSIG = ... # type: int +F_NOTIFY = ... # type: int +F_RDLCK = ... # type: int +F_SETFD = ... # type: int +F_SETFL = ... # type: int +F_SETLEASE = ... # type: int +F_SETLK = ... # type: int +F_SETLK64 = ... # type: int +F_SETLKW = ... # type: int +F_SETLKW64 = ... # type: int +F_SETOWN = ... # type: int +F_SETSIG = ... # type: int +F_SHLCK = ... # type: int +F_UNLCK = ... # type: int +F_WRLCK = ... # type: int +I_ATMARK = ... # type: int +I_CANPUT = ... # type: int +I_CKBAND = ... # type: int +I_FDINSERT = ... # type: int +I_FIND = ... # type: int +I_FLUSH = ... # type: int +I_FLUSHBAND = ... # type: int +I_GETBAND = ... # type: int +I_GETCLTIME = ... # type: int +I_GETSIG = ... # type: int +I_GRDOPT = ... # type: int +I_GWROPT = ... # type: int +I_LINK = ... # type: int +I_LIST = ... # type: int +I_LOOK = ... # type: int +I_NREAD = ... # type: int +I_PEEK = ... # type: int +I_PLINK = ... # type: int +I_POP = ... # type: int +I_PUNLINK = ... # type: int +I_PUSH = ... # type: int +I_RECVFD = ... # type: int +I_SENDFD = ... # type: int +I_SETCLTIME = ... # type: int +I_SETSIG = ... # type: int +I_SRDOPT = ... # type: int +I_STR = ... # type: int +I_SWROPT = ... # type: int +I_UNLINK = ... # type: int +LOCK_EX = ... # type: int +LOCK_MAND = ... # type: int +LOCK_NB = ... # type: int +LOCK_READ = ... # type: int +LOCK_RW = ... # type: int +LOCK_SH = ... # type: int +LOCK_UN = ... # type: int +LOCK_WRITE = ... # type: int + +_ANYFILE = Union[int, IO] + +# TODO All these return either int or bytes depending on the value of +# cmd (not on the type of arg). +def fcntl(fd: _ANYFILE, op: int, arg: Union[int, bytes] = ...) -> Any: ... + +# TODO: arg: int or read-only buffer interface or read-write buffer interface +def ioctl(fd: _ANYFILE, op: int, arg: Union[int, bytes] = ..., + mutate_flag: bool = ...) -> Any: ... + +def flock(fd: _ANYFILE, op: int) -> None: ... +def lockf(fd: _ANYFILE, op: int, length: int = ..., start: int = ..., + whence: int = ...) -> Any: ... diff --git a/client/typeshed-fallback/stdlib/2/fnmatch.pyi b/client/typeshed-fallback/stdlib/2/fnmatch.pyi new file mode 100644 index 000000000..e933b7b2c --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/fnmatch.pyi @@ -0,0 +1,8 @@ +from typing import AnyStr, Iterable, List, Union + +_EitherStr = Union[str, unicode] + +def fnmatch(filename: _EitherStr, pattern: _EitherStr) -> bool: ... +def fnmatchcase(filename: _EitherStr, pattern: _EitherStr) -> bool: ... +def filter(names: Iterable[AnyStr], pattern: _EitherStr) -> List[AnyStr]: ... +def translate(pattern: AnyStr) -> AnyStr: ... diff --git a/client/typeshed-fallback/stdlib/2/functools.pyi b/client/typeshed-fallback/stdlib/2/functools.pyi new file mode 100644 index 000000000..a0e1a8fa2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/functools.pyi @@ -0,0 +1,34 @@ +# Stubs for functools (Python 2.7) + +# NOTE: These are incomplete! + +from abc import ABCMeta, abstractmethod +from typing import Any, Callable, Generic, Dict, Iterable, Optional, Sequence, Tuple, TypeVar, overload +from collections import namedtuple + +_AnyCallable = Callable[..., Any] + +_T = TypeVar("_T") +_S = TypeVar("_S") +@overload +def reduce(function: Callable[[_T, _T], _T], + sequence: Iterable[_T]) -> _T: ... +@overload +def reduce(function: Callable[[_T, _S], _T], + sequence: Iterable[_S], initial: _T) -> _T: ... + +WRAPPER_ASSIGNMENTS = ... # type: Sequence[str] +WRAPPER_UPDATES = ... # type: Sequence[str] + +def update_wrapper(wrapper: _AnyCallable, wrapped: _AnyCallable, assigned: Sequence[str] = ..., + updated: Sequence[str] = ...) -> _AnyCallable: ... +def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_AnyCallable], _AnyCallable]: ... +def total_ordering(cls: type) -> type: ... +def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], Any]: ... + +class partial(Generic[_T]): + func = ... # Callable[..., _T] + args = ... # type: Tuple[Any, ...] + keywords = ... # type: Dict[str, Any] + def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> _T: ... diff --git a/client/typeshed-fallback/stdlib/2/future_builtins.pyi b/client/typeshed-fallback/stdlib/2/future_builtins.pyi new file mode 100644 index 000000000..a9b25b2fe --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/future_builtins.pyi @@ -0,0 +1,14 @@ +from typing import Any + +from itertools import ifilter as filter +from itertools import imap as map +from itertools import izip as zip + + +def ascii(obj: Any) -> str: ... + + +def hex(x: int) -> str: ... + + +def oct(x: int) -> str: ... diff --git a/client/typeshed-fallback/stdlib/2/gc.pyi b/client/typeshed-fallback/stdlib/2/gc.pyi new file mode 100644 index 000000000..d93e996a5 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/gc.pyi @@ -0,0 +1,29 @@ +# Stubs for gc + +from typing import Any, List, Tuple + + +def enable() -> None: ... +def disable() -> None: ... +def isenabled() -> bool: ... +def collect(generation: int = ...) -> int: ... +def set_debug(flags: int) -> None: ... +def get_debug() -> int: ... +def get_objects() -> List[Any]: ... +def set_threshold(threshold0: int, threshold1: int = ..., + threshold2: int = ...) -> None: ... +def get_count() -> Tuple[int, int, int]: ... +def get_threshold() -> Tuple[int, int, int]: ... +def get_referrers(*objs: Any) -> List[Any]: ... +def get_referents(*objs: Any) -> List[Any]: ... +def is_tracked(obj: Any) -> bool: ... + +garbage = ... # type: List[Any] + +DEBUG_STATS = ... # type: int +DEBUG_COLLECTABLE = ... # type: int +DEBUG_UNCOLLECTABLE = ... # type: int +DEBUG_INSTANCES = ... # type: int +DEBUG_OBJECTS = ... # type: int +DEBUG_SAVEALL = ... # type: int +DEBUG_LEAK = ... # type: int diff --git a/client/typeshed-fallback/stdlib/2/getopt.pyi b/client/typeshed-fallback/stdlib/2/getopt.pyi new file mode 100644 index 000000000..d6d6cb4e9 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/getopt.pyi @@ -0,0 +1,12 @@ +from typing import List, Tuple + +class GetoptError(Exception): + opt = ... # type: str + msg = ... # type: str + def __init__(self, msg: str, opt: str = ...) -> None: ... + def __str__(self) -> str: ... + +error = GetoptError + +def getopt(args: List[str], shortopts: str, longopts: List[str] = ...) -> Tuple[List[Tuple[str, str]], List[str]]: ... +def gnu_getopt(args: List[str], shortopts: str, longopts: List[str] = ...) -> Tuple[List[Tuple[str, str]], List[str]]: ... diff --git a/client/typeshed-fallback/stdlib/2/getpass.pyi b/client/typeshed-fallback/stdlib/2/getpass.pyi new file mode 100644 index 000000000..011fc8e79 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/getpass.pyi @@ -0,0 +1,8 @@ +# Stubs for getpass (Python 2) + +from typing import Any, IO + +class GetPassWarning(UserWarning): ... + +def getpass(prompt: str = ..., stream: IO[Any] = ...) -> str: ... +def getuser() -> str: ... diff --git a/client/typeshed-fallback/stdlib/2/gettext.pyi b/client/typeshed-fallback/stdlib/2/gettext.pyi new file mode 100644 index 000000000..a12d54123 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/gettext.pyi @@ -0,0 +1,41 @@ +from typing import Any, Container, Dict, IO, List, Optional, Sequence, Type, Union + +def bindtextdomain(domain: str, localedir: str = ...) -> str: ... +def bind_textdomain_codeset(domain: str, codeset: str = ...) -> str: ... +def textdomain(domain: str = ...) -> str: ... +def gettext(message: str) -> str: ... +def lgettext(message: str) -> str: ... +def dgettext(domain: str, message: str) -> str: ... +def ldgettext(domain: str, message: str) -> str: ... +def ngettext(singular: str, plural: str, n: int) -> str: ... +def lngettext(singular: str, plural: str, n: int) -> str: ... +def dngettext(domain: str, singular: str, plural: str, n: int) -> str: ... +def ldngettext(domain: str, singular: str, plural: str, n: int) -> str: ... + +class NullTranslations(object): + def __init__(self, fp: IO[str] = ...) -> None: ... + def _parse(self, fp: IO[str]) -> None: ... + def add_fallback(self, fallback: NullTranslations) -> None: ... + def gettext(self, message: str) -> str: ... + def lgettext(self, message: str) -> str: ... + def ugettext(self, message: Union[str, unicode]) -> unicode: ... + def ngettext(self, singular: str, plural: str, n: int) -> str: ... + def lngettext(self, singular: str, plural: str, n: int) -> str: ... + def ungettext(self, singular: Union[str, unicode], plural: Union[str, unicode], n: int) -> unicode: ... + def info(self) -> Dict[str, str]: ... + def charset(self) -> Optional[str]: ... + def output_charset(self) -> Optional[str]: ... + def set_output_charset(self, charset: Optional[str]) -> None: ... + def install(self, unicode: bool = ..., names: Container[str] = ...) -> None: ... + +class GNUTranslations(NullTranslations): + LE_MAGIC = ... # type: int + BE_MAGIC = ... # type: int + +def find(domain: str, localedir: Optional[str] = ..., languages: Optional[Sequence[str]] = ..., + all: Any = ...) -> Optional[Union[str, List[str]]]: ... + +def translation(domain: str, localedir: Optional[str] = ..., languages: Optional[Sequence[str]] = ..., + class_: Optional[Type[NullTranslations]] = ..., fallback: bool = ..., codeset: Optional[str] = ...) -> NullTranslations: ... +def install(domain: str, localedir: Optional[str] = ..., unicode: bool = ..., codeset: Optional[str] = ..., + names: Container[str] = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/glob.pyi b/client/typeshed-fallback/stdlib/2/glob.pyi new file mode 100644 index 000000000..667a51f2f --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/glob.pyi @@ -0,0 +1,6 @@ +from typing import List, Iterator, Union, AnyStr + +def glob(pathname: AnyStr) -> List[AnyStr]: ... +def iglob(pathname: AnyStr) -> Iterator[AnyStr]: ... +def glob1(dirname: Union[str, unicode], pattern: AnyStr) -> List[AnyStr]: ... +def glob0(dirname: Union[str, unicode], basename: AnyStr) -> List[AnyStr]: ... diff --git a/client/typeshed-fallback/stdlib/2/gzip.pyi b/client/typeshed-fallback/stdlib/2/gzip.pyi new file mode 100644 index 000000000..3177bbaf9 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/gzip.pyi @@ -0,0 +1,37 @@ +from typing import Any, IO, Text +import io + +class GzipFile(io.BufferedIOBase): + myfileobj = ... # type: Any + max_read_chunk = ... # type: Any + mode = ... # type: Any + extrabuf = ... # type: Any + extrasize = ... # type: Any + extrastart = ... # type: Any + name = ... # type: Any + min_readsize = ... # type: Any + compress = ... # type: Any + fileobj = ... # type: Any + offset = ... # type: Any + mtime = ... # type: Any + def __init__(self, filename: str = ..., mode: Text = ..., compresslevel: int = ..., + fileobj: IO[str] = ..., mtime: float = ...) -> None: ... + @property + def filename(self): ... + size = ... # type: Any + crc = ... # type: Any + def write(self, data): ... + def read(self, size=...): ... + @property + def closed(self): ... + def close(self): ... + def flush(self, zlib_mode=...): ... + def fileno(self): ... + def rewind(self): ... + def readable(self): ... + def writable(self): ... + def seekable(self): ... + def seek(self, offset, whence=...): ... + def readline(self, size=...): ... + +def open(filename: str, mode: Text = ..., compresslevel: int = ...) -> GzipFile: ... diff --git a/client/typeshed-fallback/stdlib/2/hashlib.pyi b/client/typeshed-fallback/stdlib/2/hashlib.pyi new file mode 100644 index 000000000..fa1dbce59 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/hashlib.pyi @@ -0,0 +1,31 @@ +# Stubs for hashlib (Python 2) + +from typing import Tuple, Union + +_DataType = Union[str, unicode, bytearray, buffer, memoryview] + +class _hash(object): # This is not actually in the module namespace. + name = ... # type: str + block_size = 0 + digest_size = 0 + digestsize = 0 + def __init__(self, arg: _DataType = ...) -> None: ... + def update(self, arg: _DataType) -> None: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def copy(self) -> _hash: ... + +def new(name: str, data: str = ...) -> _hash: ... + +def md5(s: _DataType = ...) -> _hash: ... +def sha1(s: _DataType = ...) -> _hash: ... +def sha224(s: _DataType = ...) -> _hash: ... +def sha256(s: _DataType = ...) -> _hash: ... +def sha384(s: _DataType = ...) -> _hash: ... +def sha512(s: _DataType = ...) -> _hash: ... + +algorithms = ... # type: Tuple[str, ...] +algorithms_guaranteed = ... # type: Tuple[str, ...] +algorithms_available = ... # type: Tuple[str, ...] + +def pbkdf2_hmac(name: str, password: str, salt: str, rounds: int, dklen: int = ...) -> str: ... diff --git a/client/typeshed-fallback/stdlib/2/heapq.pyi b/client/typeshed-fallback/stdlib/2/heapq.pyi new file mode 100644 index 000000000..00abb31a6 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/heapq.pyi @@ -0,0 +1,16 @@ +from typing import TypeVar, List, Iterable, Any, Callable, Optional + +_T = TypeVar('_T') + +def cmp_lt(x, y) -> bool: ... +def heappush(heap: List[_T], item: _T) -> None: ... +def heappop(heap: List[_T]) -> _T: + raise IndexError() # if heap is empty +def heappushpop(heap: List[_T], item: _T) -> _T: ... +def heapify(x: List[_T]) -> None: ... +def heapreplace(heap: List[_T], item: _T) -> _T: + raise IndexError() # if heap is empty +def merge(*iterables: Iterable[_T]) -> Iterable[_T]: ... +def nlargest(n: int, iterable: Iterable[_T], + key: Optional[Callable[[_T], Any]] = ...) -> List[_T]: ... +def nsmallest(n: int, iterable: Iterable[_T]) -> List[_T]: ... diff --git a/client/typeshed-fallback/stdlib/2/htmlentitydefs.pyi b/client/typeshed-fallback/stdlib/2/htmlentitydefs.pyi new file mode 100644 index 000000000..08445e6d9 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/htmlentitydefs.pyi @@ -0,0 +1,5 @@ +from typing import Any, Mapping + +name2codepoint = ... # type: Mapping[str, int] +codepoint2name = ... # type: Mapping[int, str] +entitydefs = ... # type: Mapping[str, str] diff --git a/client/typeshed-fallback/stdlib/2/httplib.pyi b/client/typeshed-fallback/stdlib/2/httplib.pyi new file mode 100644 index 000000000..6f7eae0fd --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/httplib.pyi @@ -0,0 +1,205 @@ +# Stubs for httplib (Python 2) +# +# Generated by stubgen and manually massaged a bit. +# Needs lots more work! + +from typing import Any, Dict, Optional, Protocol +import mimetools +import ssl + +class HTTPMessage(mimetools.Message): + def addcontinue(self, key: str, more: str) -> None: ... + dict = ... # type: Dict[str, str] + def addheader(self, key: str, value: str) -> None: ... + unixfrom = ... # type: str + headers = ... # type: Any + status = ... # type: str + seekable = ... # type: bool + def readheaders(self) -> None: ... + +class HTTPResponse: + fp = ... # type: Any + debuglevel = ... # type: Any + strict = ... # type: Any + msg = ... # type: Any + version = ... # type: Any + status = ... # type: Any + reason = ... # type: Any + chunked = ... # type: Any + chunk_left = ... # type: Any + length = ... # type: Any + will_close = ... # type: Any + def __init__(self, sock, debuglevel: int = ..., strict: int = ..., method: Optional[Any] = ..., + buffering: bool = ...) -> None: ... + def begin(self): ... + def close(self): ... + def isclosed(self): ... + def read(self, amt: Optional[Any] = ...): ... + def fileno(self): ... + def getheader(self, name, default: Optional[Any] = ...): ... + def getheaders(self): ... + +# This is an API stub only for HTTPConnection and HTTPSConnection, as used in +# urllib2.AbstractHTTPHandler.do_open, which takes either the class +# HTTPConnection or the class HTTPSConnection, *not* an instance of either +# class. do_open does not use all of the parameters of HTTPConnection.__init__ +# or HTTPSConnection.__init__, so HTTPConnectionProtocol only implements the +# parameters that do_open does use. +class HTTPConnectionProtocol(Protocol): + def __call__(self, host: str, timeout: int = ..., **http_con_args: Any) -> HTTPConnection: ... + +class HTTPConnection: + response_class = ... # type: Any + default_port = ... # type: Any + auto_open = ... # type: Any + debuglevel = ... # type: Any + strict = ... # type: Any + timeout = ... # type: Any + source_address = ... # type: Any + sock = ... # type: Any + host: str = ... + port: int = ... + def __init__(self, host, port: Optional[Any] = ..., strict: Optional[Any] = ..., timeout=..., + source_address: Optional[Any] = ...) -> None: ... + def set_tunnel(self, host, port: Optional[Any] = ..., headers: Optional[Any] = ...): ... + def set_debuglevel(self, level): ... + def connect(self): ... + def close(self): ... + def send(self, data): ... + def putrequest(self, method, url, skip_host: int = ..., skip_accept_encoding: int = ...): ... + def putheader(self, header, *values): ... + def endheaders(self, message_body: Optional[Any] = ...): ... + def request(self, method, url, body: Optional[Any] = ..., headers=...): ... + def getresponse(self, buffering: bool = ...): ... + +class HTTP: + debuglevel = ... # type: Any + def __init__(self, host: str = ..., port: Optional[Any] = ..., strict: Optional[Any] = ...) -> None: ... + def connect(self, host: Optional[Any] = ..., port: Optional[Any] = ...): ... + def getfile(self): ... + file = ... # type: Any + headers = ... # type: Any + def getreply(self, buffering: bool = ...): ... + def close(self): ... + +class HTTPSConnection(HTTPConnection): + default_port = ... # type: Any + key_file = ... # type: Any + cert_file = ... # type: Any + def __init__(self, host, port: Optional[Any] = ..., key_file: Optional[Any] = ..., cert_file: Optional[Any] = ..., + strict: Optional[Any] = ..., timeout=..., source_address: Optional[Any] = ..., + context: Optional[Any] = ...) -> None: ... + sock = ... # type: Any + def connect(self): ... + +class HTTPS(HTTP): + key_file = ... # type: Any + cert_file = ... # type: Any + def __init__(self, host: str = ..., port: Optional[Any] = ..., key_file: Optional[Any] = ..., cert_file: Optional[Any] = ..., strict: Optional[Any] = ..., context: Optional[Any] = ...) -> None: ... + +class HTTPException(Exception): ... +class NotConnected(HTTPException): ... +class InvalidURL(HTTPException): ... + +class UnknownProtocol(HTTPException): + args = ... # type: Any + version = ... # type: Any + def __init__(self, version) -> None: ... + +class UnknownTransferEncoding(HTTPException): ... +class UnimplementedFileMode(HTTPException): ... + +class IncompleteRead(HTTPException): + args = ... # type: Any + partial = ... # type: Any + expected = ... # type: Any + def __init__(self, partial, expected: Optional[Any] = ...) -> None: ... + +class ImproperConnectionState(HTTPException): ... +class CannotSendRequest(ImproperConnectionState): ... +class CannotSendHeader(ImproperConnectionState): ... +class ResponseNotReady(ImproperConnectionState): ... + +class BadStatusLine(HTTPException): + args = ... # type: Any + line = ... # type: Any + def __init__(self, line) -> None: ... + +class LineTooLong(HTTPException): + def __init__(self, line_type) -> None: ... + +error = ... # type: Any + +class LineAndFileWrapper: + def __init__(self, line, file) -> None: ... + def __getattr__(self, attr): ... + def read(self, amt: Optional[Any] = ...): ... + def readline(self): ... + def readlines(self, size: Optional[Any] = ...): ... + +# Constants + +responses = ... # type: Dict[int, str] + +HTTP_PORT = ... # type: int +HTTPS_PORT = ... # type: int + +# status codes +# informational +CONTINUE = ... # type: int +SWITCHING_PROTOCOLS = ... # type: int +PROCESSING = ... # type: int + +# successful +OK = ... # type: int +CREATED = ... # type: int +ACCEPTED = ... # type: int +NON_AUTHORITATIVE_INFORMATION = ... # type: int +NO_CONTENT = ... # type: int +RESET_CONTENT = ... # type: int +PARTIAL_CONTENT = ... # type: int +MULTI_STATUS = ... # type: int +IM_USED = ... # type: int + +# redirection +MULTIPLE_CHOICES = ... # type: int +MOVED_PERMANENTLY = ... # type: int +FOUND = ... # type: int +SEE_OTHER = ... # type: int +NOT_MODIFIED = ... # type: int +USE_PROXY = ... # type: int +TEMPORARY_REDIRECT = ... # type: int + +# client error +BAD_REQUEST = ... # type: int +UNAUTHORIZED = ... # type: int +PAYMENT_REQUIRED = ... # type: int +FORBIDDEN = ... # type: int +NOT_FOUND = ... # type: int +METHOD_NOT_ALLOWED = ... # type: int +NOT_ACCEPTABLE = ... # type: int +PROXY_AUTHENTICATION_REQUIRED = ... # type: int +REQUEST_TIMEOUT = ... # type: int +CONFLICT = ... # type: int +GONE = ... # type: int +LENGTH_REQUIRED = ... # type: int +PRECONDITION_FAILED = ... # type: int +REQUEST_ENTITY_TOO_LARGE = ... # type: int +REQUEST_URI_TOO_LONG = ... # type: int +UNSUPPORTED_MEDIA_TYPE = ... # type: int +REQUESTED_RANGE_NOT_SATISFIABLE = ... # type: int +EXPECTATION_FAILED = ... # type: int +UNPROCESSABLE_ENTITY = ... # type: int +LOCKED = ... # type: int +FAILED_DEPENDENCY = ... # type: int +UPGRADE_REQUIRED = ... # type: int + +# server error +INTERNAL_SERVER_ERROR = ... # type: int +NOT_IMPLEMENTED = ... # type: int +BAD_GATEWAY = ... # type: int +SERVICE_UNAVAILABLE = ... # type: int +GATEWAY_TIMEOUT = ... # type: int +HTTP_VERSION_NOT_SUPPORTED = ... # type: int +INSUFFICIENT_STORAGE = ... # type: int +NOT_EXTENDED = ... # type: int diff --git a/client/typeshed-fallback/stdlib/2/imp.pyi b/client/typeshed-fallback/stdlib/2/imp.pyi new file mode 100644 index 000000000..ffb1ad367 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/imp.pyi @@ -0,0 +1,35 @@ +"""Stubs for the 'imp' module.""" + +from typing import List, Optional, Tuple, Iterable, IO, Any +import types + +C_BUILTIN = ... # type: int +C_EXTENSION = ... # type: int +IMP_HOOK = ... # type: int +PKG_DIRECTORY = ... # type: int +PY_CODERESOURCE = ... # type: int +PY_COMPILED = ... # type: int +PY_FROZEN = ... # type: int +PY_RESOURCE = ... # type: int +PY_SOURCE = ... # type: int +SEARCH_ERROR = ... # type: int + +def acquire_lock() -> None: ... +def find_module(name: str, path: Iterable[str] = ...) -> Optional[Tuple[str, str, Tuple[str, str, int]]]: ... +def get_magic() -> str: ... +def get_suffixes() -> List[Tuple[str, str, int]]: ... +def init_builtin(name: str) -> types.ModuleType: ... +def init_frozen(name: str) -> types.ModuleType: ... +def is_builtin(name: str) -> int: ... +def is_frozen(name: str) -> bool: ... +def load_compiled(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... +def load_dynamic(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... +def load_module(name: str, file: str, pathname: str, description: Tuple[str, str, int]) -> types.ModuleType: ... +def load_source(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... +def lock_held() -> bool: ... +def new_module(name: str) -> types.ModuleType: ... +def release_lock() -> None: ... + +class NullImporter: + def __init__(self, path_string: str) -> None: ... + def find_module(self, fullname: str, path: str = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/importlib.pyi b/client/typeshed-fallback/stdlib/2/importlib.pyi new file mode 100644 index 000000000..8bb179a4b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/importlib.pyi @@ -0,0 +1,4 @@ +import types +from typing import Optional, Text + +def import_module(name: Text, package: Optional[Text] = ...) -> types.ModuleType: ... diff --git a/client/typeshed-fallback/stdlib/2/inspect.pyi b/client/typeshed-fallback/stdlib/2/inspect.pyi new file mode 100644 index 000000000..e41fbcc1d --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/inspect.pyi @@ -0,0 +1,135 @@ +from types import CodeType, TracebackType, FrameType, ModuleType +from typing import Any, Dict, Callable, List, NamedTuple, Optional, Sequence, Tuple, Type, Union + +# Types and members +class EndOfBlock(Exception): ... + +class BlockFinder: + indent: int + islambda: bool + started: bool + passline: bool + last: int + def tokeneater(self, type: int, token: str, srow_scol: Tuple[int, int], + erow_ecol: Tuple[int, int], line: str) -> None: ... + +CO_GENERATOR = ... # type: int +CO_NESTED = ... # type: int +CO_NEWLOCALS = ... # type: int +CO_NOFREE = ... # type: int +CO_OPTIMIZED = ... # type: int +CO_VARARGS = ... # type: int +CO_VARKEYWORDS = ... # type: int +TPFLAGS_IS_ABSTRACT = ... # type: int + +ModuleInfo = NamedTuple('ModuleInfo', [('name', str), + ('suffix', str), + ('mode', str), + ('module_type', int), + ]) +def getmembers( + object: object, + predicate: Optional[Callable[[Any], bool]] = ... +) -> List[Tuple[str, Any]]: ... +def getmoduleinfo(path: str) -> Optional[ModuleInfo]: ... +def getmodulename(path: str) -> Optional[str]: ... + +def ismodule(object: object) -> bool: ... +def isclass(object: object) -> bool: ... +def ismethod(object: object) -> bool: ... +def isfunction(object: object) -> bool: ... +def isgeneratorfunction(object: object) -> bool: ... +def isgenerator(object: object) -> bool: ... +def istraceback(object: object) -> bool: ... +def isframe(object: object) -> bool: ... +def iscode(object: object) -> bool: ... +def isbuiltin(object: object) -> bool: ... +def isroutine(object: object) -> bool: ... +def isabstract(object: object) -> bool: ... +def ismethoddescriptor(object: object) -> bool: ... +def isdatadescriptor(object: object) -> bool: ... +def isgetsetdescriptor(object: object) -> bool: ... +def ismemberdescriptor(object: object) -> bool: ... + +# Retrieving source code +def findsource(object: object) -> Tuple[List[str], int]: ... +def getabsfile(object: object) -> str: ... +def getblock(lines: Sequence[str]) -> Sequence[str]: ... +def getdoc(object: object) -> str: ... +def getcomments(object: object) -> str: ... +def getfile(object: object) -> str: ... +def getmodule(object: object) -> ModuleType: ... +def getsourcefile(object: object) -> str: ... +# TODO restrict to "module, class, method, function, traceback, frame, +# or code object" +def getsourcelines(object: object) -> Tuple[List[str], int]: ... +# TODO restrict to "a module, class, method, function, traceback, frame, +# or code object" +def getsource(object: object) -> str: ... +def cleandoc(doc: str) -> str: ... +def indentsize(line: str) -> int: ... + +# Classes and functions +def getclasstree(classes: List[type], unique: bool = ...) -> List[ + Union[Tuple[type, Tuple[type, ...]], list]]: ... + +ArgSpec = NamedTuple('ArgSpec', [('args', List[str]), + ('varargs', Optional[str]), + ('keywords', Optional[str]), + ('defaults', tuple), + ]) + +ArgInfo = NamedTuple('ArgInfo', [('args', List[str]), + ('varargs', Optional[str]), + ('keywords', Optional[str]), + ('locals', Dict[str, Any]), + ]) + +Arguments = NamedTuple('Arguments', [('args', List[Union[str, List[Any]]]), + ('varargs', Optional[str]), + ('keywords', Optional[str]), + ]) + +def getargs(co: CodeType) -> Arguments: ... +def getargspec(func: object) -> ArgSpec: ... +def getargvalues(frame: FrameType) -> ArgInfo: ... +def formatargspec(args, varargs=..., varkw=..., defaults=..., + formatarg=..., formatvarargs=..., formatvarkw=..., formatvalue=..., + join=...) -> str: ... +def formatargvalues(args, varargs=..., varkw=..., defaults=..., + formatarg=..., formatvarargs=..., formatvarkw=..., formatvalue=..., + join=...) -> str: ... +def getmro(cls: type) -> Tuple[type, ...]: ... +def getcallargs(func, *args, **kwds) -> Dict[str, Any]: ... + +# The interpreter stack + +Traceback = NamedTuple( + 'Traceback', + [ + ('filename', str), + ('lineno', int), + ('function', str), + ('code_context', List[str]), + ('index', int), + ] +) + +_FrameInfo = Tuple[FrameType, str, int, str, List[str], int] + +def getouterframes(frame: FrameType, context: int = ...) -> List[_FrameInfo]: ... +def getframeinfo(frame: Union[FrameType, TracebackType], context: int = ...) -> Traceback: ... +def getinnerframes(traceback: TracebackType, context: int = ...) -> List[_FrameInfo]: ... +def getlineno(frame: FrameType) -> int: ... + +def currentframe(depth: int = ...) -> FrameType: ... +def stack(context: int = ...) -> List[_FrameInfo]: ... +def trace(context: int = ...) -> List[_FrameInfo]: ... + +Attribute = NamedTuple('Attribute', [('name', str), + ('kind', str), + ('defining_class', type), + ('object', object), + ]) + +def classify_class_attrs(cls: type) -> List[Attribute]: ... diff --git a/client/typeshed-fallback/stdlib/2/io.pyi b/client/typeshed-fallback/stdlib/2/io.pyi new file mode 100644 index 000000000..56255bac2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/io.pyi @@ -0,0 +1,42 @@ +# Stubs for io + +# Based on https://docs.python.org/2/library/io.html + +# Only a subset of functionality is included. + +from typing import List, BinaryIO, TextIO, IO, overload, Iterator, Iterable, Any, Union, Optional +import _io + +from _io import BlockingIOError as BlockingIOError +from _io import BufferedRWPair as BufferedRWPair +from _io import BufferedRandom as BufferedRandom +from _io import BufferedReader as BufferedReader +from _io import BufferedWriter as BufferedWriter +from _io import BytesIO as BytesIO +from _io import DEFAULT_BUFFER_SIZE as DEFAULT_BUFFER_SIZE +from _io import FileIO as FileIO +from _io import IncrementalNewlineDecoder as IncrementalNewlineDecoder +from _io import StringIO as StringIO +from _io import TextIOWrapper as TextIOWrapper +from _io import UnsupportedOperation as UnsupportedOperation +from _io import open as open + +def _OpenWrapper(file: Union[str, unicode, int], + mode: unicode = ..., buffering: int = ..., encoding: unicode = ..., + errors: unicode = ..., newline: unicode = ..., + closefd: bool = ...) -> IO[Any]: ... + +SEEK_SET = ... # type: int +SEEK_CUR = ... # type: int +SEEK_END = ... # type: int + + +class IOBase(_io._IOBase): ... + +class RawIOBase(_io._RawIOBase, IOBase): ... + +class BufferedIOBase(_io._BufferedIOBase, IOBase): ... + +# Note: In the actual io.py, TextIOBase subclasses IOBase. +# (Which we don't do here because we don't want to subclass both TextIO and BinaryIO.) +class TextIOBase(_io._TextIOBase): ... diff --git a/client/typeshed-fallback/stdlib/2/itertools.pyi b/client/typeshed-fallback/stdlib/2/itertools.pyi new file mode 100644 index 000000000..1c8522c87 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/itertools.pyi @@ -0,0 +1,165 @@ +# Stubs for itertools + +# Based on https://docs.python.org/2/library/itertools.html + +from typing import (Iterator, TypeVar, Iterable, overload, Any, Callable, Tuple, + Union, Sequence, Generic, Optional) + +_T = TypeVar('_T') +_S = TypeVar('_S') + +def count(start: int = ..., + step: int = ...) -> Iterator[int]: ... # more general types? +def cycle(iterable: Iterable[_T]) -> Iterator[_T]: ... + +def repeat(object: _T, times: int = ...) -> Iterator[_T]: ... + +def accumulate(iterable: Iterable[_T]) -> Iterator[_T]: ... + +class chain(Iterator[_T], Generic[_T]): + def __init__(self, *iterables: Iterable[_T]) -> None: ... + def next(self) -> _T: ... + def __iter__(self) -> Iterator[_T]: ... + @staticmethod + def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... + +def compress(data: Iterable[_T], selectors: Iterable[Any]) -> Iterator[_T]: ... +def dropwhile(predicate: Callable[[_T], Any], + iterable: Iterable[_T]) -> Iterator[_T]: ... +def ifilter(predicate: Optional[Callable[[_T], Any]], + iterable: Iterable[_T]) -> Iterator[_T]: ... +def ifilterfalse(predicate: Optional[Callable[[_T], Any]], + iterable: Iterable[_T]) -> Iterator[_T]: ... + +@overload +def groupby(iterable: Iterable[_T], key: None = ...) -> Iterator[Tuple[_T, Iterator[_T]]]: ... +@overload +def groupby(iterable: Iterable[_T], key: Callable[[_T], _S]) -> Iterator[Tuple[_S, Iterator[_T]]]: ... + +@overload +def islice(iterable: Iterable[_T], stop: Optional[int]) -> Iterator[_T]: ... +@overload +def islice(iterable: Iterable[_T], start: Optional[int], stop: Optional[int], + step: Optional[int] = ...) -> Iterator[_T]: ... + +_T1 = TypeVar('_T1') +_T2 = TypeVar('_T2') +_T3 = TypeVar('_T3') +_T4 = TypeVar('_T4') +_T5 = TypeVar('_T5') +_T6 = TypeVar('_T6') + +@overload +def imap(func: Callable[[_T1], _S], iter1: Iterable[_T1]) -> Iterator[_S]: ... +@overload +def imap(func: Callable[[_T1, _T2], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2]) -> Iterator[_S]: ... +@overload +def imap(func: Callable[[_T1, _T2, _T3], _S], + iter1: Iterable[_T1], iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> Iterator[_S]: ... + +@overload +def imap(func: Callable[[_T1, _T2, _T3, _T4], _S], + iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> Iterator[_S]: ... + +@overload +def imap(func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], + iter4: Iterable[_T4], iter5: Iterable[_T5]) -> Iterator[_S]: ... + +@overload +def imap(func: Callable[[_T1, _T2, _T3, _T4, _T5, _T6], _S], + iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], + iter4: Iterable[_T4], iter5: Iterable[_T5], + iter6: Iterable[_T6]) -> Iterator[_S]: ... + +@overload +def imap(func: Callable[..., _S], + iter1: Iterable[Any], iter2: Iterable[Any], iter3: Iterable[Any], + iter4: Iterable[Any], iter5: Iterable[Any], iter6: Iterable[Any], + iter7: Iterable[Any], *iterables: Iterable[Any]) -> Iterator[_S]: ... + +def starmap(func: Any, iterable: Iterable[Any]) -> Iterator[Any]: ... +def takewhile(predicate: Callable[[_T], Any], + iterable: Iterable[_T]) -> Iterator[_T]: ... +def tee(iterable: Iterable[_T], n: int = ...) -> Tuple[Iterator[_T], ...]: ... + +@overload +def izip(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... +@overload +def izip(iter1: Iterable[_T1], + iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... +@overload +def izip(iter1: Iterable[_T1], iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... +@overload +def izip(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> Iterator[Tuple[_T1, _T2, + _T3, _T4]]: ... +@overload +def izip(iter1: Iterable[_T1], iter2: Iterable[_T2], + iter3: Iterable[_T3], iter4: Iterable[_T4], + iter5: Iterable[_T5]) -> Iterator[Tuple[_T1, _T2, + _T3, _T4, _T5]]: ... +@overload +def izip(iter1: Iterable[_T1], iter2: Iterable[_T2], + iter3: Iterable[_T3], iter4: Iterable[_T4], + iter5: Iterable[_T5], iter6: Iterable[_T6]) -> Iterator[Tuple[_T1, _T2, _T3, + _T4, _T5, _T6]]: ... +@overload +def izip(iter1: Iterable[Any], iter2: Iterable[Any], + iter3: Iterable[Any], iter4: Iterable[Any], + iter5: Iterable[Any], iter6: Iterable[Any], + iter7: Iterable[Any], *iterables: Iterable[Any]) -> Iterator[Tuple[Any, ...]]: ... + +def izip_longest(*p: Iterable[Any], + fillvalue: Any = ...) -> Iterator[Any]: ... + +@overload +def product(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... +@overload +def product(iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + iter7: Iterable[Any], + *iterables: Iterable[Any]) -> Iterator[Tuple[Any, ...]]: ... +@overload +def product(*iterables: Iterable[Any], repeat: int) -> Iterator[Tuple[Any, ...]]: ... + +def permutations(iterable: Iterable[_T], + r: int = ...) -> Iterator[Sequence[_T]]: ... +def combinations(iterable: Iterable[_T], + r: int) -> Iterator[Sequence[_T]]: ... +def combinations_with_replacement(iterable: Iterable[_T], + r: int) -> Iterator[Sequence[_T]]: ... diff --git a/client/typeshed-fallback/stdlib/2/json.pyi b/client/typeshed-fallback/stdlib/2/json.pyi new file mode 100644 index 000000000..bd48dc548 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/json.pyi @@ -0,0 +1,96 @@ +from typing import Any, IO, Optional, Tuple, Callable, Dict, List, Union, Text, Protocol + +class JSONDecodeError(ValueError): + def dumps(self, obj: Any) -> str: ... + def dump(self, obj: Any, fp: IO[str], *args: Any, **kwds: Any) -> None: ... + def loads(self, s: str) -> Any: ... + def load(self, fp: IO[str]) -> Any: ... + +def dumps(obj: Any, + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + cls: Any = ..., + indent: Optional[int] = ..., + separators: Optional[Tuple[str, str]] = ..., + encoding: str = ..., + default: Optional[Callable[[Any], Any]] = ..., + sort_keys: bool = ..., + **kwds: Any) -> str: ... + +def dump(obj: Any, + fp: Union[IO[str], IO[Text]], + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + cls: Any = ..., + indent: Optional[int] = ..., + separators: Optional[Tuple[str, str]] = ..., + encoding: str = ..., + default: Optional[Callable[[Any], Any]] = ..., + sort_keys: bool = ..., + **kwds: Any) -> None: ... + +def loads(s: Union[Text, bytes], + encoding: Any = ..., + cls: Any = ..., + object_hook: Optional[Callable[[Dict], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., + **kwds: Any) -> Any: ... + +class _Reader(Protocol): + def read(self) -> Union[Text, bytes]: ... + +def load(fp: _Reader, + encoding: Optional[str] = ..., + cls: Any = ..., + object_hook: Optional[Callable[[Dict], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., + **kwds: Any) -> Any: ... + +class JSONDecoder(object): + def __init__(self, + encoding: Union[Text, bytes] = ..., + object_hook: Callable[..., Any] = ..., + parse_float: Callable[[str], float] = ..., + parse_int: Callable[[str], int] = ..., + parse_constant: Callable[[str], Any] = ..., + strict: bool = ..., + object_pairs_hook: Callable[..., Any] = ...) -> None: ... + def decode(self, s: Union[Text, bytes], _w: Any = ...) -> Any: ... + def raw_decode(self, s: Union[Text, bytes], idx: int = ...) -> Tuple[Any, Any]: ... + +class JSONEncoder(object): + item_separator = ... # type: str + key_separator = ... # type: str + skipkeys = ... # type: bool + ensure_ascii = ... # type: bool + check_circular = ... # type: bool + allow_nan = ... # type: bool + sort_keys = ... # type: bool + indent = ... # type: Optional[int] + + def __init__(self, + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + sort_keys: bool = ..., + indent: Optional[int] = ..., + separators: Tuple[Union[Text, bytes], Union[Text, bytes]] = ..., + encoding: Union[Text, bytes] = ..., + default: Callable[..., Any] = ...) -> None: ... + + def default(self, o: Any) -> Any: ... + + def encode(self, o: Any) -> str: ... + + def iterencode(self, o: Any, _one_shot: bool = ...) -> str: ... diff --git a/client/typeshed-fallback/stdlib/2/markupbase.pyi b/client/typeshed-fallback/stdlib/2/markupbase.pyi new file mode 100644 index 000000000..358ba16c3 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/markupbase.pyi @@ -0,0 +1,9 @@ +from typing import Tuple + +class ParserBase(object): + def __init__(self) -> None: ... + def error(self, message: str) -> None: ... + def reset(self) -> None: ... + def getpos(self) -> Tuple[int, int]: ... + + def unknown_decl(self, data: str) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/md5.pyi b/client/typeshed-fallback/stdlib/2/md5.pyi new file mode 100644 index 000000000..fe6ad719d --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/md5.pyi @@ -0,0 +1,6 @@ +# Stubs for Python 2.7 md5 stdlib module + +from hashlib import md5 as md5, md5 as new + +blocksize = 0 +digest_size = 0 diff --git a/client/typeshed-fallback/stdlib/2/mimetools.pyi b/client/typeshed-fallback/stdlib/2/mimetools.pyi new file mode 100644 index 000000000..99ef5566f --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/mimetools.pyi @@ -0,0 +1,27 @@ +from typing import Any +import rfc822 + +class Message(rfc822.Message): + encodingheader = ... # type: Any + typeheader = ... # type: Any + def __init__(self, fp, seekable: int = ...): ... + plisttext = ... # type: Any + type = ... # type: Any + maintype = ... # type: Any + subtype = ... # type: Any + def parsetype(self): ... + plist = ... # type: Any + def parseplist(self): ... + def getplist(self): ... + def getparam(self, name): ... + def getparamnames(self): ... + def getencoding(self): ... + def gettype(self): ... + def getmaintype(self): ... + def getsubtype(self): ... + +def choose_boundary(): ... +def decode(input, output, encoding): ... +def encode(input, output, encoding): ... +def copyliteral(input, output): ... +def copybinary(input, output): ... diff --git a/client/typeshed-fallback/stdlib/2/multiprocessing/__init__.pyi b/client/typeshed-fallback/stdlib/2/multiprocessing/__init__.pyi new file mode 100644 index 000000000..fb00b245c --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/multiprocessing/__init__.pyi @@ -0,0 +1,50 @@ +from typing import Any, Callable, Optional, TypeVar, Iterable + +from multiprocessing import pool +from multiprocessing.process import Process as Process, current_process as current_process, active_children as active_children +from multiprocessing.util import SUBDEBUG as SUBDEBUG, SUBWARNING as SUBWARNING +from Queue import Queue as _BaseQueue + +class ProcessError(Exception): ... +class BufferTooShort(ProcessError): ... +class TimeoutError(ProcessError): ... +class AuthenticationError(ProcessError): ... + +_T = TypeVar('_T') + +class Queue(_BaseQueue[_T]): + def __init__(self, maxsize: int = ...) -> None: ... + def get(self, block: bool = ..., timeout: Optional[float] = ...) -> _T: ... + def put(self, item: _T, block: bool = ..., timeout: Optional[float] = ...) -> None: ... + def qsize(self) -> int: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def put_nowait(self, item: _T) -> None: ... + def get_nowait(self) -> _T: ... + def close(self) -> None: ... + def join_thread(self) -> None: ... + def cancel_join_thread(self) -> None: ... + +def Manager(): ... +def Pipe(duplex: bool = ...): ... +def cpu_count() -> int: ... +def freeze_support(): ... +def get_logger(): ... +def log_to_stderr(level: Optional[Any] = ...): ... +def allow_connection_pickling(): ... +def Lock(): ... +def RLock(): ... +def Condition(lock: Optional[Any] = ...): ... +def Semaphore(value: int = ...): ... +def BoundedSemaphore(value: int = ...): ... +def Event(): ... +def JoinableQueue(maxsize: int = ...): ... +def RawValue(typecode_or_type, *args): ... +def RawArray(typecode_or_type, size_or_initializer): ... +def Value(typecode_or_type, *args, **kwds): ... +def Array(typecode_or_type, size_or_initializer, **kwds): ... + +def Pool(processes: Optional[int] = ..., + initializer: Optional[Callable[..., Any]] = ..., + initargs: Iterable[Any] = ..., + maxtasksperchild: Optional[int] = ...) -> pool.Pool: ... diff --git a/client/typeshed-fallback/stdlib/2/multiprocessing/dummy/__init__.pyi b/client/typeshed-fallback/stdlib/2/multiprocessing/dummy/__init__.pyi new file mode 100644 index 000000000..aee95b3fc --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/multiprocessing/dummy/__init__.pyi @@ -0,0 +1,51 @@ +from typing import Any, Optional, List, Type + +import threading +import sys +import weakref +import array +import itertools + +from multiprocessing import TimeoutError, cpu_count +from multiprocessing.dummy.connection import Pipe +from threading import Lock, RLock, Semaphore, BoundedSemaphore +from threading import Event +from Queue import Queue + + +class DummyProcess(threading.Thread): + _children = ... # type: weakref.WeakKeyDictionary + _parent = ... # type: threading.Thread + _pid = ... # type: None + _start_called = ... # type: bool + def __init__(self, group=..., target=..., name=..., args=..., kwargs=...) -> None: ... + @property + def exitcode(self) -> Optional[int]: ... + + +Process = DummyProcess + +# This should be threading._Condition but threading.pyi exports it as Condition +class Condition(threading.Condition): + notify_all = ... # type: Any + +class Namespace(object): + def __init__(self, **kwds) -> None: ... + +class Value(object): + _typecode = ... # type: Any + _value = ... # type: Any + value = ... # type: Any + def __init__(self, typecode, value, lock=...) -> None: ... + def _get(self) -> Any: ... + def _set(self, value) -> None: ... + +JoinableQueue = Queue + +def Array(typecode, sequence, lock=...) -> array.array: ... +def Manager() -> Any: ... +def Pool(processes=..., initializer=..., initargs=...) -> Any: ... +def active_children() -> List: ... +def current_process() -> threading.Thread: ... +def freeze_support() -> None: ... +def shutdown() -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/multiprocessing/dummy/connection.pyi b/client/typeshed-fallback/stdlib/2/multiprocessing/dummy/connection.pyi new file mode 100644 index 000000000..2db5bea3d --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/multiprocessing/dummy/connection.pyi @@ -0,0 +1,26 @@ +from Queue import Queue +from typing import Any, List, Optional, Tuple, Type + +families = ... # type: List[None] + +class Connection(object): + _in = ... # type: Any + _out = ... # type: Any + recv = ... # type: Any + recv_bytes = ... # type: Any + send = ... # type: Any + send_bytes = ... # type: Any + def __init__(self, _in, _out) -> None: ... + def close(self) -> None: ... + def poll(self, timeout=...) -> Any: ... + +class Listener(object): + _backlog_queue = ... # type: Optional[Queue] + address = ... # type: Any + def __init__(self, address=..., family=..., backlog=...) -> None: ... + def accept(self) -> Connection: ... + def close(self) -> None: ... + + +def Client(address) -> Connection: ... +def Pipe(duplex=...) -> Tuple[Connection, Connection]: ... diff --git a/client/typeshed-fallback/stdlib/2/multiprocessing/pool.pyi b/client/typeshed-fallback/stdlib/2/multiprocessing/pool.pyi new file mode 100644 index 000000000..4001a5a2b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/multiprocessing/pool.pyi @@ -0,0 +1,59 @@ +from typing import ( + Any, Callable, ContextManager, Iterable, Optional, Dict, List, + TypeVar, Iterator, +) + +_T = TypeVar('_T', bound=Pool) + +class AsyncResult(): + def get(self, timeout: Optional[float] = ...) -> Any: ... + def wait(self, timeout: Optional[float] = ...) -> None: ... + def ready(self) -> bool: ... + def successful(self) -> bool: ... + +class IMapIterator(Iterator[Any]): + def __iter__(self) -> Iterator[Any]: ... + def next(self, timeout: Optional[float] = ...) -> Any: ... + +class IMapUnorderedIterator(IMapIterator): ... + +class Pool(ContextManager[Pool]): + def __init__(self, processes: Optional[int] = ..., + initializer: Optional[Callable[..., None]] = ..., + initargs: Iterable[Any] = ..., + maxtasksperchild: Optional[int] = ...) -> None: ... + def apply(self, + func: Callable[..., Any], + args: Iterable[Any] = ..., + kwds: Dict[str, Any] = ...) -> Any: ... + def apply_async(self, + func: Callable[..., Any], + args: Iterable[Any] = ..., + kwds: Dict[str, Any] = ..., + callback: Optional[Callable[..., None]] = ...) -> AsyncResult: ... + def map(self, + func: Callable[..., Any], + iterable: Iterable[Any] = ..., + chunksize: Optional[int] = ...) -> List[Any]: ... + def map_async(self, func: Callable[..., Any], + iterable: Iterable[Any] = ..., + chunksize: Optional[int] = ..., + callback: Optional[Callable[..., None]] = ...) -> AsyncResult: ... + def imap(self, + func: Callable[..., Any], + iterable: Iterable[Any] = ..., + chunksize: Optional[int] = ...) -> IMapIterator: ... + def imap_unordered(self, + func: Callable[..., Any], + iterable: Iterable[Any] = ..., + chunksize: Optional[int] = ...) -> IMapIterator: ... + def close(self) -> None: ... + def terminate(self) -> None: ... + def join(self) -> None: ... + def __enter__(self: _T) -> _T: ... + +class ThreadPool(Pool, ContextManager[ThreadPool]): + + def __init__(self, processes: Optional[int] = ..., + initializer: Optional[Callable[..., Any]] = ..., + initargs: Iterable[Any] = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/multiprocessing/process.pyi b/client/typeshed-fallback/stdlib/2/multiprocessing/process.pyi new file mode 100644 index 000000000..e26b18c91 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/multiprocessing/process.pyi @@ -0,0 +1,36 @@ +from typing import Any, Optional + +def current_process(): ... +def active_children(): ... + +class Process: + def __init__(self, group: Optional[Any] = ..., target: Optional[Any] = ..., name: Optional[Any] = ..., args=..., + kwargs=...): ... + def run(self): ... + def start(self): ... + def terminate(self): ... + def join(self, timeout: Optional[Any] = ...): ... + def is_alive(self): ... + @property + def name(self): ... + @name.setter + def name(self, name): ... + @property + def daemon(self): ... + @daemon.setter + def daemon(self, daemonic): ... + @property + def authkey(self): ... + @authkey.setter + def authkey(self, authkey): ... + @property + def exitcode(self): ... + @property + def ident(self): ... + pid = ... # type: Any + +class AuthenticationString(bytes): + def __reduce__(self): ... + +class _MainProcess(Process): + def __init__(self): ... diff --git a/client/typeshed-fallback/stdlib/2/multiprocessing/util.pyi b/client/typeshed-fallback/stdlib/2/multiprocessing/util.pyi new file mode 100644 index 000000000..4414c66b1 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/multiprocessing/util.pyi @@ -0,0 +1,29 @@ +from typing import Any, Optional +import threading + +SUBDEBUG = ... # type: Any +SUBWARNING = ... # type: Any + +def sub_debug(msg, *args): ... +def debug(msg, *args): ... +def info(msg, *args): ... +def sub_warning(msg, *args): ... +def get_logger(): ... +def log_to_stderr(level: Optional[Any] = ...): ... +def get_temp_dir(): ... +def register_after_fork(obj, func): ... + +class Finalize: + def __init__(self, obj, callback, args=..., kwargs: Optional[Any] = ..., exitpriority: Optional[Any] = ...): ... + def __call__(self, wr: Optional[Any] = ...): ... + def cancel(self): ... + def still_active(self): ... + +def is_exiting(): ... + +class ForkAwareThreadLock: + def __init__(self): ... + +class ForkAwareLocal(threading.local): + def __init__(self): ... + def __reduce__(self): ... diff --git a/client/typeshed-fallback/stdlib/2/mutex.pyi b/client/typeshed-fallback/stdlib/2/mutex.pyi new file mode 100644 index 000000000..df1e71cc1 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/mutex.pyi @@ -0,0 +1,15 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/mutex.py + +from collections import deque +from typing import Any, Callable, TypeVar + +_ArgType = TypeVar('_ArgType') + +class mutex: + locked = ... # type: bool + queue = ... # type: deque + def __init__(self) -> None: ... + def test(self) -> bool: ... + def testandset(self) -> bool: ... + def lock(self, function: Callable[[_ArgType], Any], argument: _ArgType) -> None: ... + def unlock(self) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/nturl2path.pyi b/client/typeshed-fallback/stdlib/2/nturl2path.pyi new file mode 100644 index 000000000..b87b008e4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/nturl2path.pyi @@ -0,0 +1,4 @@ +from typing import AnyStr + +def url2pathname(url: AnyStr) -> AnyStr: ... +def pathname2url(p: AnyStr) -> AnyStr: ... diff --git a/client/typeshed-fallback/stdlib/2/os/__init__.pyi b/client/typeshed-fallback/stdlib/2/os/__init__.pyi new file mode 100644 index 000000000..4a8489347 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/os/__init__.pyi @@ -0,0 +1,366 @@ +# Stubs for os +# Ron Murawski + +from builtins import OSError as error +from io import TextIOWrapper as _TextIOWrapper +from posix import stat_result as stat_result # TODO: use this, see https://github.com/python/mypy/issues/3078 +import sys +from typing import ( + Mapping, MutableMapping, Dict, List, Any, Tuple, Iterator, overload, Union, AnyStr, + Optional, Generic, Set, Callable, Text, Sequence, IO, NamedTuple, NoReturn, TypeVar +) +from . import path as path + +_T = TypeVar('_T') + +# ----- os variables ----- + +if sys.version_info >= (3, 2): + supports_bytes_environ: bool + +if sys.version_info >= (3, 3): + supports_dir_fd: Set[Callable[..., Any]] + supports_fd: Set[Callable[..., Any]] + supports_effective_ids: Set[Callable[..., Any]] + supports_follow_symlinks: Set[Callable[..., Any]] + +SEEK_SET: int +SEEK_CUR: int +SEEK_END: int + +O_RDONLY: int +O_WRONLY: int +O_RDWR: int +O_APPEND: int +O_CREAT: int +O_EXCL: int +O_TRUNC: int +# We don't use sys.platform for O_* flags to denote platform-dependent APIs because some codes, +# including tests for mypy, use a more finer way than sys.platform before using these APIs +# See https://github.com/python/typeshed/pull/2286 for discussions +O_DSYNC: int # Unix only +O_RSYNC: int # Unix only +O_SYNC: int # Unix only +O_NDELAY: int # Unix only +O_NONBLOCK: int # Unix only +O_NOCTTY: int # Unix only +O_SHLOCK: int # Unix only +O_EXLOCK: int # Unix only +O_BINARY: int # Windows only +O_NOINHERIT: int # Windows only +O_SHORT_LIVED: int # Windows only +O_TEMPORARY: int # Windows only +O_RANDOM: int # Windows only +O_SEQUENTIAL: int # Windows only +O_TEXT: int # Windows only +O_ASYNC: int # Gnu extension if in C library +O_DIRECT: int # Gnu extension if in C library +O_DIRECTORY: int # Gnu extension if in C library +O_NOFOLLOW: int # Gnu extension if in C library +O_NOATIME: int # Gnu extension if in C library +O_LARGEFILE: int # Gnu extension if in C library + +curdir: str +pardir: str +sep: str +altsep: str +extsep: str +pathsep: str +defpath: str +linesep: str +devnull: str +name: str + +F_OK: int +R_OK: int +W_OK: int +X_OK: int + +class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): + def copy(self) -> Dict[AnyStr, AnyStr]: ... + def __delitem__(self, key: AnyStr) -> None: ... + def __getitem__(self, key: AnyStr) -> AnyStr: ... + def __setitem__(self, key: AnyStr, value: AnyStr) -> None: ... + def __iter__(self) -> Iterator[AnyStr]: ... + def __len__(self) -> int: ... + +environ: _Environ[str] +if sys.version_info >= (3, 2): + environb: _Environ[bytes] + +if sys.platform != 'win32': + # Unix only + confstr_names: Dict[str, int] + pathconf_names: Dict[str, int] + sysconf_names: Dict[str, int] + + EX_OK: int + EX_USAGE: int + EX_DATAERR: int + EX_NOINPUT: int + EX_NOUSER: int + EX_NOHOST: int + EX_UNAVAILABLE: int + EX_SOFTWARE: int + EX_OSERR: int + EX_OSFILE: int + EX_CANTCREAT: int + EX_IOERR: int + EX_TEMPFAIL: int + EX_PROTOCOL: int + EX_NOPERM: int + EX_CONFIG: int + EX_NOTFOUND: int + +P_NOWAIT: int +P_NOWAITO: int +P_WAIT: int +if sys.platform == 'win32': + P_DETACH: int + P_OVERLAY: int + +# wait()/waitpid() options +if sys.platform != 'win32': + WNOHANG: int # Unix only + WCONTINUED: int # some Unix systems + WUNTRACED: int # Unix only + +TMP_MAX: int # Undocumented, but used by tempfile + +# ----- os classes (structures) ----- +if sys.version_info >= (3, 6): + from builtins import _PathLike as PathLike # See comment in builtins + +_PathType = path._PathType + +_StatVFS = NamedTuple('_StatVFS', [('f_bsize', int), ('f_frsize', int), ('f_blocks', int), + ('f_bfree', int), ('f_bavail', int), ('f_files', int), + ('f_ffree', int), ('f_favail', int), ('f_flag', int), + ('f_namemax', int)]) + +def getlogin() -> str: ... +def getpid() -> int: ... +def getppid() -> int: ... +def strerror(code: int) -> str: ... +def umask(mask: int) -> int: ... + +if sys.platform != 'win32': + def ctermid() -> str: ... + def getegid() -> int: ... + def geteuid() -> int: ... + def getgid() -> int: ... + def getgroups() -> List[int]: ... # Unix only, behaves differently on Mac + def initgroups(username: str, gid: int) -> None: ... + def getpgid(pid: int) -> int: ... + def getpgrp() -> int: ... + def getresuid() -> Tuple[int, int, int]: ... + def getresgid() -> Tuple[int, int, int]: ... + def getuid() -> int: ... + def setegid(egid: int) -> None: ... + def seteuid(euid: int) -> None: ... + def setgid(gid: int) -> None: ... + def setgroups(groups: Sequence[int]) -> None: ... + def setpgrp() -> None: ... + def setpgid(pid: int, pgrp: int) -> None: ... + def setregid(rgid: int, egid: int) -> None: ... + def setresgid(rgid: int, egid: int, sgid: int) -> None: ... + def setresuid(ruid: int, euid: int, suid: int) -> None: ... + def setreuid(ruid: int, euid: int) -> None: ... + def getsid(pid: int) -> int: ... + def setsid() -> None: ... + def setuid(uid: int) -> None: ... + def uname() -> Tuple[str, str, str, str, str]: ... + +@overload +def getenv(key: Text) -> Optional[str]: ... +@overload +def getenv(key: Text, default: _T) -> Union[str, _T]: ... +def putenv(key: Union[bytes, Text], value: Union[bytes, Text]) -> None: ... +def unsetenv(key: Union[bytes, Text]) -> None: ... + +def fdopen(fd: int, *args, **kwargs) -> IO[Any]: ... +def close(fd: int) -> None: ... +def closerange(fd_low: int, fd_high: int) -> None: ... +def dup(fd: int) -> int: ... +def dup2(fd: int, fd2: int) -> None: ... +def fstat(fd: int) -> Any: ... +def fsync(fd: int) -> None: ... +def lseek(fd: int, pos: int, how: int) -> int: ... +def open(file: _PathType, flags: int, mode: int = ...) -> int: ... +def pipe() -> Tuple[int, int]: ... +def read(fd: int, n: int) -> bytes: ... +def write(fd: int, string: bytes) -> int: ... +def access(path: _PathType, mode: int) -> bool: ... +def chdir(path: _PathType) -> None: ... +def fchdir(fd: int) -> None: ... +def getcwd() -> str: ... +def getcwdu() -> unicode: ... +def chmod(path: _PathType, mode: int) -> None: ... +def link(src: _PathType, link_name: _PathType) -> None: ... +def listdir(path: AnyStr) -> List[AnyStr]: ... +def lstat(path: _PathType) -> Any: ... +def mknod(filename: _PathType, mode: int = ..., device: int = ...) -> None: ... +def major(device: int) -> int: ... +def minor(device: int) -> int: ... +def makedev(major: int, minor: int) -> int: ... +def mkdir(path: _PathType, mode: int = ...) -> None: ... +def makedirs(path: _PathType, mode: int = ...) -> None: ... +def readlink(path: AnyStr) -> AnyStr: ... +def remove(path: _PathType) -> None: ... +def removedirs(path: _PathType) -> None: ... +def rename(src: _PathType, dst: _PathType) -> None: ... +def renames(old: _PathType, new: _PathType) -> None: ... +def rmdir(path: _PathType) -> None: ... +def stat(path: _PathType) -> Any: ... +@overload +def stat_float_times() -> bool: ... +@overload +def stat_float_times(newvalue: bool) -> None: ... +def symlink(source: _PathType, link_name: _PathType) -> None: ... +def unlink(path: _PathType) -> None: ... +# TODO: add ns, dir_fd, follow_symlinks argument +if sys.version_info >= (3, 0): + def utime(path: _PathType, times: Optional[Tuple[float, float]] = ...) -> None: ... +else: + def utime(path: _PathType, times: Optional[Tuple[float, float]]) -> None: ... + +if sys.platform != 'win32': + # Unix only + def fchmod(fd: int, mode: int) -> None: ... + def fchown(fd: int, uid: int, gid: int) -> None: ... + if sys.platform != 'darwin': + def fdatasync(fd: int) -> None: ... # Unix only, not Mac + def fpathconf(fd: int, name: Union[str, int]) -> int: ... + def fstatvfs(fd: int) -> _StatVFS: ... + def ftruncate(fd: int, length: int) -> None: ... + def isatty(fd: int) -> bool: ... + def openpty() -> Tuple[int, int]: ... # some flavors of Unix + def tcgetpgrp(fd: int) -> int: ... + def tcsetpgrp(fd: int, pg: int) -> None: ... + def ttyname(fd: int) -> str: ... + def chflags(path: _PathType, flags: int) -> None: ... + def chroot(path: _PathType) -> None: ... + def chown(path: _PathType, uid: int, gid: int) -> None: ... + def lchflags(path: _PathType, flags: int) -> None: ... + def lchmod(path: _PathType, mode: int) -> None: ... + def lchown(path: _PathType, uid: int, gid: int) -> None: ... + def mkfifo(path: _PathType, mode: int = ...) -> None: ... + def pathconf(path: _PathType, name: Union[str, int]) -> int: ... + def statvfs(path: _PathType) -> _StatVFS: ... + +if sys.version_info >= (3, 6): + def walk(top: Union[AnyStr, PathLike[AnyStr]], topdown: bool = ..., + onerror: Optional[Callable[[OSError], Any]] = ..., + followlinks: bool = ...) -> Iterator[Tuple[AnyStr, List[AnyStr], + List[AnyStr]]]: ... +else: + def walk(top: AnyStr, topdown: bool = ..., onerror: Optional[Callable[[OSError], Any]] = ..., + followlinks: bool = ...) -> Iterator[Tuple[AnyStr, List[AnyStr], + List[AnyStr]]]: ... + +def abort() -> NoReturn: ... +# These are defined as execl(file, *args) but the first *arg is mandatory. +def execl(file: _PathType, __arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> NoReturn: ... +def execlp(file: _PathType, __arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> NoReturn: ... + +# These are: execle(file, *args, env) but env is pulled from the last element of the args. +def execle(file: _PathType, __arg0: Union[bytes, Text], *args: Any) -> NoReturn: ... +def execlpe(file: _PathType, __arg0: Union[bytes, Text], *args: Any) -> NoReturn: ... + +# The docs say `args: tuple or list of strings` +# The implementation enforces tuple or list so we can't use Sequence. +_ExecVArgs = Union[Tuple[Union[bytes, Text], ...], List[bytes], List[Text], List[Union[bytes, Text]]] +def execv(path: _PathType, args: _ExecVArgs) -> NoReturn: ... +def execve(path: _PathType, args: _ExecVArgs, env: Mapping[str, str]) -> NoReturn: ... +def execvp(file: _PathType, args: _ExecVArgs) -> NoReturn: ... +def execvpe(file: _PathType, args: _ExecVArgs, env: Mapping[str, str]) -> NoReturn: ... + +def _exit(n: int) -> NoReturn: ... +def kill(pid: int, sig: int) -> None: ... + +if sys.platform != 'win32': + # Unix only + def fork() -> int: ... + def forkpty() -> Tuple[int, int]: ... # some flavors of Unix + def killpg(pgid: int, sig: int) -> None: ... + def nice(increment: int) -> int: ... + def plock(op: int) -> None: ... # ???op is int? + +if sys.version_info >= (3, 0): + class popen(_TextIOWrapper): + # TODO 'b' modes or bytes command not accepted? + def __init__(self, command: str, mode: str = ..., + bufsize: int = ...) -> None: ... + def close(self) -> Any: ... # may return int +else: + def popen(command: str, *args, **kwargs) -> IO[Any]: ... + def popen2(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any]]: ... + def popen3(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any], IO[Any]]: ... + def popen4(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any]]: ... + +def spawnl(mode: int, path: _PathType, arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> int: ... +def spawnle(mode: int, path: _PathType, arg0: Union[bytes, Text], + *args: Any) -> int: ... # Imprecise sig +def spawnv(mode: int, path: _PathType, args: List[Union[bytes, Text]]) -> int: ... +def spawnve(mode: int, path: _PathType, args: List[Union[bytes, Text]], + env: Mapping[str, str]) -> int: ... +def system(command: _PathType) -> int: ... +def times() -> Tuple[float, float, float, float, float]: ... +def waitpid(pid: int, options: int) -> Tuple[int, int]: ... +def urandom(n: int) -> bytes: ... + +if sys.platform == 'win32': + def startfile(path: _PathType, operation: Optional[str] = ...) -> None: ... +else: + # Unix only + def spawnlp(mode: int, file: _PathType, arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> int: ... + def spawnlpe(mode: int, file: _PathType, arg0: Union[bytes, Text], *args: Any) -> int: ... # Imprecise signature + def spawnvp(mode: int, file: _PathType, args: List[Union[bytes, Text]]) -> int: ... + def spawnvpe(mode: int, file: _PathType, args: List[Union[bytes, Text]], env: Mapping[str, str]) -> int: ... + def wait() -> Tuple[int, int]: ... + def wait3(options: int) -> Tuple[int, int, Any]: ... + def wait4(pid: int, options: int) -> Tuple[int, int, Any]: ... + def WCOREDUMP(status: int) -> bool: ... + def WIFCONTINUED(status: int) -> bool: ... + def WIFSTOPPED(status: int) -> bool: ... + def WIFSIGNALED(status: int) -> bool: ... + def WIFEXITED(status: int) -> bool: ... + def WEXITSTATUS(status: int) -> int: ... + def WSTOPSIG(status: int) -> int: ... + def WTERMSIG(status: int) -> int: ... + def confstr(name: Union[str, int]) -> Optional[str]: ... + def getloadavg() -> Tuple[float, float, float]: ... + def sysconf(name: Union[str, int]) -> int: ... + +if sys.version_info >= (3, 0): + def sched_getaffinity(id: int) -> Set[int]: ... +if sys.version_info >= (3, 3): + class waitresult: + si_pid: int + def waitid(idtype: int, id: int, options: int) -> waitresult: ... + +if sys.version_info < (3, 0): + def tmpfile() -> IO[Any]: ... + def tmpnam() -> str: ... + def tempnam(dir: str = ..., prefix: str = ...) -> str: ... + +P_ALL: int +WEXITED: int +WNOWAIT: int + +if sys.version_info >= (3, 3): + if sys.platform != 'win32': + # Unix only + def sync() -> None: ... + + def truncate(path: Union[_PathType, int], length: int) -> None: ... # Unix only up to version 3.4 + + def fwalk(top: AnyStr = ..., topdown: bool = ..., + onerror: Callable = ..., *, follow_symlinks: bool = ..., + dir_fd: int = ...) -> Iterator[Tuple[AnyStr, List[AnyStr], List[AnyStr], int]]: ... + + terminal_size = NamedTuple('terminal_size', [('columns', int), ('lines', int)]) + def get_terminal_size(fd: int = ...) -> terminal_size: ... + +if sys.version_info >= (3, 4): + def cpu_count() -> Optional[int]: ... diff --git a/client/typeshed-fallback/stdlib/2/os/path.pyi b/client/typeshed-fallback/stdlib/2/os/path.pyi new file mode 100644 index 000000000..09663afa4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/os/path.pyi @@ -0,0 +1,177 @@ +# NB: path.pyi and stdlib/2 and stdlib/3 must remain consistent! +# Stubs for os.path +# Ron Murawski + +import os +import sys +from typing import ( + overload, List, Any, AnyStr, Sequence, Tuple, BinaryIO, TextIO, + TypeVar, Union, Text, Callable, Optional +) + +_T = TypeVar('_T') + +if sys.version_info >= (3, 6): + from builtins import _PathLike + _PathType = Union[bytes, Text, _PathLike] + _StrPath = Union[Text, _PathLike[Text]] + _BytesPath = Union[bytes, _PathLike[bytes]] +else: + _PathType = Union[bytes, Text] + _StrPath = Text + _BytesPath = bytes + +# ----- os.path variables ----- +supports_unicode_filenames: bool +# aliases (also in os) +curdir: str +pardir: str +sep: str +altsep: str +extsep: str +pathsep: str +defpath: str +devnull: str + +# ----- os.path function stubs ----- +if sys.version_info >= (3, 6): + # Overloads are necessary to work around python/mypy#3644. + @overload + def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def abspath(path: AnyStr) -> AnyStr: ... + @overload + def basename(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def basename(path: AnyStr) -> AnyStr: ... + @overload + def dirname(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def dirname(path: AnyStr) -> AnyStr: ... + @overload + def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expanduser(path: AnyStr) -> AnyStr: ... + @overload + def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expandvars(path: AnyStr) -> AnyStr: ... + @overload + def normcase(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normcase(path: AnyStr) -> AnyStr: ... + @overload + def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + @overload + def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(path: AnyStr) -> AnyStr: ... + else: + @overload + def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(filename: AnyStr) -> AnyStr: ... + +else: + def abspath(path: AnyStr) -> AnyStr: ... + def basename(path: AnyStr) -> AnyStr: ... + def dirname(path: AnyStr) -> AnyStr: ... + def expanduser(path: AnyStr) -> AnyStr: ... + def expandvars(path: AnyStr) -> AnyStr: ... + def normcase(path: AnyStr) -> AnyStr: ... + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + def realpath(path: AnyStr) -> AnyStr: ... + else: + def realpath(filename: AnyStr) -> AnyStr: ... + +if sys.version_info >= (3, 6): + # In reality it returns str for sequences of _StrPath and bytes for sequences + # of _BytesPath, but mypy does not accept such a signature. + def commonpath(paths: Sequence[_PathType]) -> Any: ... +elif sys.version_info >= (3, 5): + def commonpath(paths: Sequence[AnyStr]) -> AnyStr: ... + +# NOTE: Empty lists results in '' (str) regardless of contained type. +# Also, in Python 2 mixed sequences of Text and bytes results in either Text or bytes +# So, fall back to Any +def commonprefix(list: Sequence[_PathType]) -> Any: ... + +if sys.version_info >= (3, 3): + def exists(path: Union[_PathType, int]) -> bool: ... +else: + def exists(path: _PathType) -> bool: ... +def lexists(path: _PathType) -> bool: ... + +# These return float if os.stat_float_times() == True, +# but int is a subclass of float. +def getatime(path: _PathType) -> float: ... +def getmtime(path: _PathType) -> float: ... +def getctime(path: _PathType) -> float: ... + +def getsize(path: _PathType) -> int: ... +def isabs(path: _PathType) -> bool: ... +def isfile(path: _PathType) -> bool: ... +def isdir(path: _PathType) -> bool: ... +def islink(path: _PathType) -> bool: ... +def ismount(path: _PathType) -> bool: ... + +if sys.version_info < (3, 0): + # Make sure signatures are disjunct, and allow combinations of bytes and unicode. + # (Since Python 2 allows that, too) + # Note that e.g. os.path.join("a", "b", "c", "d", u"e") will still result in + # a type error. + @overload + def join(__p1: bytes, *p: bytes) -> bytes: ... + @overload + def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: bytes, __p2: bytes, __p3: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: bytes, __p2: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: Text, *p: _PathType) -> Text: ... +elif sys.version_info >= (3, 6): + # Mypy complains that the signatures overlap (same for relpath below), but things seem to behave correctly anyway. + @overload + def join(path: _StrPath, *paths: _StrPath) -> Text: ... + @overload + def join(path: _BytesPath, *paths: _BytesPath) -> bytes: ... +else: + def join(path: AnyStr, *paths: AnyStr) -> AnyStr: ... + +@overload +def relpath(path: _BytesPath, start: Optional[_BytesPath] = ...) -> bytes: ... +@overload +def relpath(path: _StrPath, start: Optional[_StrPath] = ...) -> Text: ... + +def samefile(path1: _PathType, path2: _PathType) -> bool: ... +def sameopenfile(fp1: int, fp2: int) -> bool: ... +def samestat(stat1: os.stat_result, stat2: os.stat_result) -> bool: ... + +if sys.version_info >= (3, 6): + @overload + def split(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def split(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +else: + def split(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitdrive(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitext(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + +if sys.platform == 'win32': + def splitunc(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + +if sys.version_info < (3,): + def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/os2emxpath.pyi b/client/typeshed-fallback/stdlib/2/os2emxpath.pyi new file mode 100644 index 000000000..09663afa4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/os2emxpath.pyi @@ -0,0 +1,177 @@ +# NB: path.pyi and stdlib/2 and stdlib/3 must remain consistent! +# Stubs for os.path +# Ron Murawski + +import os +import sys +from typing import ( + overload, List, Any, AnyStr, Sequence, Tuple, BinaryIO, TextIO, + TypeVar, Union, Text, Callable, Optional +) + +_T = TypeVar('_T') + +if sys.version_info >= (3, 6): + from builtins import _PathLike + _PathType = Union[bytes, Text, _PathLike] + _StrPath = Union[Text, _PathLike[Text]] + _BytesPath = Union[bytes, _PathLike[bytes]] +else: + _PathType = Union[bytes, Text] + _StrPath = Text + _BytesPath = bytes + +# ----- os.path variables ----- +supports_unicode_filenames: bool +# aliases (also in os) +curdir: str +pardir: str +sep: str +altsep: str +extsep: str +pathsep: str +defpath: str +devnull: str + +# ----- os.path function stubs ----- +if sys.version_info >= (3, 6): + # Overloads are necessary to work around python/mypy#3644. + @overload + def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def abspath(path: AnyStr) -> AnyStr: ... + @overload + def basename(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def basename(path: AnyStr) -> AnyStr: ... + @overload + def dirname(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def dirname(path: AnyStr) -> AnyStr: ... + @overload + def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expanduser(path: AnyStr) -> AnyStr: ... + @overload + def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expandvars(path: AnyStr) -> AnyStr: ... + @overload + def normcase(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normcase(path: AnyStr) -> AnyStr: ... + @overload + def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + @overload + def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(path: AnyStr) -> AnyStr: ... + else: + @overload + def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(filename: AnyStr) -> AnyStr: ... + +else: + def abspath(path: AnyStr) -> AnyStr: ... + def basename(path: AnyStr) -> AnyStr: ... + def dirname(path: AnyStr) -> AnyStr: ... + def expanduser(path: AnyStr) -> AnyStr: ... + def expandvars(path: AnyStr) -> AnyStr: ... + def normcase(path: AnyStr) -> AnyStr: ... + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + def realpath(path: AnyStr) -> AnyStr: ... + else: + def realpath(filename: AnyStr) -> AnyStr: ... + +if sys.version_info >= (3, 6): + # In reality it returns str for sequences of _StrPath and bytes for sequences + # of _BytesPath, but mypy does not accept such a signature. + def commonpath(paths: Sequence[_PathType]) -> Any: ... +elif sys.version_info >= (3, 5): + def commonpath(paths: Sequence[AnyStr]) -> AnyStr: ... + +# NOTE: Empty lists results in '' (str) regardless of contained type. +# Also, in Python 2 mixed sequences of Text and bytes results in either Text or bytes +# So, fall back to Any +def commonprefix(list: Sequence[_PathType]) -> Any: ... + +if sys.version_info >= (3, 3): + def exists(path: Union[_PathType, int]) -> bool: ... +else: + def exists(path: _PathType) -> bool: ... +def lexists(path: _PathType) -> bool: ... + +# These return float if os.stat_float_times() == True, +# but int is a subclass of float. +def getatime(path: _PathType) -> float: ... +def getmtime(path: _PathType) -> float: ... +def getctime(path: _PathType) -> float: ... + +def getsize(path: _PathType) -> int: ... +def isabs(path: _PathType) -> bool: ... +def isfile(path: _PathType) -> bool: ... +def isdir(path: _PathType) -> bool: ... +def islink(path: _PathType) -> bool: ... +def ismount(path: _PathType) -> bool: ... + +if sys.version_info < (3, 0): + # Make sure signatures are disjunct, and allow combinations of bytes and unicode. + # (Since Python 2 allows that, too) + # Note that e.g. os.path.join("a", "b", "c", "d", u"e") will still result in + # a type error. + @overload + def join(__p1: bytes, *p: bytes) -> bytes: ... + @overload + def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: bytes, __p2: bytes, __p3: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: bytes, __p2: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: Text, *p: _PathType) -> Text: ... +elif sys.version_info >= (3, 6): + # Mypy complains that the signatures overlap (same for relpath below), but things seem to behave correctly anyway. + @overload + def join(path: _StrPath, *paths: _StrPath) -> Text: ... + @overload + def join(path: _BytesPath, *paths: _BytesPath) -> bytes: ... +else: + def join(path: AnyStr, *paths: AnyStr) -> AnyStr: ... + +@overload +def relpath(path: _BytesPath, start: Optional[_BytesPath] = ...) -> bytes: ... +@overload +def relpath(path: _StrPath, start: Optional[_StrPath] = ...) -> Text: ... + +def samefile(path1: _PathType, path2: _PathType) -> bool: ... +def sameopenfile(fp1: int, fp2: int) -> bool: ... +def samestat(stat1: os.stat_result, stat2: os.stat_result) -> bool: ... + +if sys.version_info >= (3, 6): + @overload + def split(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def split(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +else: + def split(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitdrive(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitext(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + +if sys.platform == 'win32': + def splitunc(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + +if sys.version_info < (3,): + def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/pipes.pyi b/client/typeshed-fallback/stdlib/2/pipes.pyi new file mode 100644 index 000000000..d5f5291e3 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/pipes.pyi @@ -0,0 +1,13 @@ +from typing import Any, IO + +class Template: + def __init__(self) -> None: ... + def reset(self) -> None: ... + def clone(self) -> Template: ... + def debug(self, flag: bool) -> None: ... + def append(self, cmd: str, kind: str) -> None: ... + def prepend(self, cmd: str, kind: str) -> None: ... + def open(self, file: str, mode: str) -> IO[Any]: ... + def copy(self, infile: str, outfile: str) -> None: ... + +def quote(s: str) -> str: ... diff --git a/client/typeshed-fallback/stdlib/2/platform.pyi b/client/typeshed-fallback/stdlib/2/platform.pyi new file mode 100644 index 000000000..0e7a03130 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/platform.pyi @@ -0,0 +1,45 @@ +# Stubs for platform (Python 2) +# +# Based on stub generated by stubgen. + +from typing import Any, Optional, Tuple + +__copyright__ = ... # type: Any +DEV_NULL = ... # type: Any + +def libc_ver(executable=..., lib=..., version=..., chunksize: int = ...): ... +def linux_distribution(distname=..., version=..., id=..., supported_dists=..., full_distribution_name: int = ...): ... +def dist(distname=..., version=..., id=..., supported_dists=...): ... + +class _popen: + tmpfile = ... # type: Any + pipe = ... # type: Any + bufsize = ... # type: Any + mode = ... # type: Any + def __init__(self, cmd, mode=..., bufsize: Optional[Any] = ...): ... + def read(self): ... + def readlines(self): ... + def close(self, remove=..., error=...): ... + __del__ = ... # type: Any + +def popen(cmd, mode=..., bufsize: Optional[Any] = ...): ... +def win32_ver(release=..., version=..., csd=..., ptype=...): ... +def mac_ver(release=..., versioninfo=..., machine=...): ... +def java_ver(release=..., vendor=..., vminfo=..., osinfo=...): ... +def system_alias(system, release, version): ... +def architecture(executable=..., bits=..., linkage=...) -> Tuple[str, str]: ... +def uname() -> Tuple[str, str, str, str, str, str]: ... +def system() -> str: ... +def node() -> str: ... +def release() -> str: ... +def version() -> str: ... +def machine() -> str: ... +def processor() -> str: ... +def python_implementation() -> str: ... +def python_version() -> str: ... +def python_version_tuple() -> Tuple[str, str, str]: ... +def python_branch() -> str: ... +def python_revision() -> str: ... +def python_build() -> Tuple[str, str]: ... +def python_compiler() -> str: ... +def platform(aliased: int = ..., terse: int = ...) -> str: ... diff --git a/client/typeshed-fallback/stdlib/2/popen2.pyi b/client/typeshed-fallback/stdlib/2/popen2.pyi new file mode 100644 index 000000000..a71e78e57 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/popen2.pyi @@ -0,0 +1,28 @@ +from typing import Any, Iterable, List, Optional, Union, TextIO, Tuple, TypeVar + +_T = TypeVar('_T') + + +class Popen3: + sts = ... # type: int + cmd = ... # type: Iterable + pid = ... # type: int + tochild = ... # type: TextIO + fromchild = ... # type: TextIO + childerr = ... # type: Optional[TextIO] + def __init__(self, cmd: Iterable = ..., capturestderr: bool = ..., bufsize: int = ...) -> None: ... + def __del__(self) -> None: ... + def poll(self, _deadstate: _T = ...) -> Union[int, _T]: ... + def wait(self) -> int: ... + +class Popen4(Popen3): + childerr = ... # type: None + cmd = ... # type: Iterable + pid = ... # type: int + tochild = ... # type: TextIO + fromchild = ... # type: TextIO + def __init__(self, cmd: Iterable = ..., bufsize: int = ...) -> None: ... + +def popen2(cmd: Iterable = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO]: ... +def popen3(cmd: Iterable = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO, TextIO]: ... +def popen4(cmd: Iterable = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO]: ... diff --git a/client/typeshed-fallback/stdlib/2/posix.pyi b/client/typeshed-fallback/stdlib/2/posix.pyi new file mode 100644 index 000000000..ba01df0b7 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/posix.pyi @@ -0,0 +1,205 @@ +from typing import Dict, List, Mapping, Tuple, Union, Sequence, IO, Optional, TypeVar + +error = OSError + +confstr_names = ... # type: Dict[str, int] +environ = ... # type: Dict[str, str] +pathconf_names = ... # type: Dict[str, int] +sysconf_names = ... # type: Dict[str, int] + +EX_CANTCREAT = ... # type: int +EX_CONFIG = ... # type: int +EX_DATAERR = ... # type: int +EX_IOERR = ... # type: int +EX_NOHOST = ... # type: int +EX_NOINPUT = ... # type: int +EX_NOPERM = ... # type: int +EX_NOUSER = ... # type: int +EX_OK = ... # type: int +EX_OSERR = ... # type: int +EX_OSFILE = ... # type: int +EX_PROTOCOL = ... # type: int +EX_SOFTWARE = ... # type: int +EX_TEMPFAIL = ... # type: int +EX_UNAVAILABLE = ... # type: int +EX_USAGE = ... # type: int +F_OK = ... # type: int +NGROUPS_MAX = ... # type: int +O_APPEND = ... # type: int +O_ASYNC = ... # type: int +O_CREAT = ... # type: int +O_DIRECT = ... # type: int +O_DIRECTORY = ... # type: int +O_DSYNC = ... # type: int +O_EXCL = ... # type: int +O_LARGEFILE = ... # type: int +O_NDELAY = ... # type: int +O_NOATIME = ... # type: int +O_NOCTTY = ... # type: int +O_NOFOLLOW = ... # type: int +O_NONBLOCK = ... # type: int +O_RDONLY = ... # type: int +O_RDWR = ... # type: int +O_RSYNC = ... # type: int +O_SYNC = ... # type: int +O_TRUNC = ... # type: int +O_WRONLY = ... # type: int +R_OK = ... # type: int +TMP_MAX = ... # type: int +WCONTINUED = ... # type: int +WNOHANG = ... # type: int +WUNTRACED = ... # type: int +W_OK = ... # type: int +X_OK = ... # type: int + +def WCOREDUMP(status: int) -> bool: ... +def WEXITSTATUS(status: int) -> bool: ... +def WIFCONTINUED(status: int) -> bool: ... +def WIFEXITED(status: int) -> bool: ... +def WIFSIGNALED(status: int) -> bool: ... +def WIFSTOPPED(status: int) -> bool: ... +def WSTOPSIG(status: int) -> bool: ... +def WTERMSIG(status: int) -> bool: ... + +class stat_result(object): + n_fields = ... # type: int + n_sequence_fields = ... # type: int + n_unnamed_fields = ... # type: int + st_mode = ... # type: int + st_ino = ... # type: int + st_dev = ... # type: int + st_nlink = ... # type: int + st_uid = ... # type: int + st_gid = ... # type: int + st_size = ... # type: int + st_atime = ... # type: int + st_mtime = ... # type: int + st_ctime = ... # type: int + +class statvfs_result(object): + n_fields = ... # type: int + n_sequence_fields = ... # type: int + n_unnamed_fields = ... # type: int + f_bsize = ... # type: int + f_frsize = ... # type: int + f_blocks = ... # type: int + f_bfree = ... # type: int + f_bavail = ... # type: int + f_files = ... # type: int + f_ffree = ... # type: int + f_favail = ... # type: int + f_flag = ... # type: int + f_namemax = ... # type: int + +def _exit(status: int) -> None: ... +def abort() -> None: ... +def access(path: unicode, mode: int) -> bool: ... +def chdir(path: unicode) -> None: ... +def chmod(path: unicode, mode: int) -> None: ... +def chown(path: unicode, uid: int, gid: int) -> None: ... +def chroot(path: unicode) -> None: ... +def close(fd: int) -> None: ... +def closerange(fd_low: int, fd_high: int) -> None: ... +def confstr(name: Union[str, int]) -> str: ... +def ctermid() -> str: ... +def dup(fd: int) -> int: ... +def dup2(fd: int, fd2: int) -> None: ... +def execv(path: str, args: Sequence[str], env: Mapping[str, str]) -> None: ... +def execve(path: str, args: Sequence[str], env: Mapping[str, str]) -> None: ... +def fchdir(fd: int) -> None: ... +def fchmod(fd: int, mode: int) -> None: ... +def fchown(fd: int, uid: int, gid: int) -> None: ... +def fdatasync(fd: int) -> None: ... +def fdopen(fd: int, mode: str = ..., bufsize: int = ...) -> IO[str]: ... +def fork() -> int: + raise OSError() +def forkpty() -> Tuple[int, int]: + raise OSError() +def fpathconf(fd: int, name: str) -> None: ... +def fstat(fd: int) -> stat_result: ... +def fstatvfs(fd: int) -> statvfs_result: ... +def fsync(fd: int) -> None: ... +def ftruncate(fd: int, length: int) -> None: ... +def getcwd() -> str: ... +def getcwdu() -> unicode: ... +def getegid() -> int: ... +def geteuid() -> int: ... +def getgid() -> int: ... +def getgroups() -> List[int]: ... +def getloadavg() -> Tuple[float, float, float]: + raise OSError() +def getlogin() -> str: ... +def getpgid(pid: int) -> int: ... +def getpgrp() -> int: ... +def getpid() -> int: ... +def getppid() -> int: ... +def getresgid() -> Tuple[int, int, int]: ... +def getresuid() -> Tuple[int, int, int]: ... +def getsid(pid: int) -> int: ... +def getuid() -> int: ... +def initgroups(username: str, gid: int) -> None: ... +def isatty(fd: int) -> bool: ... +def kill(pid: int, sig: int) -> None: ... +def killpg(pgid: int, sig: int) -> None: ... +def lchown(path: unicode, uid: int, gid: int) -> None: ... +def link(source: unicode, link_name: str) -> None: ... +_T = TypeVar("_T") +def listdir(path: _T) -> List[_T]: ... +def lseek(fd: int, pos: int, how: int) -> None: ... +def lstat(path: unicode) -> stat_result: ... +def major(device: int) -> int: ... +def makedev(major: int, minor: int) -> int: ... +def minor(device: int) -> int: ... +def mkdir(path: unicode, mode: int = ...) -> None: ... +def mkfifo(path: unicode, mode: int = ...) -> None: ... +def mknod(filename: unicode, mode: int = ..., device: int = ...) -> None: ... +def nice(increment: int) -> int: ... +def open(file: unicode, flags: int, mode: int = ...) -> int: ... +def openpty() -> Tuple[int, int]: ... +def pathconf(path: unicode, name: str) -> str: ... +def pipe() -> Tuple[int, int]: ... +def popen(command: str, mode: str = ..., bufsize: int = ...) -> IO[str]: ... +def putenv(varname: str, value: str) -> None: ... +def read(fd: int, n: int) -> str: ... +def readlink(path: _T) -> _T: ... +def remove(path: unicode) -> None: ... +def rename(src: unicode, dst: unicode) -> None: ... +def rmdir(path: unicode) -> None: ... +def setegid(egid: int) -> None: ... +def seteuid(euid: int) -> None: ... +def setgid(gid: int) -> None: ... +def setgroups(groups: Sequence[int]) -> None: ... +def setpgid(pid: int, pgrp: int) -> None: ... +def setpgrp() -> None: ... +def setregid(rgid: int, egid: int) -> None: ... +def setresgid(rgid: int, egid: int, sgid: int) -> None: ... +def setresuid(ruid: int, euid: int, suid: int) -> None: ... +def setreuid(ruid: int, euid: int) -> None: ... +def setsid() -> None: ... +def setuid(pid: int) -> None: ... +def stat(path: unicode) -> stat_result: ... +def statvfs(path: unicode) -> statvfs_result: ... +def stat_float_times(fd: int) -> None: ... +def strerror(code: int) -> str: ... +def symlink(source: unicode, link_name: unicode) -> None: ... +def sysconf(name: Union[str, int]) -> int: ... +def system(command: unicode) -> int: ... +def tcgetpgrp(fd: int) -> int: ... +def tcsetpgrp(fd: int, pg: int) -> None: ... +def times() -> Tuple[float, float, float, float, float]: ... +def tmpfile() -> IO[str]: ... +def ttyname(fd: int) -> str: ... +def umask(mask: int) -> int: ... +def uname() -> Tuple[str, str, str, str, str]: ... +def unlink(path: unicode) -> None: ... +def unsetenv(varname: str) -> None: ... +def urandom(n: int) -> str: ... +def utime(path: unicode, times: Optional[Tuple[int, int]]) -> None: + raise OSError +def wait() -> int: ... +_r = Tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, int] +def wait3(options: int) -> Tuple[int, int, _r]: ... +def wait4(pid: int, options: int) -> Tuple[int, int, _r]: ... +def waitpid(pid: int, options: int) -> int: + raise OSError() +def write(fd: int, str: str) -> int: ... diff --git a/client/typeshed-fallback/stdlib/2/pydoc.pyi b/client/typeshed-fallback/stdlib/2/pydoc.pyi new file mode 100644 index 000000000..41505e6b2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/pydoc.pyi @@ -0,0 +1,176 @@ +from typing import Any, AnyStr, Callable, Container, Dict, IO, List, Mapping, MutableMapping, NoReturn, Optional, Tuple, Type, Union +from repr import Repr + +from types import FunctionType, MethodType, ModuleType, TracebackType +# the return type of sys.exc_info(), used by ErrorDuringImport.__init__ +_Exc_Info = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] + +__author__ = ... # type: str +__date__ = ... # type: str +__version__ = ... # type: str +__credits__ = ... # type: str + +def pathdirs() -> List[str]: ... +def getdoc(object: object) -> Union[str, unicode]: ... +def splitdoc(doc: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def classname(object: object, modname: str) -> str: ... +def isdata(object: object) -> bool: ... +def replace(text: AnyStr, *pairs: AnyStr) -> AnyStr: ... +def cram(text: str, maxlen: int) -> str: ... +def stripid(text: str) -> str: ... +def allmethods(cl: type) -> MutableMapping[str, MethodType]: ... +def visiblename(name: str, all: Optional[Container[str]] = ..., obj: Optional[object] = ...) -> bool: ... +def classify_class_attrs(object: object) -> List[Tuple[str, str, type, str]]: ... + +def ispackage(path: str) -> bool: ... +def source_synopsis(file: IO[AnyStr]) -> Optional[AnyStr]: ... +def synopsis(filename: str, cache: MutableMapping[str, Tuple[int, str]] = ...) -> Optional[str]: ... + +class ErrorDuringImport(Exception): + filename = ... # type: str + exc = ... # type: Optional[Type[BaseException]] + value = ... # type: Optional[BaseException] + tb = ... # type: Optional[TracebackType] + def __init__(self, filename: str, exc_info: _Exc_Info) -> None: ... + +def importfile(path: str) -> ModuleType: ... +def safeimport(path: str, forceload: bool = ..., cache: MutableMapping[str, ModuleType] = ...) -> ModuleType: ... + +class Doc: + def document(self, object: object, name: Optional[str] = ..., *args: Any) -> str: ... + def fail(self, object: object, name: Optional[str] = ..., *args: Any) -> NoReturn: ... + def docmodule(self, object: object, name: Optional[str] = ..., *args: Any) -> str: ... + def docclass(self, object: object, name: Optional[str] = ..., *args: Any) -> str: ... + def docroutine(self, object: object, name: Optional[str] = ..., *args: Any) -> str: ... + def docother(self, object: object, name: Optional[str] = ..., *args: Any) -> str: ... + def docproperty(self, object: object, name: Optional[str] = ..., *args: Any) -> str: ... + def docdata(self, object: object, name: Optional[str] = ..., *args: Any) -> str: ... + def getdocloc(self, object: object) -> Optional[str]: ... + +class HTMLRepr(Repr): + maxlist = ... # type: int + maxtuple = ... # type: int + maxdict = ... # type: int + maxstring = ... # type: int + maxother = ... # type: int + def __init__(self) -> None: ... + def escape(self, text: str) -> str: ... + def repr(self, object: object) -> str: ... + def repr1(self, x: object, level: complex) -> str: ... + def repr_string(self, x: Union[str, unicode], level: complex) -> str: ... + def repr_str(self, x: Union[str, unicode], level: complex) -> str: ... + def repr_instance(self, x: object, level: complex) -> str: ... + def repr_unicode(self, x: AnyStr, level: complex) -> str: ... + +class HTMLDoc(Doc): + def repr(self, object: object) -> str: ... + def escape(self, test: str) -> str: ... + def page(self, title: str, contents: str) -> str: ... + def heading(self, title: str, fgcol: str, bgcol: str, extras: str = ...) -> str: ... + def section(self, title: str, fgcol: str, bgcol: str, contents: str, width: int = ..., prelude: str = ..., marginalia: Optional[str] = ..., gap: str = ...) -> str: ... + def bigsection(self, title: str, *args) -> str: ... + def preformat(self, text: str) -> str: ... + def multicolumn(self, list: List[Any], format: Callable[[Any], str], cols: int = ...) -> str: ... + def grey(self, text: str) -> str: ... + def namelink(self, name: str, *dicts: MutableMapping[str, str]) -> str: ... + def classlink(self, object: object, modname: str) -> str: ... + def modulelink(self, object: object) -> str: ... + def modpkglink(self, data: Tuple[str, str, bool, bool]) -> str: ... + def markup(self, text: str, escape: Optional[Callable[[str], str]] = ..., funcs: Mapping[str, str] = ..., classes: Mapping[str, str] = ..., methods: Mapping[str, str] = ...) -> str: ... + def formattree(self, tree: List[Union[Tuple[type, Tuple[type, ...]], list]], modname: str, parent: Optional[type] = ...) -> str: ... + def docmodule(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., *ignored) -> str: ... + def docclass(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., funcs: Mapping[str, str] = ..., classes: Mapping[str, str] = ..., *ignored) -> str: ... + def formatvalue(self, object: object) -> str: ... + def docroutine(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., funcs: Mapping[str, str] = ..., classes: Mapping[str, str] = ..., methods: Mapping[str, str] = ..., cl: Optional[type] = ..., *ignored) -> str: ... + def docproperty(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., cl: Optional[Any] = ..., *ignored) -> str: ... + def docother(self, object: object, name: Optional[str] = ..., mod: Optional[Any] = ..., *ignored) -> str: ... + def docdata(self, object: object, name: Optional[str] = ..., mod: Optional[Any] = ..., cl: Optional[Any] = ..., *ignored) -> str: ... + def index(self, dir: str, shadowed: Optional[MutableMapping[str, bool]] = ...) -> str: ... + +class TextRepr(Repr): + maxlist = ... # type: int + maxtuple = ... # type: int + maxdict = ... # type: int + maxstring = ... # type: int + maxother = ... # type: int + def __init__(self) -> None: ... + def repr1(self, x: object, level: complex) -> str: ... + def repr_string(self, x: str, level: complex) -> str: ... + def repr_str(self, x: str, level: complex) -> str: ... + def repr_instance(self, x: object, level: complex) -> str: ... + +class TextDoc(Doc): + def repr(self, object: object) -> str: ... + def bold(self, text: str) -> str: ... + def indent(self, text: str, prefix: str = ...) -> str: ... + def section(self, title: str, contents: str) -> str: ... + def formattree(self, tree: List[Union[Tuple[type, Tuple[type, ...]], list]], modname: str, parent: Optional[type] = ..., prefix: str = ...) -> str: ... + def docmodule(self, object: object, name: Optional[str] = ..., mod: Optional[Any] = ..., *ignored) -> str: ... + def docclass(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., *ignored) -> str: ... + def formatvalue(self, object: object) -> str: ... + def docroutine(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., cl: Optional[Any] = ..., *ignored) -> str: ... + def docproperty(self, object: object, name: Optional[str] = ..., mod: Optional[Any] = ..., cl: Optional[Any] = ..., *ignored) -> str: ... + def docdata(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., cl: Optional[Any] = ..., *ignored) -> str: ... + def docother(self, object: object, name: Optional[str] = ..., mod: Optional[str] = ..., parent: Optional[str] = ..., maxlen: Optional[int] = ..., doc: Optional[Any] = ..., *ignored) -> str: ... + +def pager(text: str) -> None: ... +def getpager() -> Callable[[str], None]: ... +def plain(text: str) -> str: ... +def pipepager(text: str, cmd: str) -> None: ... +def tempfilepager(text: str, cmd: str) -> None: ... +def ttypager(text: str) -> None: ... +def plainpager(text: str) -> None: ... +def describe(thing: Any) -> str: ... +def locate(path: str, forceload: bool = ...) -> object: ... + +text = ... # type: TextDoc +html = ... # type: HTMLDoc + +class _OldStyleClass: ... + +def resolve(thing: Union[str, object], forceload: bool = ...) -> Optional[Tuple[object, str]]: ... +def render_doc(thing: Union[str, object], title: str = ..., forceload: bool = ...) -> str: ... +def doc(thing: Union[str, object], title: str = ..., forceload: bool = ...) -> None: ... +def writedoc(thing: Union[str, object], forceload: bool = ...) -> None: ... +def writedocs(dir: str, pkgpath: str = ..., done: Optional[Any] = ...) -> None: ... + +class Helper: + keywords = ... # type: Dict[str, Union[str, Tuple[str, str]]] + symbols = ... # type: Dict[str, str] + topics = ... # type: Dict[str, Union[str, Tuple[str, ...]]] + def __init__(self, input: Optional[IO[str]] = ..., output: Optional[IO[str]] = ...) -> None: ... + input = ... # type: IO[str] + output = ... # type: IO[str] + def __call__(self, request: Union[str, Helper, object] = ...) -> None: ... + def interact(self) -> None: ... + def getline(self, prompt: str) -> str: ... + def help(self, request: Any) -> None: ... + def intro(self) -> None: ... + def list(self, items: List[str], columns: int = ..., width: int = ...) -> None: ... + def listkeywords(self) -> None: ... + def listsymbols(self) -> None: ... + def listtopics(self) -> None: ... + def showtopic(self, topic: str, more_xrefs: str = ...) -> None: ... + def showsymbol(self, symbol: str) -> None: ... + def listmodules(self, key: str = ...) -> None: ... + +help = ... # type: Helper + +# See Python issue #11182: "remove the unused and undocumented pydoc.Scanner class" +# class Scanner: +# roots = ... # type: Any +# state = ... # type: Any +# children = ... # type: Any +# descendp = ... # type: Any +# def __init__(self, roots, children, descendp) -> None: ... +# def next(self): ... + +class ModuleScanner: + quit = ... # type: bool + def run(self, callback: Callable[[Optional[str], str, str], None], key: Optional[Any] = ..., completer: Optional[Callable[[], None]] = ..., onerror: Optional[Callable] = ...) -> None: ... + +def apropos(key: str) -> None: ... +def serve(port: int, callback: Optional[Callable[[Any], None]] = ..., completer: Optional[Callable[[], None]] = ...) -> None: ... +def gui() -> None: ... +def ispath(x: Any) -> bool: ... +def cli() -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/random.pyi b/client/typeshed-fallback/stdlib/2/random.pyi new file mode 100644 index 000000000..3292db864 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/random.pyi @@ -0,0 +1,75 @@ +# Stubs for random +# Ron Murawski +# Updated by Jukka Lehtosalo + +# based on https://docs.python.org/2/library/random.html + +# ----- random classes ----- + +import _random +from typing import ( + Any, TypeVar, Sequence, List, Callable, AbstractSet, Union, + overload +) + +_T = TypeVar('_T') + +class Random(_random.Random): + def __init__(self, x: object = ...) -> None: ... + def seed(self, x: object = ...) -> None: ... + def getstate(self) -> _random._State: ... + def setstate(self, state: _random._State) -> None: ... + def jumpahead(self, n: int) -> None: ... + def getrandbits(self, k: int) -> int: ... + @overload + def randrange(self, stop: int) -> int: ... + @overload + def randrange(self, start: int, stop: int, step: int = ...) -> int: ... + def randint(self, a: int, b: int) -> int: ... + def choice(self, seq: Sequence[_T]) -> _T: ... + def shuffle(self, x: List[Any], random: Callable[[], None] = ...) -> None: ... + def sample(self, population: Union[Sequence[_T], AbstractSet[_T]], k: int) -> List[_T]: ... + def random(self) -> float: ... + def uniform(self, a: float, b: float) -> float: ... + def triangular(self, low: float = ..., high: float = ..., mode: float = ...) -> float: ... + def betavariate(self, alpha: float, beta: float) -> float: ... + def expovariate(self, lambd: float) -> float: ... + def gammavariate(self, alpha: float, beta: float) -> float: ... + def gauss(self, mu: float, sigma: float) -> float: ... + def lognormvariate(self, mu: float, sigma: float) -> float: ... + def normalvariate(self, mu: float, sigma: float) -> float: ... + def vonmisesvariate(self, mu: float, kappa: float) -> float: ... + def paretovariate(self, alpha: float) -> float: ... + def weibullvariate(self, alpha: float, beta: float) -> float: ... + +# SystemRandom is not implemented for all OS's; good on Windows & Linux +class SystemRandom(Random): + ... + +# ----- random function stubs ----- +def seed(x: object = ...) -> None: ... +def getstate() -> object: ... +def setstate(state: object) -> None: ... +def jumpahead(n: int) -> None: ... +def getrandbits(k: int) -> int: ... +@overload +def randrange(stop: int) -> int: ... +@overload +def randrange(start: int, stop: int, step: int = ...) -> int: ... +def randint(a: int, b: int) -> int: ... +def choice(seq: Sequence[_T]) -> _T: ... +def shuffle(x: List[Any], random: Callable[[], float] = ...) -> None: ... +def sample(population: Union[Sequence[_T], AbstractSet[_T]], k: int) -> List[_T]: ... +def random() -> float: ... +def uniform(a: float, b: float) -> float: ... +def triangular(low: float = ..., high: float = ..., + mode: float = ...) -> float: ... +def betavariate(alpha: float, beta: float) -> float: ... +def expovariate(lambd: float) -> float: ... +def gammavariate(alpha: float, beta: float) -> float: ... +def gauss(mu: float, sigma: float) -> float: ... +def lognormvariate(mu: float, sigma: float) -> float: ... +def normalvariate(mu: float, sigma: float) -> float: ... +def vonmisesvariate(mu: float, kappa: float) -> float: ... +def paretovariate(alpha: float) -> float: ... +def weibullvariate(alpha: float, beta: float) -> float: ... diff --git a/client/typeshed-fallback/stdlib/2/re.pyi b/client/typeshed-fallback/stdlib/2/re.pyi new file mode 100644 index 000000000..2a2c2cb03 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/re.pyi @@ -0,0 +1,100 @@ +# Stubs for re +# Ron Murawski +# 'bytes' support added by Jukka Lehtosalo + +# based on: http: //docs.python.org/2.7/library/re.html + +from typing import ( + List, Iterator, overload, Callable, Tuple, Sequence, Dict, + Generic, AnyStr, Match, Pattern, Any, Optional, Union +) + +# ----- re variables and constants ----- +DEBUG = 0 +I = 0 +IGNORECASE = 0 +L = 0 +LOCALE = 0 +M = 0 +MULTILINE = 0 +S = 0 +DOTALL = 0 +X = 0 +VERBOSE = 0 +U = 0 +UNICODE = 0 +T = 0 +TEMPLATE = 0 + +class error(Exception): ... + +@overload +def compile(pattern: AnyStr, flags: int = ...) -> Pattern[AnyStr]: ... +@overload +def compile(pattern: Pattern[AnyStr], flags: int = ...) -> Pattern[AnyStr]: ... + +@overload +def search(pattern: Union[str, unicode], string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ... +@overload +def search(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ... + +@overload +def match(pattern: Union[str, unicode], string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ... +@overload +def match(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, flags: int = ...) -> Optional[Match[AnyStr]]: ... + +@overload +def split(pattern: Union[str, unicode], string: AnyStr, + maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ... +@overload +def split(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, + maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ... + +@overload +def findall(pattern: Union[str, unicode], string: AnyStr, flags: int = ...) -> List[Any]: ... +@overload +def findall(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, flags: int = ...) -> List[Any]: ... + +# Return an iterator yielding match objects over all non-overlapping matches +# for the RE pattern in string. The string is scanned left-to-right, and +# matches are returned in the order found. Empty matches are included in the +# result unless they touch the beginning of another match. +@overload +def finditer(pattern: Union[str, unicode], string: AnyStr, + flags: int = ...) -> Iterator[Match[AnyStr]]: ... +@overload +def finditer(pattern: Union[Pattern[str], Pattern[unicode]], string: AnyStr, + flags: int = ...) -> Iterator[Match[AnyStr]]: ... + +@overload +def sub(pattern: Union[str, unicode], repl: AnyStr, string: AnyStr, count: int = ..., + flags: int = ...) -> AnyStr: ... +@overload +def sub(pattern: Union[str, unicode], repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, count: int = ..., flags: int = ...) -> AnyStr: ... +@overload +def sub(pattern: Union[Pattern[str], Pattern[unicode]], repl: AnyStr, string: AnyStr, count: int = ..., + flags: int = ...) -> AnyStr: ... +@overload +def sub(pattern: Union[Pattern[str], Pattern[unicode]], repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, count: int = ..., flags: int = ...) -> AnyStr: ... + +@overload +def subn(pattern: Union[str, unicode], repl: AnyStr, string: AnyStr, count: int = ..., + flags: int = ...) -> Tuple[AnyStr, int]: ... +@overload +def subn(pattern: Union[str, unicode], repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, count: int = ..., + flags: int = ...) -> Tuple[AnyStr, int]: ... +@overload +def subn(pattern: Union[Pattern[str], Pattern[unicode]], repl: AnyStr, string: AnyStr, count: int = ..., + flags: int = ...) -> Tuple[AnyStr, int]: ... +@overload +def subn(pattern: Union[Pattern[str], Pattern[unicode]], repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, count: int = ..., + flags: int = ...) -> Tuple[AnyStr, int]: ... + +def escape(string: AnyStr) -> AnyStr: ... + +def purge() -> None: ... +def template(pattern: Union[AnyStr, Pattern[AnyStr]], flags: int = ...) -> Pattern[AnyStr]: ... diff --git a/client/typeshed-fallback/stdlib/2/repr.pyi b/client/typeshed-fallback/stdlib/2/repr.pyi new file mode 100644 index 000000000..5e54f6961 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/repr.pyi @@ -0,0 +1,31 @@ +class Repr: + maxarray = ... # type: int + maxdeque = ... # type: int + maxdict = ... # type: int + maxfrozenset = ... # type: int + maxlevel = ... # type: int + maxlist = ... # type: int + maxlong = ... # type: int + maxother = ... # type: int + maxset = ... # type: int + maxstring = ... # type: int + maxtuple = ... # type: int + def __init__(self) -> None: ... + def _repr_iterable(self, x, level: complex, left, right, maxiter, trail=...) -> str: ... + def repr(self, x) -> str: ... + def repr1(self, x, level: complex) -> str: ... + def repr_array(self, x, level: complex) -> str: ... + def repr_deque(self, x, level: complex) -> str: ... + def repr_dict(self, x, level: complex) -> str: ... + def repr_frozenset(self, x, level: complex) -> str: ... + def repr_instance(self, x, level: complex) -> str: ... + def repr_list(self, x, level: complex) -> str: ... + def repr_long(self, x, level: complex) -> str: ... + def repr_set(self, x, level: complex) -> str: ... + def repr_str(self, x, level: complex) -> str: ... + def repr_tuple(self, x, level: complex) -> str: ... + +def _possibly_sorted(x) -> list: ... + +aRepr = ... # type: Repr +def repr(x) -> str: ... diff --git a/client/typeshed-fallback/stdlib/2/resource.pyi b/client/typeshed-fallback/stdlib/2/resource.pyi new file mode 100644 index 000000000..92654a9c5 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/resource.pyi @@ -0,0 +1,33 @@ +from typing import Tuple, NamedTuple + +class error(Exception): ... + +RLIM_INFINITY = ... # type: int +def getrlimit(resource: int) -> Tuple[int, int]: ... +def setrlimit(resource: int, limits: Tuple[int, int]) -> None: ... + +RLIMIT_CORE = ... # type: int +RLIMIT_CPU = ... # type: int +RLIMIT_FSIZE = ... # type: int +RLIMIT_DATA = ... # type: int +RLIMIT_STACK = ... # type: int +RLIMIT_RSS = ... # type: int +RLIMIT_NPROC = ... # type: int +RLIMIT_NOFILE = ... # type: int +RLIMIT_OFILE = ... # type: int +RLIMIT_MEMLOCK = ... # type: int +RLIMIT_VMEM = ... # type: int +RLIMIT_AS = ... # type: int + +_RUsage = NamedTuple('_RUsage', [('ru_utime', float), ('ru_stime', float), ('ru_maxrss', int), + ('ru_ixrss', int), ('ru_idrss', int), ('ru_isrss', int), + ('ru_minflt', int), ('ru_majflt', int), ('ru_nswap', int), + ('ru_inblock', int), ('ru_oublock', int), ('ru_msgsnd', int), + ('ru_msgrcv', int), ('ru_nsignals', int), ('ru_nvcsw', int), + ('ru_nivcsw', int)]) +def getrusage(who: int) -> _RUsage: ... +def getpagesize() -> int: ... + +RUSAGE_SELF = ... # type: int +RUSAGE_CHILDREN = ... # type: int +RUSAGE_BOTH = ... # type: int diff --git a/client/typeshed-fallback/stdlib/2/rfc822.pyi b/client/typeshed-fallback/stdlib/2/rfc822.pyi new file mode 100644 index 000000000..2e37e9483 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/rfc822.pyi @@ -0,0 +1,79 @@ +# Stubs for rfc822 (Python 2) +# +# Based on stub generated by stubgen. + +from typing import Any, Optional + +class Message: + fp = ... # type: Any + seekable = ... # type: Any + startofheaders = ... # type: Any + startofbody = ... # type: Any + def __init__(self, fp, seekable: int = ...): ... + def rewindbody(self): ... + dict = ... # type: Any + unixfrom = ... # type: Any + headers = ... # type: Any + status = ... # type: Any + def readheaders(self): ... + def isheader(self, line): ... + def islast(self, line): ... + def iscomment(self, line): ... + def getallmatchingheaders(self, name): ... + def getfirstmatchingheader(self, name): ... + def getrawheader(self, name): ... + def getheader(self, name, default: Optional[Any] = ...): ... + get = ... # type: Any + def getheaders(self, name): ... + def getaddr(self, name): ... + def getaddrlist(self, name): ... + def getdate(self, name): ... + def getdate_tz(self, name): ... + def __len__(self): ... + def __getitem__(self, name): ... + def __setitem__(self, name, value): ... + def __delitem__(self, name): ... + def setdefault(self, name, default=...): ... + def has_key(self, name): ... + def __contains__(self, name): ... + def __iter__(self): ... + def keys(self): ... + def values(self): ... + def items(self): ... + +class AddrlistClass: + specials = ... # type: Any + pos = ... # type: Any + LWS = ... # type: Any + CR = ... # type: Any + atomends = ... # type: Any + phraseends = ... # type: Any + field = ... # type: Any + commentlist = ... # type: Any + def __init__(self, field): ... + def gotonext(self): ... + def getaddrlist(self): ... + def getaddress(self): ... + def getrouteaddr(self): ... + def getaddrspec(self): ... + def getdomain(self): ... + def getdelimited(self, beginchar, endchars, allowcomments: int = ...): ... + def getquote(self): ... + def getcomment(self): ... + def getdomainliteral(self): ... + def getatom(self, atomends: Optional[Any] = ...): ... + def getphraselist(self): ... + +class AddressList(AddrlistClass): + addresslist = ... # type: Any + def __init__(self, field): ... + def __len__(self): ... + def __add__(self, other): ... + def __iadd__(self, other): ... + def __sub__(self, other): ... + def __isub__(self, other): ... + def __getitem__(self, index): ... + +def parsedate_tz(data): ... +def parsedate(data): ... +def mktime_tz(data): ... diff --git a/client/typeshed-fallback/stdlib/2/robotparser.pyi b/client/typeshed-fallback/stdlib/2/robotparser.pyi new file mode 100644 index 000000000..403039ae9 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/robotparser.pyi @@ -0,0 +1,7 @@ +class RobotFileParser: + def set_url(self, url: str): ... + def read(self): ... + def parse(self, lines: str): ... + def can_fetch(self, user_agent: str, url: str): ... + def mtime(self): ... + def modified(self): ... diff --git a/client/typeshed-fallback/stdlib/2/runpy.pyi b/client/typeshed-fallback/stdlib/2/runpy.pyi new file mode 100644 index 000000000..846e492ba --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/runpy.pyi @@ -0,0 +1,17 @@ +from typing import Any, Optional + +class _TempModule: + mod_name = ... # type: Any + module = ... # type: Any + def __init__(self, mod_name): ... + def __enter__(self): ... + def __exit__(self, *args): ... + +class _ModifiedArgv0: + value = ... # type: Any + def __init__(self, value): ... + def __enter__(self): ... + def __exit__(self, *args): ... + +def run_module(mod_name, init_globals: Optional[Any] = ..., run_name: Optional[Any] = ..., alter_sys: bool = ...): ... +def run_path(path_name, init_globals: Optional[Any] = ..., run_name: Optional[Any] = ...): ... diff --git a/client/typeshed-fallback/stdlib/2/sets.pyi b/client/typeshed-fallback/stdlib/2/sets.pyi new file mode 100644 index 000000000..a68994f2f --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/sets.pyi @@ -0,0 +1,61 @@ +# Stubs for sets (Python 2) +from typing import Any, Callable, Hashable, Iterable, Iterator, MutableMapping, Optional, TypeVar, Union + +_T = TypeVar('_T') +_Setlike = Union[BaseSet[_T], Iterable[_T]] +_SelfT = TypeVar('_SelfT', bound=BaseSet) + +class BaseSet(Iterable[_T]): + def __init__(self) -> None: ... + def __len__(self) -> int: ... + def __repr__(self) -> str: ... + def __str__(self) -> str: ... + def __iter__(self) -> Iterator[_T]: ... + def __cmp__(self, other: Any) -> int: ... + def __eq__(self, other: Any) -> bool: ... + def __ne__(self, other: Any) -> bool: ... + def copy(self: _SelfT) -> _SelfT: ... + def __copy__(self: _SelfT) -> _SelfT: ... + def __deepcopy__(self: _SelfT, memo: MutableMapping[int, BaseSet[_T]]) -> _SelfT: ... + def __or__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def union(self: _SelfT, other: _Setlike) -> _SelfT: ... + def __and__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def intersection(self: _SelfT, other: _Setlike) -> _SelfT: ... + def __xor__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def symmetric_difference(self: _SelfT, other: _Setlike) -> _SelfT: ... + def __sub__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def difference(self: _SelfT, other: _Setlike) -> _SelfT: ... + def __contains__(self, element: Any) -> bool: ... + def issubset(self, other: BaseSet[_T]) -> bool: ... + def issuperset(self, other: BaseSet[_T]) -> bool: ... + def __le__(self, other: BaseSet[_T]) -> bool: ... + def __ge__(self, other: BaseSet[_T]) -> bool: ... + def __lt__(self, other: BaseSet[_T]) -> bool: ... + def __gt__(self, other: BaseSet[_T]) -> bool: ... + +class ImmutableSet(BaseSet[_T], Hashable): + def __init__(self, iterable: Optional[_Setlike] = ...) -> None: ... + def __hash__(self) -> int: ... + +class Set(BaseSet[_T]): + def __init__(self, iterable: Optional[_Setlike] = ...) -> None: ... + def __ior__(self, other: BaseSet[_T]) -> Set: ... + def union_update(self, other: _Setlike) -> None: ... + def __iand__(self, other: BaseSet[_T]) -> Set: ... + def intersection_update(self, other: _Setlike) -> None: ... + def __ixor__(self, other: BaseSet[_T]) -> Set: ... + def symmetric_difference_update(self, other: _Setlike) -> None: ... + def __isub__(self, other: BaseSet[_T]) -> Set: ... + def difference_update(self, other: _Setlike) -> None: ... + def update(self, iterable: _Setlike) -> None: ... + def clear(self) -> None: ... + def add(self, element: _T) -> None: ... + def remove(self, element: _T) -> None: ... + def discard(self, element: _T) -> None: ... + def pop(self) -> _T: ... + def __as_immutable__(self) -> ImmutableSet[_T]: ... + def __as_temporarily_immutable__(self) -> _TemporarilyImmutableSet[_T]: ... + +class _TemporarilyImmutableSet(BaseSet[_T]): + def __init__(self, set: BaseSet[_T]) -> None: ... + def __hash__(self) -> int: ... diff --git a/client/typeshed-fallback/stdlib/2/sha.pyi b/client/typeshed-fallback/stdlib/2/sha.pyi new file mode 100644 index 000000000..f1606fa8d --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/sha.pyi @@ -0,0 +1,11 @@ +# Stubs for Python 2.7 sha stdlib module + +class sha(object): + def update(self, arg: str) -> None: ... + def digest(self) -> str: ... + def hexdigest(self) -> str: ... + def copy(self) -> sha: ... + +def new(string: str = ...) -> sha: ... +blocksize = 0 +digest_size = 0 diff --git a/client/typeshed-fallback/stdlib/2/shelve.pyi b/client/typeshed-fallback/stdlib/2/shelve.pyi new file mode 100644 index 000000000..d7d9b8c60 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/shelve.pyi @@ -0,0 +1,33 @@ +from typing import Any, Dict, Iterator, List, Optional, Tuple +import collections + + +class Shelf(collections.MutableMapping): + def __init__(self, dict: Dict[Any, Any], protocol: Optional[int] = ..., writeback: bool = ..., keyencoding: str = ...) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def keys(self) -> List[Any]: ... + def __len__(self) -> int: ... + def has_key(self, key: Any) -> bool: ... + def __contains__(self, key: Any) -> bool: ... + def get(self, key: Any, default: Any = ...) -> Any: ... + def __getitem__(self, key: Any) -> Any: ... + def __setitem__(self, key: Any, value: Any) -> None: ... + def __delitem__(self, key: Any) -> None: ... + def __enter__(self) -> Shelf: ... + def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... + def close(self) -> None: ... + def __del__(self) -> None: ... + def sync(self) -> None: ... + +class BsdDbShelf(Shelf): + def __init__(self, dict: Dict[Any, Any], protocol: Optional[int] = ..., writeback: bool = ..., keyencoding: str = ...) -> None: ... + def set_location(self, key: Any) -> Tuple[str, Any]: ... + def next(self) -> Tuple[str, Any]: ... + def previous(self) -> Tuple[str, Any]: ... + def first(self) -> Tuple[str, Any]: ... + def last(self) -> Tuple[str, Any]: ... + +class DbfilenameShelf(Shelf): + def __init__(self, filename: str, flag: str = ..., protocol: Optional[int] = ..., writeback: bool = ...) -> None: ... + +def open(filename: str, flag: str = ..., protocol: Optional[int] = ..., writeback: bool = ...) -> DbfilenameShelf: ... diff --git a/client/typeshed-fallback/stdlib/2/shlex.pyi b/client/typeshed-fallback/stdlib/2/shlex.pyi new file mode 100644 index 000000000..4b80fb641 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/shlex.pyi @@ -0,0 +1,27 @@ +from typing import Optional, List, Any, IO + +def split(s: Optional[str], comments: bool = ..., posix: bool = ...) -> List[str]: ... + +class shlex: + def __init__(self, instream: IO[Any] = ..., infile: IO[Any] = ..., posix: bool = ...) -> None: ... + def get_token(self) -> Optional[str]: ... + def push_token(self, _str: str) -> None: ... + def read_token(self) -> str: ... + def sourcehook(self, filename: str) -> None: ... + def push_source(self, stream: IO[Any], filename: str = ...) -> None: ... + def pop_source(self) -> IO[Any]: ... + def error_leader(self, file: str = ..., line: int = ...) -> str: ... + + commenters = ... # type: str + wordchars = ... # type: str + whitespace = ... # type: str + escape = ... # type: str + quotes = ... # type: str + escapedquotes = ... # type: str + whitespace_split = ... # type: bool + infile = ... # type: IO[Any] + source = ... # type: Optional[str] + debug = ... # type: int + lineno = ... # type: int + token = ... # type: Any + eof = ... # type: Optional[str] diff --git a/client/typeshed-fallback/stdlib/2/signal.pyi b/client/typeshed-fallback/stdlib/2/signal.pyi new file mode 100644 index 000000000..cda4c65ec --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/signal.pyi @@ -0,0 +1,71 @@ +from typing import Callable, Any, Tuple, Union +from types import FrameType + +SIG_DFL: int = ... +SIG_IGN: int = ... + +ITIMER_REAL: int = ... +ITIMER_VIRTUAL: int = ... +ITIMER_PROF: int = ... + +NSIG: int = ... + +SIGABRT: int = ... +SIGALRM: int = ... +SIGBREAK: int = ... # Windows +SIGBUS: int = ... +SIGCHLD: int = ... +SIGCLD: int = ... +SIGCONT: int = ... +SIGEMT: int = ... +SIGFPE: int = ... +SIGHUP: int = ... +SIGILL: int = ... +SIGINFO: int = ... +SIGINT: int = ... +SIGIO: int = ... +SIGIOT: int = ... +SIGKILL: int = ... +SIGPIPE: int = ... +SIGPOLL: int = ... +SIGPROF: int = ... +SIGPWR: int = ... +SIGQUIT: int = ... +SIGRTMAX: int = ... +SIGRTMIN: int = ... +SIGSEGV: int = ... +SIGSTOP: int = ... +SIGSYS: int = ... +SIGTERM: int = ... +SIGTRAP: int = ... +SIGTSTP: int = ... +SIGTTIN: int = ... +SIGTTOU: int = ... +SIGURG: int = ... +SIGUSR1: int = ... +SIGUSR2: int = ... +SIGVTALRM: int = ... +SIGWINCH: int = ... +SIGXCPU: int = ... +SIGXFSZ: int = ... + +# Windows +CTRL_C_EVENT: int = ... +CTRL_BREAK_EVENT: int = ... + +class ItimerError(IOError): ... + +_HANDLER = Union[Callable[[int, FrameType], None], int, None] + +def alarm(time: int) -> int: ... +def getsignal(signalnum: int) -> _HANDLER: ... +def pause() -> None: ... +def setitimer(which: int, seconds: float, interval: float = ...) -> Tuple[float, float]: ... +def getitimer(which: int) -> Tuple[float, float]: ... +def set_wakeup_fd(fd: int) -> int: ... +def siginterrupt(signalnum: int, flag: bool) -> None: + raise RuntimeError() +def signal(signalnum: int, handler: _HANDLER) -> _HANDLER: + raise RuntimeError() +def default_int_handler(signum: int, frame: FrameType) -> None: + raise KeyboardInterrupt() diff --git a/client/typeshed-fallback/stdlib/2/smtplib.pyi b/client/typeshed-fallback/stdlib/2/smtplib.pyi new file mode 100644 index 000000000..76bdcb459 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/smtplib.pyi @@ -0,0 +1,86 @@ +from typing import Any + +class SMTPException(Exception): ... +class SMTPServerDisconnected(SMTPException): ... + +class SMTPResponseException(SMTPException): + smtp_code = ... # type: Any + smtp_error = ... # type: Any + args = ... # type: Any + def __init__(self, code, msg) -> None: ... + +class SMTPSenderRefused(SMTPResponseException): + smtp_code = ... # type: Any + smtp_error = ... # type: Any + sender = ... # type: Any + args = ... # type: Any + def __init__(self, code, msg, sender) -> None: ... + +class SMTPRecipientsRefused(SMTPException): + recipients = ... # type: Any + args = ... # type: Any + def __init__(self, recipients) -> None: ... + +class SMTPDataError(SMTPResponseException): ... +class SMTPConnectError(SMTPResponseException): ... +class SMTPHeloError(SMTPResponseException): ... +class SMTPAuthenticationError(SMTPResponseException): ... + +def quoteaddr(addr): ... +def quotedata(data): ... + +class SSLFakeFile: + sslobj = ... # type: Any + def __init__(self, sslobj) -> None: ... + def readline(self, size=...): ... + def close(self): ... + +class SMTP: + debuglevel = ... # type: Any + file = ... # type: Any + helo_resp = ... # type: Any + ehlo_msg = ... # type: Any + ehlo_resp = ... # type: Any + does_esmtp = ... # type: Any + default_port = ... # type: Any + timeout = ... # type: Any + esmtp_features = ... # type: Any + local_hostname = ... # type: Any + def __init__(self, host: str = ..., port: int = ..., local_hostname=..., timeout=...) -> None: ... + def set_debuglevel(self, debuglevel): ... + sock = ... # type: Any + def connect(self, host=..., port=...): ... + def send(self, str): ... + def putcmd(self, cmd, args=...): ... + def getreply(self): ... + def docmd(self, cmd, args=...): ... + def helo(self, name=...): ... + def ehlo(self, name=...): ... + def has_extn(self, opt): ... + def help(self, args=...): ... + def rset(self): ... + def noop(self): ... + def mail(self, sender, options=...): ... + def rcpt(self, recip, options=...): ... + def data(self, msg): ... + def verify(self, address): ... + vrfy = ... # type: Any + def expn(self, address): ... + def ehlo_or_helo_if_needed(self): ... + def login(self, user, password): ... + def starttls(self, keyfile=..., certfile=...): ... + def sendmail(self, from_addr, to_addrs, msg, mail_options=..., rcpt_options=...): ... + def close(self): ... + def quit(self): ... + +class SMTP_SSL(SMTP): + default_port = ... # type: Any + keyfile = ... # type: Any + certfile = ... # type: Any + def __init__(self, host=..., port=..., local_hostname=..., keyfile=..., certfile=..., timeout=...) -> None: ... + +class LMTP(SMTP): + ehlo_msg = ... # type: Any + def __init__(self, host=..., port=..., local_hostname=...) -> None: ... + sock = ... # type: Any + def connect(self, host=..., port=...): ... diff --git a/client/typeshed-fallback/stdlib/2/spwd.pyi b/client/typeshed-fallback/stdlib/2/spwd.pyi new file mode 100644 index 000000000..1d5899031 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/spwd.pyi @@ -0,0 +1,14 @@ +from typing import List, NamedTuple + +struct_spwd = NamedTuple("struct_spwd", [("sp_nam", str), + ("sp_pwd", str), + ("sp_lstchg", int), + ("sp_min", int), + ("sp_max", int), + ("sp_warn", int), + ("sp_inact", int), + ("sp_expire", int), + ("sp_flag", int)]) + +def getspall() -> List[struct_spwd]: ... +def getspnam(name: str) -> struct_spwd: ... diff --git a/client/typeshed-fallback/stdlib/2/sre_constants.pyi b/client/typeshed-fallback/stdlib/2/sre_constants.pyi new file mode 100644 index 000000000..4404873f6 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/sre_constants.pyi @@ -0,0 +1,94 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/sre_constants.py + +from typing import Dict, List, TypeVar + +MAGIC = ... # type: int +MAXREPEAT = ... # type: int + +class error(Exception): ... + +FAILURE = ... # type: str +SUCCESS = ... # type: str +ANY = ... # type: str +ANY_ALL = ... # type: str +ASSERT = ... # type: str +ASSERT_NOT = ... # type: str +AT = ... # type: str +BIGCHARSET = ... # type: str +BRANCH = ... # type: str +CALL = ... # type: str +CATEGORY = ... # type: str +CHARSET = ... # type: str +GROUPREF = ... # type: str +GROUPREF_IGNORE = ... # type: str +GROUPREF_EXISTS = ... # type: str +IN = ... # type: str +IN_IGNORE = ... # type: str +INFO = ... # type: str +JUMP = ... # type: str +LITERAL = ... # type: str +LITERAL_IGNORE = ... # type: str +MARK = ... # type: str +MAX_REPEAT = ... # type: str +MAX_UNTIL = ... # type: str +MIN_REPEAT = ... # type: str +MIN_UNTIL = ... # type: str +NEGATE = ... # type: str +NOT_LITERAL = ... # type: str +NOT_LITERAL_IGNORE = ... # type: str +RANGE = ... # type: str +REPEAT = ... # type: str +REPEAT_ONE = ... # type: str +SUBPATTERN = ... # type: str +MIN_REPEAT_ONE = ... # type: str +AT_BEGINNING = ... # type: str +AT_BEGINNING_LINE = ... # type: str +AT_BEGINNING_STRING = ... # type: str +AT_BOUNDARY = ... # type: str +AT_NON_BOUNDARY = ... # type: str +AT_END = ... # type: str +AT_END_LINE = ... # type: str +AT_END_STRING = ... # type: str +AT_LOC_BOUNDARY = ... # type: str +AT_LOC_NON_BOUNDARY = ... # type: str +AT_UNI_BOUNDARY = ... # type: str +AT_UNI_NON_BOUNDARY = ... # type: str +CATEGORY_DIGIT = ... # type: str +CATEGORY_NOT_DIGIT = ... # type: str +CATEGORY_SPACE = ... # type: str +CATEGORY_NOT_SPACE = ... # type: str +CATEGORY_WORD = ... # type: str +CATEGORY_NOT_WORD = ... # type: str +CATEGORY_LINEBREAK = ... # type: str +CATEGORY_NOT_LINEBREAK = ... # type: str +CATEGORY_LOC_WORD = ... # type: str +CATEGORY_LOC_NOT_WORD = ... # type: str +CATEGORY_UNI_DIGIT = ... # type: str +CATEGORY_UNI_NOT_DIGIT = ... # type: str +CATEGORY_UNI_SPACE = ... # type: str +CATEGORY_UNI_NOT_SPACE = ... # type: str +CATEGORY_UNI_WORD = ... # type: str +CATEGORY_UNI_NOT_WORD = ... # type: str +CATEGORY_UNI_LINEBREAK = ... # type: str +CATEGORY_UNI_NOT_LINEBREAK = ... # type: str + +_T = TypeVar('_T') +def makedict(list: List[_T]) -> Dict[_T, int]: ... + +OP_IGNORE = ... # type: Dict[str, str] +AT_MULTILINE = ... # type: Dict[str, str] +AT_LOCALE = ... # type: Dict[str, str] +AT_UNICODE = ... # type: Dict[str, str] +CH_LOCALE = ... # type: Dict[str, str] +CH_UNICODE = ... # type: Dict[str, str] +SRE_FLAG_TEMPLATE = ... # type: int +SRE_FLAG_IGNORECASE = ... # type: int +SRE_FLAG_LOCALE = ... # type: int +SRE_FLAG_MULTILINE = ... # type: int +SRE_FLAG_DOTALL = ... # type: int +SRE_FLAG_UNICODE = ... # type: int +SRE_FLAG_VERBOSE = ... # type: int +SRE_FLAG_DEBUG = ... # type: int +SRE_INFO_PREFIX = ... # type: int +SRE_INFO_LITERAL = ... # type: int +SRE_INFO_CHARSET = ... # type: int diff --git a/client/typeshed-fallback/stdlib/2/sre_parse.pyi b/client/typeshed-fallback/stdlib/2/sre_parse.pyi new file mode 100644 index 000000000..544a6182d --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/sre_parse.pyi @@ -0,0 +1,63 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/sre_parse.py + +from typing import Any, Dict, Iterable, List, Match, Optional, Pattern as _Pattern, Set, Tuple, Union + +SPECIAL_CHARS = ... # type: str +REPEAT_CHARS = ... # type: str +DIGITS = ... # type: Set +OCTDIGITS = ... # type: Set +HEXDIGITS = ... # type: Set +WHITESPACE = ... # type: Set +ESCAPES = ... # type: Dict[str, Tuple[str, int]] +CATEGORIES = ... # type: Dict[str, Union[Tuple[str, str], Tuple[str, List[Tuple[str, str]]]]] +FLAGS = ... # type: Dict[str, int] + +class Pattern: + flags = ... # type: int + open = ... # type: List[int] + groups = ... # type: int + groupdict = ... # type: Dict[str, int] + lookbehind = ... # type: int + def __init__(self) -> None: ... + def opengroup(self, name: str = ...) -> int: ... + def closegroup(self, gid: int) -> None: ... + def checkgroup(self, gid: int) -> bool: ... + + +_OpSubpatternType = Tuple[Optional[int], int, int, SubPattern] +_OpGroupRefExistsType = Tuple[int, SubPattern, SubPattern] +_OpInType = List[Tuple[str, int]] +_OpBranchType = Tuple[None, List[SubPattern]] +_AvType = Union[_OpInType, _OpBranchType, Iterable[SubPattern], _OpGroupRefExistsType, _OpSubpatternType] +_CodeType = Union[str, _AvType] + +class SubPattern: + pattern = ... # type: str + data = ... # type: List[_CodeType] + width = ... # type: Optional[int] + def __init__(self, pattern, data: List[_CodeType] = ...) -> None: ... + def dump(self, level: int = ...) -> None: ... + def __len__(self) -> int: ... + def __delitem__(self, index: Union[int, slice]) -> None: ... + def __getitem__(self, index: Union[int, slice]) -> Union[SubPattern, _CodeType]: ... + def __setitem__(self, index: Union[int, slice], code: _CodeType): ... + def insert(self, index, code: _CodeType) -> None: ... + def append(self, code: _CodeType) -> None: ... + def getwidth(self) -> int: ... + +class Tokenizer: + string = ... # type: str + index = ... # type: int + def __init__(self, string: str) -> None: ... + def match(self, char: str, skip: int = ...) -> int: ... + def get(self) -> Optional[str]: ... + def tell(self) -> Tuple[int, Optional[str]]: ... + def seek(self, index: int) -> None: ... + +def isident(char: str) -> bool: ... +def isdigit(char: str) -> bool: ... +def isname(name: str) -> bool: ... +def parse(str: str, flags: int = ..., pattern: Pattern = ...) -> SubPattern: ... +_Template = Tuple[List[Tuple[int, int]], List[Optional[int]]] +def parse_template(source: str, pattern: _Pattern) -> _Template: ... +def expand_template(template: _Template, match: Match) -> str: ... diff --git a/client/typeshed-fallback/stdlib/2/stat.pyi b/client/typeshed-fallback/stdlib/2/stat.pyi new file mode 100644 index 000000000..dd3418db9 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/stat.pyi @@ -0,0 +1,59 @@ +def S_ISDIR(mode: int) -> bool: ... +def S_ISCHR(mode: int) -> bool: ... +def S_ISBLK(mode: int) -> bool: ... +def S_ISREG(mode: int) -> bool: ... +def S_ISFIFO(mode: int) -> bool: ... +def S_ISLNK(mode: int) -> bool: ... +def S_ISSOCK(mode: int) -> bool: ... + +def S_IMODE(mode: int) -> int: ... +def S_IFMT(mode: int) -> int: ... + +ST_MODE = 0 +ST_INO = 0 +ST_DEV = 0 +ST_NLINK = 0 +ST_UID = 0 +ST_GID = 0 +ST_SIZE = 0 +ST_ATIME = 0 +ST_MTIME = 0 +ST_CTIME = 0 +S_IFSOCK = 0 +S_IFLNK = 0 +S_IFREG = 0 +S_IFBLK = 0 +S_IFDIR = 0 +S_IFCHR = 0 +S_IFIFO = 0 +S_ISUID = 0 +S_ISGID = 0 +S_ISVTX = 0 +S_IRWXU = 0 +S_IRUSR = 0 +S_IWUSR = 0 +S_IXUSR = 0 +S_IRWXG = 0 +S_IRGRP = 0 +S_IWGRP = 0 +S_IXGRP = 0 +S_IRWXO = 0 +S_IROTH = 0 +S_IWOTH = 0 +S_IXOTH = 0 +S_ENFMT = 0 +S_IREAD = 0 +S_IWRITE = 0 +S_IEXEC = 0 +UF_NODUMP = 0 +UF_IMMUTABLE = 0 +UF_APPEND = 0 +UF_OPAQUE = 0 +UF_NOUNLINK = 0 +UF_COMPRESSED = 0 +UF_HIDDEN = 0 +SF_ARCHIVED = 0 +SF_IMMUTABLE = 0 +SF_APPEND = 0 +SF_NOUNLINK = 0 +SF_SNAPSHOT = 0 diff --git a/client/typeshed-fallback/stdlib/2/string.pyi b/client/typeshed-fallback/stdlib/2/string.pyi new file mode 100644 index 000000000..751fd28a0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/string.pyi @@ -0,0 +1,74 @@ +# Stubs for string + +# Based on http://docs.python.org/3.2/library/string.html + +from typing import Mapping, Sequence, Any, Optional, Union, List, Tuple, Iterable, AnyStr + +ascii_letters = ... # type: str +ascii_lowercase = ... # type: str +ascii_uppercase = ... # type: str +digits = ... # type: str +hexdigits = ... # type: str +letters = ... # type: str +lowercase = ... # type: str +octdigits = ... # type: str +punctuation = ... # type: str +printable = ... # type: str +uppercase = ... # type: str +whitespace = ... # type: str + +def capwords(s: AnyStr, sep: AnyStr = ...) -> AnyStr: ... +# TODO: originally named 'from' +def maketrans(_from: str, to: str) -> str: ... +def atof(s: unicode) -> float: ... +def atoi(s: unicode, base: int = ...) -> int: ... +def atol(s: unicode, base: int = ...) -> int: ... +def capitalize(word: AnyStr) -> AnyStr: ... +def find(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def rfind(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def index(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def rindex(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def count(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def lower(s: AnyStr) -> AnyStr: ... +def split(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def rsplit(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def splitfields(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def join(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... +def joinfields(word: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... +def lstrip(s: AnyStr, chars: AnyStr = ...) -> AnyStr: ... +def rstrip(s: AnyStr, chars: AnyStr = ...) -> AnyStr: ... +def strip(s: AnyStr, chars: AnyStr = ...) -> AnyStr: ... +def swapcase(s: AnyStr) -> AnyStr: ... +def translate(s: str, table: str, deletechars: str = ...) -> str: ... +def upper(s: AnyStr) -> AnyStr: ... +def ljust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def rjust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def center(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def zfill(s: AnyStr, width: int) -> AnyStr: ... +def replace(s: AnyStr, old: AnyStr, new: AnyStr, maxreplace: int = ...) -> AnyStr: ... + +class Template(object): + # TODO: Unicode support? + template = ... # type: str + + def __init__(self, template: str) -> None: ... + def substitute(self, mapping: Mapping[str, str] = ..., **kwds: str) -> str: ... + def safe_substitute(self, mapping: Mapping[str, str] = ..., + **kwds: str) -> str: ... + +# TODO(MichalPokorny): This is probably badly and/or loosely typed. +class Formatter(object): + def format(self, format_string: str, *args, **kwargs) -> str: ... + def vformat(self, format_string: str, args: Sequence[Any], + kwargs: Mapping[str, Any]) -> str: ... + def parse(self, format_string: str) -> Iterable[Tuple[str, str, str, str]]: ... + def get_field(self, field_name: str, args: Sequence[Any], + kwargs: Mapping[str, Any]) -> Any: ... + def get_value(self, key: Union[int, str], args: Sequence[Any], + kwargs: Mapping[str, Any]) -> Any: + raise IndexError() + raise KeyError() + def check_unused_args(self, used_args: Sequence[Union[int, str]], args: Sequence[Any], + kwargs: Mapping[str, Any]) -> None: ... + def format_field(self, value: Any, format_spec: str) -> Any: ... + def convert_field(self, value: Any, conversion: str) -> Any: ... diff --git a/client/typeshed-fallback/stdlib/2/stringold.pyi b/client/typeshed-fallback/stdlib/2/stringold.pyi new file mode 100644 index 000000000..7d31ebe5b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/stringold.pyi @@ -0,0 +1,46 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/stringold.py +from typing import AnyStr, Iterable, List, Optional, Type + +whitespace = ... # type: str +lowercase = ... # type: str +uppercase = ... # type: str +letters = ... # type: str +digits = ... # type: str +hexdigits = ... # type: str +octdigits = ... # type: str +_idmap = ... # type: str +_idmapL = ... # type: Optional[List[str]] +index_error = ValueError +atoi_error = ValueError +atof_error = ValueError +atol_error = ValueError + + +def lower(s: AnyStr) -> AnyStr: ... +def upper(s: AnyStr) -> AnyStr: ... +def swapcase(s: AnyStr) -> AnyStr: ... +def strip(s: AnyStr) -> AnyStr: ... +def lstrip(s: AnyStr) -> AnyStr: ... +def rstrip(s: AnyStr) -> AnyStr: ... +def split(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def splitfields(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def join(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... +def joinfields(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... +def index(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def rindex(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def count(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def find(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def rfind(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... +def atof(s: unicode) -> float: ... +def atoi(s: unicode, base: int = ...) -> int: ... +def atol(s: unicode, base: int = ...) -> long: ... +def ljust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def rjust(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def center(s: AnyStr, width: int, fillchar: AnyStr = ...) -> AnyStr: ... +def zfill(s: AnyStr, width: int) -> AnyStr: ... +def expandtabs(s: AnyStr, tabsize: int = ...) -> AnyStr: ... +def translate(s: str, table: str, deletions: str = ...) -> str: ... +def capitalize(s: AnyStr) -> AnyStr: ... +def capwords(s: AnyStr, sep: AnyStr = ...) -> AnyStr: ... +def maketrans(fromstr: str, tostr: str) -> str: ... +def replace(s: AnyStr, old: AnyStr, new: AnyStr, maxreplace: int = ...) -> AnyStr: ... diff --git a/client/typeshed-fallback/stdlib/2/strop.pyi b/client/typeshed-fallback/stdlib/2/strop.pyi new file mode 100644 index 000000000..736c716a3 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/strop.pyi @@ -0,0 +1,72 @@ +"""Stub file for the 'strop' module.""" + +from typing import List, Sequence + +lowercase = ... # type: str +uppercase = ... # type: str +whitespace = ... # type: str + +def atof(a: str) -> float: + raise DeprecationWarning() + +def atoi(a: str, base: int = ...) -> int: + raise DeprecationWarning() + +def atol(a: str, base: int = ...) -> long: + raise DeprecationWarning() + +def capitalize(s: str) -> str: + raise DeprecationWarning() + +def count(s: str, sub: str, start: int = ..., end: int = ...) -> int: + raise DeprecationWarning() + +def expandtabs(string: str, tabsize: int = ...) -> str: + raise DeprecationWarning() + raise OverflowError() + +def find(s: str, sub: str, start: int = ..., end: int = ...) -> int: + raise DeprecationWarning() + +def join(list: Sequence[str], sep: str = ...) -> str: + raise DeprecationWarning() + raise OverflowError() + +def joinfields(list: Sequence[str], sep: str = ...) -> str: + raise DeprecationWarning() + raise OverflowError() + +def lower(s: str) -> str: + raise DeprecationWarning() + +def lstrip(s: str) -> str: + raise DeprecationWarning() + +def maketrans(frm: str, to: str) -> str: ... + +def replace(s: str, old: str, new: str, maxsplit: int = ...) -> str: + raise DeprecationWarning() + +def rfind(s: str, sub: str, start: int = ..., end: int = ...) -> int: + raise DeprecationWarning() + +def rstrip(s: str) -> str: + raise DeprecationWarning() + +def split(s: str, sep: str, maxsplit: int = ...) -> List[str]: + raise DeprecationWarning() + +def splitfields(s: str, sep: str, maxsplit: int = ...) -> List[str]: + raise DeprecationWarning() + +def strip(s: str) -> str: + raise DeprecationWarning() + +def swapcase(s: str) -> str: + raise DeprecationWarning() + +def translate(s: str, table: str, deletechars: str = ...) -> str: + raise DeprecationWarning() + +def upper(s: str) -> str: + raise DeprecationWarning() diff --git a/client/typeshed-fallback/stdlib/2/subprocess.pyi b/client/typeshed-fallback/stdlib/2/subprocess.pyi new file mode 100644 index 000000000..0e1360949 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/subprocess.pyi @@ -0,0 +1,115 @@ +# Stubs for subprocess + +# Based on http://docs.python.org/2/library/subprocess.html and Python 3 stub + +from typing import Sequence, Any, Mapping, Callable, Tuple, IO, Union, Optional, List, Text + +_FILE = Union[None, int, IO[Any]] +_TXT = Union[bytes, Text] +_CMD = Union[_TXT, Sequence[_TXT]] +_ENV = Union[Mapping[bytes, _TXT], Mapping[Text, _TXT]] + +# Same args as Popen.__init__ +def call(args: _CMD, + bufsize: int = ..., + executable: _TXT = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: _TXT = ..., + env: _ENV = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ...) -> int: ... + +def check_call(args: _CMD, + bufsize: int = ..., + executable: _TXT = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: _TXT = ..., + env: _ENV = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ...) -> int: ... + +# Same args as Popen.__init__ except for stdout +def check_output(args: _CMD, + bufsize: int = ..., + executable: _TXT = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: _TXT = ..., + env: _ENV = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ...) -> bytes: ... + +PIPE = ... # type: int +STDOUT = ... # type: int + +class CalledProcessError(Exception): + returncode = 0 + # morally: _CMD + cmd = ... # type: Any + # morally: Optional[bytes] + output = ... # type: Any + + def __init__(self, + returncode: int, + cmd: _CMD, + output: Optional[bytes] = ...) -> None: ... + +class Popen: + stdin = ... # type: Optional[IO[Any]] + stdout = ... # type: Optional[IO[Any]] + stderr = ... # type: Optional[IO[Any]] + pid = 0 + returncode = 0 + + def __init__(self, + args: _CMD, + bufsize: int = ..., + executable: Optional[_TXT] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_TXT] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ...) -> None: ... + + def poll(self) -> int: ... + def wait(self) -> int: ... + # morally: -> Tuple[Optional[bytes], Optional[bytes]] + def communicate(self, input: Optional[_TXT] = ...) -> Tuple[Any, Any]: ... + def send_signal(self, signal: int) -> None: ... + def terminate(self) -> None: ... + def kill(self) -> None: ... + def __enter__(self) -> Popen: ... + def __exit__(self, type, value, traceback) -> bool: ... + +# Windows-only: STARTUPINFO etc. + +STD_INPUT_HANDLE = ... # type: Any +STD_OUTPUT_HANDLE = ... # type: Any +STD_ERROR_HANDLE = ... # type: Any +SW_HIDE = ... # type: Any +STARTF_USESTDHANDLES = ... # type: Any +STARTF_USESHOWWINDOW = ... # type: Any +CREATE_NEW_CONSOLE = ... # type: Any +CREATE_NEW_PROCESS_GROUP = ... # type: Any diff --git a/client/typeshed-fallback/stdlib/2/symbol.pyi b/client/typeshed-fallback/stdlib/2/symbol.pyi new file mode 100644 index 000000000..ef41c8129 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/symbol.pyi @@ -0,0 +1,91 @@ +# Stubs for symbol (Python 2) + +from typing import Dict + +single_input = ... # type: int +file_input = ... # type: int +eval_input = ... # type: int +decorator = ... # type: int +decorators = ... # type: int +decorated = ... # type: int +funcdef = ... # type: int +parameters = ... # type: int +varargslist = ... # type: int +fpdef = ... # type: int +fplist = ... # type: int +stmt = ... # type: int +simple_stmt = ... # type: int +small_stmt = ... # type: int +expr_stmt = ... # type: int +augassign = ... # type: int +print_stmt = ... # type: int +del_stmt = ... # type: int +pass_stmt = ... # type: int +flow_stmt = ... # type: int +break_stmt = ... # type: int +continue_stmt = ... # type: int +return_stmt = ... # type: int +yield_stmt = ... # type: int +raise_stmt = ... # type: int +import_stmt = ... # type: int +import_name = ... # type: int +import_from = ... # type: int +import_as_name = ... # type: int +dotted_as_name = ... # type: int +import_as_names = ... # type: int +dotted_as_names = ... # type: int +dotted_name = ... # type: int +global_stmt = ... # type: int +exec_stmt = ... # type: int +assert_stmt = ... # type: int +compound_stmt = ... # type: int +if_stmt = ... # type: int +while_stmt = ... # type: int +for_stmt = ... # type: int +try_stmt = ... # type: int +with_stmt = ... # type: int +with_item = ... # type: int +except_clause = ... # type: int +suite = ... # type: int +testlist_safe = ... # type: int +old_test = ... # type: int +old_lambdef = ... # type: int +test = ... # type: int +or_test = ... # type: int +and_test = ... # type: int +not_test = ... # type: int +comparison = ... # type: int +comp_op = ... # type: int +expr = ... # type: int +xor_expr = ... # type: int +and_expr = ... # type: int +shift_expr = ... # type: int +arith_expr = ... # type: int +term = ... # type: int +factor = ... # type: int +power = ... # type: int +atom = ... # type: int +listmaker = ... # type: int +testlist_comp = ... # type: int +lambdef = ... # type: int +trailer = ... # type: int +subscriptlist = ... # type: int +subscript = ... # type: int +sliceop = ... # type: int +exprlist = ... # type: int +testlist = ... # type: int +dictorsetmaker = ... # type: int +classdef = ... # type: int +arglist = ... # type: int +argument = ... # type: int +list_iter = ... # type: int +list_for = ... # type: int +list_if = ... # type: int +comp_iter = ... # type: int +comp_for = ... # type: int +comp_if = ... # type: int +testlist1 = ... # type: int +encoding_decl = ... # type: int +yield_expr = ... # type: int + +sym_name = ... # type: Dict[int, str] diff --git a/client/typeshed-fallback/stdlib/2/sys.pyi b/client/typeshed-fallback/stdlib/2/sys.pyi new file mode 100644 index 000000000..33fca3bea --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/sys.pyi @@ -0,0 +1,138 @@ +"""Stubs for the 'sys' module.""" + +from typing import ( + IO, NoReturn, Union, List, Sequence, Any, Dict, Tuple, BinaryIO, Optional, + Callable, overload, Text, Type, +) +from types import FrameType, ModuleType, TracebackType, ClassType + +# The following type alias are stub-only and do not exist during runtime +_ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType] +_OptExcInfo = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] + +class _flags: + bytes_warning = ... # type: int + debug = ... # type: int + division_new = ... # type: int + division_warning = ... # type: int + dont_write_bytecode = ... # type: int + hash_randomization = ... # type: int + ignore_environment = ... # type: int + inspect = ... # type: int + interactive = ... # type: int + no_site = ... # type: int + no_user_site = ... # type: int + optimize = ... # type: int + py3k_warning = ... # type: int + tabcheck = ... # type: int + unicode = ... # type: int + verbose = ... # type: int + +class _float_info: + max = ... # type: float + max_exp = ... # type: int + max_10_exp = ... # type: int + min = ... # type: float + min_exp = ... # type: int + min_10_exp = ... # type: int + dig = ... # type: int + mant_dig = ... # type: int + epsilon = ... # type: float + radix = ... # type: int + rounds = ... # type: int + +class _version_info(Tuple[int, int, int, str, int]): + major = 0 + minor = 0 + micro = 0 + releaselevel = ... # type: str + serial = 0 + +_mercurial = ... # type: Tuple[str, str, str] +api_version = ... # type: int +argv = ... # type: List[str] +builtin_module_names = ... # type: Tuple[str, ...] +byteorder = ... # type: str +copyright = ... # type: str +dont_write_bytecode = ... # type: bool +exec_prefix = ... # type: str +executable = ... # type: str +flags = ... # type: _flags +float_repr_style = ... # type: str +hexversion = ... # type: int +long_info = ... # type: object +maxint = ... # type: int +maxsize = ... # type: int +maxunicode = ... # type: int +modules = ... # type: Dict[str, Any] +path = ... # type: List[str] +platform = ... # type: str +prefix = ... # type: str +py3kwarning = ... # type: bool +__stderr__ = ... # type: IO[str] +__stdin__ = ... # type: IO[str] +__stdout__ = ... # type: IO[str] +stderr = ... # type: IO[str] +stdin = ... # type: IO[str] +stdout = ... # type: IO[str] +subversion = ... # type: Tuple[str, str, str] +version = ... # type: str +warnoptions = ... # type: object +float_info = ... # type: _float_info +version_info = ... # type: _version_info +ps1 = ... # type: str +ps2 = ... # type: str +last_type = ... # type: type +last_value = ... # type: BaseException +last_traceback = ... # type: TracebackType +# TODO precise types +meta_path = ... # type: List[Any] +path_hooks = ... # type: List[Any] +path_importer_cache = ... # type: Dict[str, Any] +displayhook = ... # type: Optional[Callable[[int], None]] +excepthook = ... # type: Optional[Callable[[type, BaseException, TracebackType], None]] +exc_type = ... # type: Optional[type] +exc_value = ... # type: Union[BaseException, ClassType] +exc_traceback = ... # type: TracebackType + +class _WindowsVersionType: + major = ... # type: Any + minor = ... # type: Any + build = ... # type: Any + platform = ... # type: Any + service_pack = ... # type: Any + service_pack_major = ... # type: Any + service_pack_minor = ... # type: Any + suite_mask = ... # type: Any + product_type = ... # type: Any + +def getwindowsversion() -> _WindowsVersionType: ... + +def _clear_type_cache() -> None: ... +def _current_frames() -> Dict[int, FrameType]: ... +def _getframe(depth: int = ...) -> FrameType: ... +def call_tracing(fn: Any, args: Any) -> Any: ... +def __displayhook__(value: int) -> None: ... +def __excepthook__(type_: type, value: BaseException, traceback: TracebackType) -> None: ... +def exc_clear() -> None: + raise DeprecationWarning() +def exc_info() -> _OptExcInfo: ... + +# sys.exit() accepts an optional argument of anything printable +def exit(arg: Any = ...) -> NoReturn: + raise SystemExit() +def getcheckinterval() -> int: ... # deprecated +def getdefaultencoding() -> str: ... +def getdlopenflags() -> int: ... +def getfilesystemencoding() -> str: ... # In practice, never returns None +def getrefcount(arg: Any) -> int: ... +def getrecursionlimit() -> int: ... +def getsizeof(obj: object, default: int = ...) -> int: ... +def getprofile() -> Optional[Any]: ... +def gettrace() -> Optional[Any]: ... +def setcheckinterval(interval: int) -> None: ... # deprecated +def setdlopenflags(n: int) -> None: ... +def setdefaultencoding(encoding: Text) -> None: ... # only exists after reload(sys) +def setprofile(profilefunc: Any) -> None: ... # TODO type +def setrecursionlimit(limit: int) -> None: ... +def settrace(tracefunc: Any) -> None: ... # TODO type diff --git a/client/typeshed-fallback/stdlib/2/tempfile.pyi b/client/typeshed-fallback/stdlib/2/tempfile.pyi new file mode 100644 index 000000000..bad5b837a --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/tempfile.pyi @@ -0,0 +1,111 @@ +from typing import Any, AnyStr, IO, Iterable, Iterator, List, Optional, overload, Text, Tuple, Union +from thread import LockType +from random import Random + +TMP_MAX = ... # type: int +tempdir = ... # type: str +template = ... # type: str +_name_sequence = ... # type: Optional[_RandomNameSequence] + +class _RandomNameSequence: + characters: str = ... + mutex: LockType + @property + def rng(self) -> Random: ... + def __iter__(self) -> _RandomNameSequence: ... + def next(self) -> str: ... + # from os.path: + def normcase(self, path: AnyStr) -> AnyStr: ... + +class _TemporaryFileWrapper(IO[str]): + delete: bool + file: IO + name: Any + def __init__(self, file: IO, name: Any, delete: bool = ...) -> None: ... + def __del__(self) -> None: ... + def __enter__(self) -> _TemporaryFileWrapper: ... + def __exit__(self, exc, value, tb) -> bool: ... + def __getattr__(self, name: unicode) -> Any: ... + def close(self) -> None: ... + def unlink(self, path: unicode) -> None: ... + # These methods don't exist directly on this object, but + # are delegated to the underlying IO object through __getattr__. + # We need to add them here so that this class is concrete. + def __iter__(self) -> Iterator[str]: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def next(self) -> str: ... + def read(self, n: int = ...) -> str: ... + def readable(self) -> bool: ... + def readline(self, limit: int = ...) -> str: ... + def readlines(self, hint: int = ...) -> List[str]: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def writable(self) -> bool: ... + def write(self, s: Text) -> int: ... + def writelines(self, lines: Iterable[str]) -> None: ... + + +# TODO text files + +def TemporaryFile( + mode: Union[bytes, unicode] = ..., + bufsize: int = ..., + suffix: Union[bytes, unicode] = ..., + prefix: Union[bytes, unicode] = ..., + dir: Union[bytes, unicode] = ... +) -> _TemporaryFileWrapper: + ... + +def NamedTemporaryFile( + mode: Union[bytes, unicode] = ..., + bufsize: int = ..., + suffix: Union[bytes, unicode] = ..., + prefix: Union[bytes, unicode] = ..., + dir: Union[bytes, unicode] = ..., + delete: bool = ... +) -> _TemporaryFileWrapper: + ... + +def SpooledTemporaryFile( + max_size: int = ..., + mode: Union[bytes, unicode] = ..., + buffering: int = ..., + suffix: Union[bytes, unicode] = ..., + prefix: Union[bytes, unicode] = ..., + dir: Union[bytes, unicode] = ... +) -> _TemporaryFileWrapper: + ... + +class TemporaryDirectory: + name = ... # type: Any # Can be str or unicode + def __init__(self, + suffix: Union[bytes, unicode] = ..., + prefix: Union[bytes, unicode] = ..., + dir: Union[bytes, unicode] = ...) -> None: ... + def cleanup(self) -> None: ... + def __enter__(self) -> Any: ... # Can be str or unicode + def __exit__(self, type, value, traceback) -> bool: ... + +@overload +def mkstemp() -> Tuple[int, str]: ... +@overload +def mkstemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: Optional[AnyStr] = ..., + text: bool = ...) -> Tuple[int, AnyStr]: ... +@overload +def mkdtemp() -> str: ... +@overload +def mkdtemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: Optional[AnyStr] = ...) -> AnyStr: ... +@overload +def mktemp() -> str: ... +@overload +def mktemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: Optional[AnyStr] = ...) -> AnyStr: ... +def gettempdir() -> str: ... +def gettempprefix() -> str: ... + +def _candidate_tempdir_list() -> List[str]: ... +def _get_candidate_names() -> Optional[_RandomNameSequence]: ... +def _get_default_tempdir() -> str: ... diff --git a/client/typeshed-fallback/stdlib/2/textwrap.pyi b/client/typeshed-fallback/stdlib/2/textwrap.pyi new file mode 100644 index 000000000..60498a65a --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/textwrap.pyi @@ -0,0 +1,61 @@ +from typing import AnyStr, List, Dict, Pattern + +class TextWrapper(object): + width: int = ... + initial_indent: str = ... + subsequent_indent: str = ... + expand_tabs: bool = ... + replace_whitespace: bool = ... + fix_sentence_endings: bool = ... + drop_whitespace: bool = ... + break_long_words: bool = ... + break_on_hyphens: bool = ... + + # Attributes not present in documentation + sentence_end_re: Pattern[str] = ... + wordsep_re: Pattern[str] = ... + wordsep_simple_re: Pattern[str] = ... + whitespace_trans: str = ... + unicode_whitespace_trans: Dict[int, int] = ... + uspace: int = ... + x: int = ... + + def __init__( + self, + width: int = ..., + initial_indent: str = ..., + subsequent_indent: str = ..., + expand_tabs: bool = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + drop_whitespace: bool = ..., + break_on_hyphens: bool = ...) -> None: + ... + + def wrap(self, text: AnyStr) -> List[AnyStr]: ... + def fill(self, text: AnyStr) -> AnyStr: ... + +def wrap(text: AnyStr, + width: int = ..., + initial_indent: AnyStr = ..., + subsequent_indent: AnyStr = ..., + expand_tabs: bool = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + drop_whitespace: bool = ..., + break_on_hyphens: bool = ...) -> List[AnyStr]: ... + +def fill(text: AnyStr, + width: int = ..., + initial_indent: AnyStr = ..., + subsequent_indent: AnyStr = ..., + expand_tabs: bool = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + drop_whitespace: bool = ..., + break_on_hyphens: bool = ...) -> AnyStr: ... + +def dedent(text: AnyStr) -> AnyStr: ... diff --git a/client/typeshed-fallback/stdlib/2/thread.pyi b/client/typeshed-fallback/stdlib/2/thread.pyi new file mode 100644 index 000000000..eb4e6d6d3 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/thread.pyi @@ -0,0 +1,30 @@ +"""Stubs for the "thread" module.""" +from typing import Callable, Any + +def _count() -> int: ... + +class error(Exception): ... + +class LockType: + def acquire(self, waitflag: int = ...) -> bool: ... + def acquire_lock(self, waitflag: int = ...) -> bool: ... + def release(self) -> None: ... + def release_lock(self) -> None: ... + def locked(self) -> bool: ... + def locked_lock(self) -> bool: ... + def __enter__(self) -> LockType: ... + def __exit__(self, typ: Any, value: Any, traceback: Any) -> None: ... + +class _local(object): ... +class _localdummy(object): ... + +def start_new(function: Callable[..., Any], args: Any, kwargs: Any = ...) -> int: ... +def start_new_thread(function: Callable[..., Any], args: Any, kwargs: Any = ...) -> int: ... +def interrupt_main() -> None: ... +def exit() -> None: + raise SystemExit() +def exit_thread() -> Any: + raise SystemExit() +def allocate_lock() -> LockType: ... +def get_ident() -> int: ... +def stack_size(size: int = ...) -> int: ... diff --git a/client/typeshed-fallback/stdlib/2/toaiff.pyi b/client/typeshed-fallback/stdlib/2/toaiff.pyi new file mode 100644 index 000000000..77334c7f5 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/toaiff.pyi @@ -0,0 +1,16 @@ +# Stubs for toaiff (Python 2) + +# Source: https://hg.python.org/cpython/file/2.7/Lib/toaiff.py +from pipes import Template +from typing import Dict, List + + +__all__: List[str] +table: Dict[str, Template] +t: Template +uncompress: Template + +class error(Exception): ... + +def toaiff(filename: str) -> str: ... +def _toaiff(filename: str, temps: List[str]) -> str: ... diff --git a/client/typeshed-fallback/stdlib/2/tokenize.pyi b/client/typeshed-fallback/stdlib/2/tokenize.pyi new file mode 100644 index 000000000..c7ee7dba7 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/tokenize.pyi @@ -0,0 +1,136 @@ +# Automatically generated by pytype, manually fixed up. May still contain errors. + +from typing import Any, Callable, Dict, Generator, Iterator, List, Tuple, Union, Iterable + +__author__ = ... # type: str +__credits__ = ... # type: str + +AMPER = ... # type: int +AMPEREQUAL = ... # type: int +AT = ... # type: int +BACKQUOTE = ... # type: int +Binnumber = ... # type: str +Bracket = ... # type: str +CIRCUMFLEX = ... # type: int +CIRCUMFLEXEQUAL = ... # type: int +COLON = ... # type: int +COMMA = ... # type: int +COMMENT = ... # type: int +Comment = ... # type: str +ContStr = ... # type: str +DEDENT = ... # type: int +DOT = ... # type: int +DOUBLESLASH = ... # type: int +DOUBLESLASHEQUAL = ... # type: int +DOUBLESTAR = ... # type: int +DOUBLESTAREQUAL = ... # type: int +Decnumber = ... # type: str +Double = ... # type: str +Double3 = ... # type: str +ENDMARKER = ... # type: int +EQEQUAL = ... # type: int +EQUAL = ... # type: int +ERRORTOKEN = ... # type: int +Expfloat = ... # type: str +Exponent = ... # type: str +Floatnumber = ... # type: str +Funny = ... # type: str +GREATER = ... # type: int +GREATEREQUAL = ... # type: int +Hexnumber = ... # type: str +INDENT = ... # type: int + +def ISEOF(x: int) -> bool: ... +def ISNONTERMINAL(x: int) -> bool: ... +def ISTERMINAL(x: int) -> bool: ... + +Ignore = ... # type: str +Imagnumber = ... # type: str +Intnumber = ... # type: str +LBRACE = ... # type: int +LEFTSHIFT = ... # type: int +LEFTSHIFTEQUAL = ... # type: int +LESS = ... # type: int +LESSEQUAL = ... # type: int +LPAR = ... # type: int +LSQB = ... # type: int +MINEQUAL = ... # type: int +MINUS = ... # type: int +NAME = ... # type: int +NEWLINE = ... # type: int +NL = ... # type: int +NOTEQUAL = ... # type: int +NT_OFFSET = ... # type: int +NUMBER = ... # type: int +N_TOKENS = ... # type: int +Name = ... # type: str +Number = ... # type: str +OP = ... # type: int +Octnumber = ... # type: str +Operator = ... # type: str +PERCENT = ... # type: int +PERCENTEQUAL = ... # type: int +PLUS = ... # type: int +PLUSEQUAL = ... # type: int +PlainToken = ... # type: str +Pointfloat = ... # type: str +PseudoExtras = ... # type: str +PseudoToken = ... # type: str +RBRACE = ... # type: int +RIGHTSHIFT = ... # type: int +RIGHTSHIFTEQUAL = ... # type: int +RPAR = ... # type: int +RSQB = ... # type: int +SEMI = ... # type: int +SLASH = ... # type: int +SLASHEQUAL = ... # type: int +STAR = ... # type: int +STAREQUAL = ... # type: int +STRING = ... # type: int +Single = ... # type: str +Single3 = ... # type: str +Special = ... # type: str +String = ... # type: str +TILDE = ... # type: int +Token = ... # type: str +Triple = ... # type: str +VBAR = ... # type: int +VBAREQUAL = ... # type: int +Whitespace = ... # type: str +chain = ... # type: type +double3prog = ... # type: type +endprogs = ... # type: Dict[str, Any] +pseudoprog = ... # type: type +single3prog = ... # type: type +single_quoted = ... # type: Dict[str, str] +t = ... # type: str +tabsize = ... # type: int +tok_name = ... # type: Dict[int, str] +tokenprog = ... # type: type +triple_quoted = ... # type: Dict[str, str] +x = ... # type: str + +_Pos = Tuple[int, int] +_TokenType = Tuple[int, str, _Pos, _Pos, str] + +def any(*args, **kwargs) -> str: ... +def generate_tokens(readline: Callable[[], str]) -> Generator[_TokenType, None, None]: ... +def group(*args: str) -> str: ... +def maybe(*args: str) -> str: ... +def printtoken(type: int, token: str, srow_scol: _Pos, erow_ecol: _Pos, line: str) -> None: ... +def tokenize(readline: Callable[[], str], tokeneater: Callable[[Tuple[int, str, _Pos, _Pos, str]], None]) -> None: ... +def tokenize_loop(readline: Callable[[], str], tokeneater: Callable[[Tuple[int, str, _Pos, _Pos, str]], None]) -> None: ... +def untokenize(iterable: Iterable[_TokenType]) -> str: ... + +class StopTokenizing(Exception): ... + +class TokenError(Exception): ... + +class Untokenizer: + prev_col = ... # type: int + prev_row = ... # type: int + tokens = ... # type: List[str] + def __init__(self) -> None: ... + def add_whitespace(self, _Pos) -> None: ... + def compat(self, token: Tuple[int, Any], iterable: Iterator[_TokenType]) -> None: ... + def untokenize(self, iterable: Iterable[_TokenType]) -> str: ... diff --git a/client/typeshed-fallback/stdlib/2/types.pyi b/client/typeshed-fallback/stdlib/2/types.pyi new file mode 100644 index 000000000..f18aed290 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/types.pyi @@ -0,0 +1,167 @@ +# Stubs for types +# Note, all classes "defined" here require special handling. + +from typing import ( + Any, Callable, Dict, Iterable, Iterator, List, Optional, + Tuple, Type, TypeVar, Union, overload, +) + +_T = TypeVar('_T') + +class NoneType: ... +TypeType = type +ObjectType = object + +IntType = int +LongType = int # Really long, but can't reference that due to a mypy import cycle +FloatType = float +BooleanType = bool +ComplexType = complex +StringType = str +UnicodeType = unicode +StringTypes = ... # type: Tuple[Type[StringType], Type[UnicodeType]] +BufferType = buffer +TupleType = tuple +ListType = list +DictType = dict +DictionaryType = dict + +class _Cell: + cell_contents = ... # type: Any + +class FunctionType: + func_closure = ... # type: Optional[Tuple[_Cell, ...]] + func_code = ... # type: CodeType + func_defaults = ... # type: Optional[Tuple[Any, ...]] + func_dict = ... # type: Dict[str, Any] + func_doc = ... # type: Optional[str] + func_globals = ... # type: Dict[str, Any] + func_name = ... # type: str + __closure__ = func_closure + __code__ = func_code + __defaults__ = func_defaults + __dict__ = func_dict + __globals__ = func_globals + __name__ = func_name + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __get__(self, obj: Optional[object], type: Optional[type]) -> UnboundMethodType: ... + +LambdaType = FunctionType + +class CodeType: + co_argcount = ... # type: int + co_cellvars = ... # type: Tuple[str, ...] + co_code = ... # type: str + co_consts = ... # type: Tuple[Any, ...] + co_filename = ... # type: str + co_firstlineno = ... # type: int + co_flags = ... # type: int + co_freevars = ... # type: Tuple[str, ...] + co_lnotab = ... # type: str + co_name = ... # type: str + co_names = ... # type: Tuple[str, ...] + co_nlocals = ... # type: int + co_stacksize = ... # type: int + co_varnames = ... # type: Tuple[str, ...] + +class GeneratorType: + gi_code = ... # type: CodeType + gi_frame = ... # type: FrameType + gi_running = ... # type: int + def __iter__(self) -> GeneratorType: ... + def close(self) -> None: ... + def next(self) -> Any: ... + def send(self, arg: Any) -> Any: ... + @overload + def throw(self, val: BaseException) -> Any: ... + @overload + def throw(self, typ: type, val: BaseException = ..., tb: TracebackType = ...) -> Any: ... + +class ClassType: ... +class UnboundMethodType: + im_class = ... # type: type + im_func = ... # type: FunctionType + im_self = ... # type: object + __name__ = ... # type: str + __func__ = im_func + __self__ = im_self + def __init__(self, func: Callable, obj: object) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + +class InstanceType(object): ... + +MethodType = UnboundMethodType + +class BuiltinFunctionType: + __self__ = ... # type: Optional[object] + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... +BuiltinMethodType = BuiltinFunctionType + +class ModuleType: + __doc__ = ... # type: Optional[str] + __file__ = ... # type: Optional[str] + __name__ = ... # type: str + __package__ = ... # type: Optional[str] + __path__ = ... # type: Optional[Iterable[str]] + __dict__ = ... # type: Dict[str, Any] + def __init__(self, name: str, doc: Optional[str] = ...) -> None: ... +FileType = file +XRangeType = xrange + +class TracebackType: + tb_frame = ... # type: FrameType + tb_lasti = ... # type: int + tb_lineno = ... # type: int + tb_next = ... # type: TracebackType + +class FrameType: + f_back = ... # type: FrameType + f_builtins = ... # type: Dict[str, Any] + f_code = ... # type: CodeType + f_exc_type = ... # type: None + f_exc_value = ... # type: None + f_exc_traceback = ... # type: None + f_globals = ... # type: Dict[str, Any] + f_lasti = ... # type: int + f_lineno = ... # type: int + f_locals = ... # type: Dict[str, Any] + f_restricted = ... # type: bool + f_trace = ... # type: Callable[[], None] + + def clear(self) -> None: ... + +SliceType = slice +class EllipsisType: ... + +class DictProxyType: + # TODO is it possible to have non-string keys? + # no __init__ + def copy(self) -> dict: ... + def get(self, key: str, default: _T = ...) -> Union[Any, _T]: ... + def has_key(self, key: str) -> bool: ... + def items(self) -> List[Tuple[str, Any]]: ... + def iteritems(self) -> Iterator[Tuple[str, Any]]: ... + def iterkeys(self) -> Iterator[str]: ... + def itervalues(self) -> Iterator[Any]: ... + def keys(self) -> List[str]: ... + def values(self) -> List[Any]: ... + def __contains__(self, key: str) -> bool: ... + def __getitem__(self, key: str) -> Any: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + +class NotImplementedType: ... + +class GetSetDescriptorType: + __name__ = ... # type: str + __objclass__ = ... # type: type + def __get__(self, obj: Any, type: type = ...) -> Any: ... + def __set__(self, obj: Any) -> None: ... + def __delete__(self, obj: Any) -> None: ... +# Same type on Jython, different on CPython and PyPy, unknown on IronPython. +class MemberDescriptorType: + __name__ = ... # type: str + __objclass__ = ... # type: type + def __get__(self, obj: Any, type: type = ...) -> Any: ... + def __set__(self, obj: Any) -> None: ... + def __delete__(self, obj: Any) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2/typing.pyi b/client/typeshed-fallback/stdlib/2/typing.pyi new file mode 100644 index 000000000..7049d10bb --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/typing.pyi @@ -0,0 +1,469 @@ +# Stubs for typing (Python 2.7) + +from abc import abstractmethod, ABCMeta +from types import CodeType, FrameType, TracebackType +import collections # Needed by aliases like DefaultDict, see mypy issue 2986 + +# Definitions of special type checking related constructs. Their definitions +# are not used, so their value does not matter. + +overload = object() +Any = object() +TypeVar = object() +_promote = object() +no_type_check = object() + +class _SpecialForm(object): + def __getitem__(self, typeargs: Any) -> object: ... + +Tuple: _SpecialForm = ... +Generic: _SpecialForm = ... +Protocol: _SpecialForm = ... +Callable: _SpecialForm = ... +Type: _SpecialForm = ... +ClassVar: _SpecialForm = ... + +class GenericMeta(type): ... + +# Return type that indicates a function does not return. +# This type is equivalent to the None type, but the no-op Union is necessary to +# distinguish the None type from the None value. +NoReturn = Union[None] + +# Type aliases and type constructors + +class TypeAlias: + # Class for defining generic aliases for library types. + def __init__(self, target_type: type) -> None: ... + def __getitem__(self, typeargs: Any) -> Any: ... + +Union = TypeAlias(object) +Optional = TypeAlias(object) +List = TypeAlias(object) +Dict = TypeAlias(object) +DefaultDict = TypeAlias(object) +Set = TypeAlias(object) +FrozenSet = TypeAlias(object) +Counter = TypeAlias(object) +Deque = TypeAlias(object) + +# Predefined type variables. +AnyStr = TypeVar('AnyStr', str, unicode) + +# Abstract base classes. + +# These type variables are used by the container types. +_T = TypeVar('_T') +_S = TypeVar('_S') +_KT = TypeVar('_KT') # Key type. +_VT = TypeVar('_VT') # Value type. +_T_co = TypeVar('_T_co', covariant=True) # Any type covariant containers. +_V_co = TypeVar('_V_co', covariant=True) # Any type covariant containers. +_KT_co = TypeVar('_KT_co', covariant=True) # Key type covariant containers. +_VT_co = TypeVar('_VT_co', covariant=True) # Value type covariant containers. +_T_contra = TypeVar('_T_contra', contravariant=True) # Ditto contravariant. +_TC = TypeVar('_TC', bound=Type[object]) + +def runtime(cls: _TC) -> _TC: ... + +@runtime +class SupportsInt(Protocol, metaclass=ABCMeta): + @abstractmethod + def __int__(self) -> int: ... + +@runtime +class SupportsFloat(Protocol, metaclass=ABCMeta): + @abstractmethod + def __float__(self) -> float: ... + +@runtime +class SupportsComplex(Protocol, metaclass=ABCMeta): + @abstractmethod + def __complex__(self) -> complex: ... + +@runtime +class SupportsAbs(Protocol[_T_co]): + @abstractmethod + def __abs__(self) -> _T_co: ... + +@runtime +class SupportsRound(Protocol[_T_co]): + @abstractmethod + def __round__(self, ndigits: int = ...) -> _T_co: ... + +@runtime +class Reversible(Protocol[_T_co]): + @abstractmethod + def __reversed__(self) -> Iterator[_T_co]: ... + +@runtime +class Sized(Protocol, metaclass=ABCMeta): + @abstractmethod + def __len__(self) -> int: ... + +@runtime +class Hashable(Protocol, metaclass=ABCMeta): + # TODO: This is special, in that a subclass of a hashable class may not be hashable + # (for example, list vs. object). It's not obvious how to represent this. This class + # is currently mostly useless for static checking. + @abstractmethod + def __hash__(self) -> int: ... + +@runtime +class Iterable(Protocol[_T_co]): + @abstractmethod + def __iter__(self) -> Iterator[_T_co]: ... + +@runtime +class Iterator(Iterable[_T_co], Protocol[_T_co]): + @abstractmethod + def next(self) -> _T_co: ... + def __iter__(self) -> Iterator[_T_co]: ... + +class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]): + @abstractmethod + def next(self) -> _T_co: ... + + @abstractmethod + def send(self, value: _T_contra) -> _T_co: ... + + @abstractmethod + def throw(self, typ: Type[BaseException], val: Optional[BaseException] = ..., + tb: TracebackType = ...) -> _T_co: ... + @abstractmethod + def close(self) -> None: ... + @property + def gi_code(self) -> CodeType: ... + @property + def gi_frame(self) -> FrameType: ... + @property + def gi_running(self) -> bool: ... + +@runtime +class Container(Protocol[_T_co]): + @abstractmethod + def __contains__(self, x: object) -> bool: ... + +class Sequence(Iterable[_T_co], Container[_T_co], Reversible[_T_co], Generic[_T_co]): + @overload + @abstractmethod + def __getitem__(self, i: int) -> _T_co: ... + @overload + @abstractmethod + def __getitem__(self, s: slice) -> Sequence[_T_co]: ... + # Mixin methods + def index(self, x: Any) -> int: ... + def count(self, x: Any) -> int: ... + def __contains__(self, x: object) -> bool: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __reversed__(self) -> Iterator[_T_co]: ... + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... + +class MutableSequence(Sequence[_T], Generic[_T]): + @abstractmethod + def insert(self, index: int, object: _T) -> None: ... + @overload + @abstractmethod + def __getitem__(self, i: int) -> _T: ... + @overload + @abstractmethod + def __getitem__(self, s: slice) -> MutableSequence[_T]: ... + @overload + @abstractmethod + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + @abstractmethod + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + @overload + @abstractmethod + def __delitem__(self, i: int) -> None: ... + @overload + @abstractmethod + def __delitem__(self, i: slice) -> None: ... + # Mixin methods + def append(self, object: _T) -> None: ... + def extend(self, iterable: Iterable[_T]) -> None: ... + def reverse(self) -> None: ... + def pop(self, index: int = ...) -> _T: ... + def remove(self, object: _T) -> None: ... + def __iadd__(self, x: Iterable[_T]) -> MutableSequence[_T]: ... + +class AbstractSet(Iterable[_T_co], Container[_T_co], Generic[_T_co]): + @abstractmethod + def __contains__(self, x: object) -> bool: ... + # Mixin methods + def __le__(self, s: AbstractSet[Any]) -> bool: ... + def __lt__(self, s: AbstractSet[Any]) -> bool: ... + def __gt__(self, s: AbstractSet[Any]) -> bool: ... + def __ge__(self, s: AbstractSet[Any]) -> bool: ... + def __and__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... + def __or__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ... + def __sub__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... + def __xor__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ... + # TODO: argument can be any container? + def isdisjoint(self, s: AbstractSet[Any]) -> bool: ... + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... + + +class MutableSet(AbstractSet[_T], Generic[_T]): + @abstractmethod + def add(self, x: _T) -> None: ... + @abstractmethod + def discard(self, x: _T) -> None: ... + # Mixin methods + def clear(self) -> None: ... + def pop(self) -> _T: ... + def remove(self, element: _T) -> None: ... + def __ior__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: ... + def __iand__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... + def __ixor__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: ... + def __isub__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... + +class MappingView(object): + def __len__(self) -> int: ... + +class ItemsView(MappingView, AbstractSet[Tuple[_KT_co, _VT_co]], Generic[_KT_co, _VT_co]): + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[Tuple[_KT_co, _VT_co]]: ... + +class KeysView(MappingView, AbstractSet[_KT_co], Generic[_KT_co]): + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_KT_co]: ... + +class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]): + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_VT_co]: ... + +@runtime +class ContextManager(Protocol[_T_co]): + def __enter__(self) -> _T_co: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType]) -> Optional[bool]: ... + +class Mapping(Iterable[_KT], Container[_KT], Generic[_KT, _VT_co]): + # TODO: We wish the key type could also be covariant, but that doesn't work, + # see discussion in https: //github.com/python/typing/pull/273. + @abstractmethod + def __getitem__(self, k: _KT) -> _VT_co: + ... + # Mixin methods + @overload + def get(self, k: _KT) -> Optional[_VT_co]: ... + @overload + def get(self, k: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]: ... + def keys(self) -> list[_KT]: ... + def values(self) -> list[_VT_co]: ... + def items(self) -> list[Tuple[_KT, _VT_co]]: ... + def iterkeys(self) -> Iterator[_KT]: ... + def itervalues(self) -> Iterator[_VT_co]: ... + def iteritems(self) -> Iterator[Tuple[_KT, _VT_co]]: ... + def __contains__(self, o: object) -> bool: ... + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... + +class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]): + @abstractmethod + def __setitem__(self, k: _KT, v: _VT) -> None: ... + @abstractmethod + def __delitem__(self, v: _KT) -> None: ... + + def clear(self) -> None: ... + @overload + def pop(self, k: _KT) -> _VT: ... + @overload + def pop(self, k: _KT, default: Union[_VT, _T] = ...) -> Union[_VT, _T]: ... + def popitem(self) -> Tuple[_KT, _VT]: ... + def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ... + @overload + def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + @overload + def update(self, **kwargs: _VT) -> None: ... + +Text = unicode + +TYPE_CHECKING = True + +class IO(Iterator[AnyStr], Generic[AnyStr]): + # TODO detach + # TODO use abstract properties + @property + def mode(self) -> str: ... + @property + def name(self) -> str: ... + @abstractmethod + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + @abstractmethod + def fileno(self) -> int: ... + @abstractmethod + def flush(self) -> None: ... + @abstractmethod + def isatty(self) -> bool: ... + # TODO what if n is None? + @abstractmethod + def read(self, n: int = ...) -> AnyStr: ... + @abstractmethod + def readable(self) -> bool: ... + @abstractmethod + def readline(self, limit: int = ...) -> AnyStr: ... + @abstractmethod + def readlines(self, hint: int = ...) -> list[AnyStr]: ... + @abstractmethod + def seek(self, offset: int, whence: int = ...) -> int: ... + @abstractmethod + def seekable(self) -> bool: ... + @abstractmethod + def tell(self) -> int: ... + @abstractmethod + def truncate(self, size: Optional[int] = ...) -> int: ... + @abstractmethod + def writable(self) -> bool: ... + # TODO buffer objects + @abstractmethod + def write(self, s: AnyStr) -> int: ... + @abstractmethod + def writelines(self, lines: Iterable[AnyStr]) -> None: ... + + @abstractmethod + def next(self) -> AnyStr: ... + @abstractmethod + def __iter__(self) -> Iterator[AnyStr]: ... + @abstractmethod + def __enter__(self) -> IO[AnyStr]: ... + @abstractmethod + def __exit__(self, t: Optional[Type[BaseException]], value: Optional[BaseException], + traceback: Optional[TracebackType]) -> bool: ... + +class BinaryIO(IO[str]): + # TODO readinto + # TODO read1? + # TODO peek? + @abstractmethod + def __enter__(self) -> BinaryIO: ... + +class TextIO(IO[unicode]): + # TODO use abstractproperty + @property + def buffer(self) -> BinaryIO: ... + @property + def encoding(self) -> str: ... + @property + def errors(self) -> Optional[str]: ... + @property + def line_buffering(self) -> bool: ... + @property + def newlines(self) -> Any: ... # None, str or tuple + @abstractmethod + def __enter__(self) -> TextIO: ... + +class ByteString(Sequence[int], metaclass=ABCMeta): ... + +class Match(Generic[AnyStr]): + pos: int + endpos: int + lastindex: Optional[int] + string: AnyStr + + # The regular expression object whose match() or search() method produced + # this match instance. This should not be Pattern[AnyStr] because the type + # of the pattern is independent of the type of the matched string in + # Python 2. Strictly speaking Match should be generic over AnyStr twice: + # once for the type of the pattern and once for the type of the matched + # string. + re: Pattern[Any] + # Can be None if there are no groups or if the last group was unnamed; + # otherwise matches the type of the pattern. + lastgroup: Optional[Any] + + def expand(self, template: Union[str, Text]) -> Any: ... + + @overload + def group(self, group1: int = ...) -> AnyStr: ... + @overload + def group(self, group1: str) -> AnyStr: ... + @overload + def group(self, group1: int, group2: int, + *groups: int) -> Tuple[AnyStr, ...]: ... + @overload + def group(self, group1: str, group2: str, + *groups: str) -> Tuple[AnyStr, ...]: ... + + def groups(self, default: AnyStr = ...) -> Tuple[AnyStr, ...]: ... + def groupdict(self, default: AnyStr = ...) -> Dict[str, AnyStr]: ... + def start(self, group: Union[int, str] = ...) -> int: ... + def end(self, group: Union[int, str] = ...) -> int: ... + def span(self, group: Union[int, str] = ...) -> Tuple[int, int]: ... + +# We need a second TypeVar with the same definition as AnyStr, because +# Pattern is generic over AnyStr (determining the type of its .pattern +# attribute), but at the same time its methods take either bytes or +# Text and return the same type, regardless of the type of the pattern. +_AnyStr2 = TypeVar('_AnyStr2', bytes, Text) + +class Pattern(Generic[AnyStr]): + flags: int + groupindex: Dict[AnyStr, int] + groups: int + pattern: AnyStr + + def search(self, string: _AnyStr2, pos: int = ..., + endpos: int = ...) -> Optional[Match[_AnyStr2]]: ... + def match(self, string: _AnyStr2, pos: int = ..., + endpos: int = ...) -> Optional[Match[_AnyStr2]]: ... + def split(self, string: _AnyStr2, maxsplit: int = ...) -> List[_AnyStr2]: ... + # Returns either a list of _AnyStr2 or a list of tuples, depending on + # whether there are groups in the pattern. + def findall(self, string: Union[bytes, Text], pos: int = ..., + endpos: int = ...) -> List[Any]: ... + def finditer(self, string: _AnyStr2, pos: int = ..., + endpos: int = ...) -> Iterator[Match[_AnyStr2]]: ... + + @overload + def sub(self, repl: _AnyStr2, string: _AnyStr2, + count: int = ...) -> _AnyStr2: ... + @overload + def sub(self, repl: Callable[[Match[_AnyStr2]], _AnyStr2], string: _AnyStr2, + count: int = ...) -> _AnyStr2: ... + + @overload + def subn(self, repl: _AnyStr2, string: _AnyStr2, + count: int = ...) -> Tuple[_AnyStr2, int]: ... + @overload + def subn(self, repl: Callable[[Match[_AnyStr2]], _AnyStr2], string: _AnyStr2, + count: int = ...) -> Tuple[_AnyStr2, int]: ... + +# Functions + +def get_type_hints(obj: Callable, globalns: Optional[dict[Text, Any]] = ..., + localns: Optional[dict[Text, Any]] = ...) -> None: ... + +@overload +def cast(tp: Type[_T], obj: Any) -> _T: ... +@overload +def cast(tp: str, obj: Any) -> Any: ... + +# Type constructors + +# NamedTuple is special-cased in the type checker +class NamedTuple(tuple): + _fields = ... # type: Tuple[str, ...] + + def __init__(self, typename: Text, fields: Iterable[Tuple[Text, Any]] = ..., *, + verbose: bool = ..., rename: bool = ..., **kwargs: Any) -> None: ... + + @classmethod + def _make(cls: Type[_T], iterable: Iterable[Any]) -> _T: ... + + def _asdict(self) -> dict: ... + def _replace(self: _T, **kwargs: Any) -> _T: ... + +def NewType(name: str, tp: Type[_T]) -> Type[_T]: ... diff --git a/client/typeshed-fallback/stdlib/2/unittest.pyi b/client/typeshed-fallback/stdlib/2/unittest.pyi new file mode 100644 index 000000000..b0b39810d --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/unittest.pyi @@ -0,0 +1,250 @@ +# Stubs for unittest + +# Based on http://docs.python.org/2.7/library/unittest.html + +from typing import (Any, Callable, Dict, FrozenSet, Iterable, Iterator, + List, NoReturn, Optional, overload, Pattern, Sequence, Set, + Text, TextIO, Tuple, Type, TypeVar, Union) +from abc import abstractmethod, ABCMeta +import types + +_T = TypeVar('_T') +_FT = TypeVar('_FT') + +_ExceptionType = Union[Type[BaseException], Tuple[Type[BaseException], ...]] +_Regexp = Union[Text, Pattern[Text]] + +class Testable(metaclass=ABCMeta): + @abstractmethod + def run(self, result: TestResult) -> None: ... + @abstractmethod + def debug(self) -> None: ... + @abstractmethod + def countTestCases(self) -> int: ... + +# TODO ABC for test runners? + +class TestResult: + errors = ... # type: List[Tuple[Testable, str]] + failures = ... # type: List[Tuple[Testable, str]] + skipped = ... # type: List[Tuple[Testable, str]] + expectedFailures = ... # type: List[Tuple[Testable, str]] + unexpectedSuccesses = ... # type: List[Testable] + shouldStop = ... # type: bool + testsRun = ... # type: int + buffer = ... # type: bool + failfast = ... # type: bool + + def wasSuccessful(self) -> bool: ... + def stop(self) -> None: ... + def startTest(self, test: Testable) -> None: ... + def stopTest(self, test: Testable) -> None: ... + def startTestRun(self) -> None: ... + def stopTestRun(self) -> None: ... + def addError(self, test: Testable, err: Tuple[type, Any, Any]) -> None: ... # TODO + def addFailure(self, test: Testable, err: Tuple[type, Any, Any]) -> None: ... # TODO + def addSuccess(self, test: Testable) -> None: ... + def addSkip(self, test: Testable, reason: str) -> None: ... + def addExpectedFailure(self, test: Testable, err: str) -> None: ... + def addUnexpectedSuccess(self, test: Testable) -> None: ... + +class _AssertRaisesBaseContext: + expected = ... # type: Any + failureException = ... # type: Type[BaseException] + obj_name = ... # type: str + expected_regex = ... # type: Pattern[str] + +class _AssertRaisesContext(_AssertRaisesBaseContext): + exception = ... # type: Any # TODO precise type + def __enter__(self) -> _AssertRaisesContext: ... + def __exit__(self, exc_type, exc_value, tb) -> bool: ... + +class TestCase(Testable): + failureException = ... # type: Type[BaseException] + longMessage = ... # type: bool + maxDiff = ... # type: Optional[int] + # undocumented + _testMethodName = ... # type: str + def __init__(self, methodName: str = ...) -> None: ... + def setUp(self) -> None: ... + def tearDown(self) -> None: ... + @classmethod + def setUpClass(cls) -> None: ... + @classmethod + def tearDownClass(cls) -> None: ... + def run(self, result: TestResult = ...) -> None: ... + def debug(self) -> None: ... + def assert_(self, expr: Any, msg: object = ...) -> None: ... + def failUnless(self, expr: Any, msg: object = ...) -> None: ... + def assertTrue(self, expr: Any, msg: object = ...) -> None: ... + def assertEqual(self, first: Any, second: Any, + msg: object = ...) -> None: ... + def assertEquals(self, first: Any, second: Any, + msg: object = ...) -> None: ... + def failUnlessEqual(self, first: Any, second: Any, + msg: object = ...) -> None: ... + def assertNotEqual(self, first: Any, second: Any, + msg: object = ...) -> None: ... + def assertNotEquals(self, first: Any, second: Any, + msg: object = ...) -> None: ... + def failIfEqual(self, first: Any, second: Any, + msg: object = ...) -> None: ... + def assertAlmostEqual(self, first: float, second: float, places: int = ..., + msg: object = ..., + delta: float = ...) -> None: ... + def assertAlmostEquals(self, first: float, second: float, places: int = ..., + msg: object = ..., + delta: float = ...) -> None: ... + def failUnlessAlmostEqual(self, first: float, second: float, places: int = ..., + msg: object = ...) -> None: ... + def assertNotAlmostEqual(self, first: float, second: float, places: int = ..., + msg: object = ..., + delta: float = ...) -> None: ... + def assertNotAlmostEquals(self, first: float, second: float, places: int = ..., + msg: object = ..., + delta: float = ...) -> None: ... + def failIfAlmostEqual(self, first: float, second: float, places: int = ..., + msg: object = ..., + delta: float = ...) -> None: ... + def assertGreater(self, first: Any, second: Any, + msg: object = ...) -> None: ... + def assertGreaterEqual(self, first: Any, second: Any, + msg: object = ...) -> None: ... + def assertMultiLineEqual(self, first: str, second: str, + msg: object = ...) -> None: ... + def assertSequenceEqual(self, first: Sequence[Any], second: Sequence[Any], + msg: object = ..., seq_type: type = ...) -> None: ... + def assertListEqual(self, first: List[Any], second: List[Any], + msg: object = ...) -> None: ... + def assertTupleEqual(self, first: Tuple[Any, ...], second: Tuple[Any, ...], + msg: object = ...) -> None: ... + def assertSetEqual(self, first: Union[Set[Any], FrozenSet[Any]], + second: Union[Set[Any], FrozenSet[Any]], msg: object = ...) -> None: ... + def assertDictEqual(self, first: Dict[Any, Any], second: Dict[Any, Any], + msg: object = ...) -> None: ... + def assertLess(self, first: Any, second: Any, + msg: object = ...) -> None: ... + def assertLessEqual(self, first: Any, second: Any, + msg: object = ...) -> None: ... + @overload + def assertRaises(self, exception: _ExceptionType, callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + @overload + def assertRaises(self, exception: _ExceptionType) -> _AssertRaisesContext: ... + @overload + def assertRaisesRegexp(self, exception: _ExceptionType, regexp: _Regexp, callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + @overload + def assertRaisesRegexp(self, exception: _ExceptionType, regexp: _Regexp) -> _AssertRaisesContext: ... + def assertRegexpMatches(self, text: Text, regexp: _Regexp, msg: object = ...) -> None: ... + def assertNotRegexpMatches(self, text: Text, regexp: _Regexp, msg: object = ...) -> None: ... + def assertItemsEqual(self, first: Iterable[Any], second: Iterable[Any], msg: object = ...) -> None: ... + def assertDictContainsSubset(self, expected: Dict[Any, Any], actual: Dict[Any, Any], msg: object = ...) -> None: ... + def addTypeEqualityFunc(self, typeobj: type, function: Callable[..., None]) -> None: ... + @overload + def failUnlessRaises(self, exception: _ExceptionType, callable: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + @overload + def failUnlessRaises(self, exception: _ExceptionType) -> _AssertRaisesContext: ... + def failIf(self, expr: Any, msg: object = ...) -> None: ... + def assertFalse(self, expr: Any, msg: object = ...) -> None: ... + def assertIs(self, first: object, second: object, + msg: object = ...) -> None: ... + def assertIsNot(self, first: object, second: object, + msg: object = ...) -> None: ... + def assertIsNone(self, expr: Any, msg: object = ...) -> None: ... + def assertIsNotNone(self, expr: Any, msg: object = ...) -> None: ... + def assertIn(self, first: _T, second: Iterable[_T], + msg: object = ...) -> None: ... + def assertNotIn(self, first: _T, second: Iterable[_T], + msg: object = ...) -> None: ... + def assertIsInstance(self, obj: Any, cls: Union[type, Tuple[type, ...]], + msg: object = ...) -> None: ... + def assertNotIsInstance(self, obj: Any, cls: Union[type, Tuple[type, ...]], + msg: object = ...) -> None: ... + def fail(self, msg: object = ...) -> NoReturn: ... + def countTestCases(self) -> int: ... + def defaultTestResult(self) -> TestResult: ... + def id(self) -> str: ... + def shortDescription(self) -> str: ... # May return None + def addCleanup(self, function: Any, *args: Any, **kwargs: Any) -> None: ... + def doCleanups(self) -> bool: ... + def skipTest(self, reason: Any) -> None: ... + def _formatMessage(self, msg: Optional[Text], standardMsg: Text) -> str: ... # undocumented + def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: ... # undocumented + +class FunctionTestCase(Testable): + def __init__(self, testFunc: Callable[[], None], + setUp: Optional[Callable[[], None]] = ..., + tearDown: Optional[Callable[[], None]] = ..., + description: Optional[str] = ...) -> None: ... + def run(self, result: TestResult) -> None: ... + def debug(self) -> None: ... + def countTestCases(self) -> int: ... + +class TestSuite(Testable): + def __init__(self, tests: Iterable[Testable] = ...) -> None: ... + def addTest(self, test: Testable) -> None: ... + def addTests(self, tests: Iterable[Testable]) -> None: ... + def run(self, result: TestResult) -> None: ... + def debug(self) -> None: ... + def countTestCases(self) -> int: ... + def __iter__(self) -> Iterator[Testable]: ... + +class TestLoader: + testMethodPrefix = ... # type: str + sortTestMethodsUsing = ... # type: Optional[Callable[[str, str], int]] + suiteClass = ... # type: Callable[[List[TestCase]], TestSuite] + def loadTestsFromTestCase(self, + testCaseClass: Type[TestCase]) -> TestSuite: ... + def loadTestsFromModule(self, module: types.ModuleType = ..., + use_load_tests: bool = ...) -> TestSuite: ... + def loadTestsFromName(self, name: str = ..., + module: Optional[types.ModuleType] = ...) -> TestSuite: ... + def loadTestsFromNames(self, names: List[str] = ..., + module: Optional[types.ModuleType] = ...) -> TestSuite: ... + def discover(self, start_dir: str, pattern: str = ..., + top_level_dir: Optional[str] = ...) -> TestSuite: ... + def getTestCaseNames(self, testCaseClass: Type[TestCase] = ...) -> List[str]: ... + +defaultTestLoader = ... # type: TestLoader + +class TextTestResult(TestResult): + def __init__(self, stream: TextIO, descriptions: bool, verbosity: int) -> None: ... + +class TextTestRunner: + def __init__(self, stream: Optional[TextIO] = ..., descriptions: bool = ..., + verbosity: int = ..., failfast: bool = ..., buffer: bool = ..., + resultclass: Optional[Type[TestResult]] = ...) -> None: ... + def _makeResult(self) -> TestResult: ... + +class SkipTest(Exception): + ... + +# TODO precise types +def skipUnless(condition: Any, reason: Union[str, unicode]) -> Any: ... +def skipIf(condition: Any, reason: Union[str, unicode]) -> Any: ... +def expectedFailure(func: _FT) -> _FT: ... +def skip(reason: Union[str, unicode]) -> Any: ... + +# not really documented +class TestProgram: + result = ... # type: TestResult + def runTests(self) -> None: ... # undocumented + +def main(module: Union[None, Text, types.ModuleType] = ..., defaultTest: Optional[str] = ..., + argv: Optional[Sequence[str]] = ..., + testRunner: Union[Type[TextTestRunner], TextTestRunner, None] = ..., + testLoader: TestLoader = ..., exit: bool = ..., verbosity: int = ..., + failfast: Optional[bool] = ..., catchbreak: Optional[bool] = ..., + buffer: Optional[bool] = ...) -> TestProgram: ... + +def load_tests(loader: TestLoader, tests: TestSuite, pattern: Optional[Text]) -> TestSuite: ... + +def installHandler() -> None: ... +def registerResult(result: TestResult) -> None: ... +def removeResult(result: TestResult) -> bool: ... +@overload +def removeHandler() -> None: ... +@overload +def removeHandler(function: Callable[..., Any]) -> Callable[..., Any]: ... + +# private but occasionally used +util = ... # type: types.ModuleType diff --git a/client/typeshed-fallback/stdlib/2/urllib.pyi b/client/typeshed-fallback/stdlib/2/urllib.pyi new file mode 100644 index 000000000..3373da357 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/urllib.pyi @@ -0,0 +1,134 @@ +from typing import Any, AnyStr, IO, List, Mapping, Sequence, Text, Tuple, TypeVar, Union + +def url2pathname(pathname: AnyStr) -> AnyStr: ... +def pathname2url(pathname: AnyStr) -> AnyStr: ... +def urlopen(url: str, data=..., proxies: Mapping[str, str] = ..., context=...) -> IO[Any]: ... +def urlretrieve(url, filename=..., reporthook=..., data=..., context=...): ... +def urlcleanup() -> None: ... + +class ContentTooShortError(IOError): + content = ... # type: Any + def __init__(self, message, content) -> None: ... + +class URLopener: + version = ... # type: Any + proxies = ... # type: Any + key_file = ... # type: Any + cert_file = ... # type: Any + context = ... # type: Any + addheaders = ... # type: Any + tempcache = ... # type: Any + ftpcache = ... # type: Any + def __init__(self, proxies: Mapping[str, str] = ..., context=..., **x509) -> None: ... + def __del__(self): ... + def close(self): ... + def cleanup(self): ... + def addheader(self, *args): ... + type = ... # type: Any + def open(self, fullurl: str, data=...): ... + def open_unknown(self, fullurl, data=...): ... + def open_unknown_proxy(self, proxy, fullurl, data=...): ... + def retrieve(self, url, filename=..., reporthook=..., data=...): ... + def open_http(self, url, data=...): ... + def http_error(self, url, fp, errcode, errmsg, headers, data=...): ... + def http_error_default(self, url, fp, errcode, errmsg, headers): ... + def open_https(self, url, data=...): ... + def open_file(self, url): ... + def open_local_file(self, url): ... + def open_ftp(self, url): ... + def open_data(self, url, data=...): ... + +class FancyURLopener(URLopener): + auth_cache = ... # type: Any + tries = ... # type: Any + maxtries = ... # type: Any + def __init__(self, *args, **kwargs) -> None: ... + def http_error_default(self, url, fp, errcode, errmsg, headers): ... + def http_error_302(self, url, fp, errcode, errmsg, headers, data=...): ... + def redirect_internal(self, url, fp, errcode, errmsg, headers, data): ... + def http_error_301(self, url, fp, errcode, errmsg, headers, data=...): ... + def http_error_303(self, url, fp, errcode, errmsg, headers, data=...): ... + def http_error_307(self, url, fp, errcode, errmsg, headers, data=...): ... + def http_error_401(self, url, fp, errcode, errmsg, headers, data=...): ... + def http_error_407(self, url, fp, errcode, errmsg, headers, data=...): ... + def retry_proxy_http_basic_auth(self, url, realm, data=...): ... + def retry_proxy_https_basic_auth(self, url, realm, data=...): ... + def retry_http_basic_auth(self, url, realm, data=...): ... + def retry_https_basic_auth(self, url, realm, data=...): ... + def get_user_passwd(self, host, realm, clear_cache=...): ... + def prompt_user_passwd(self, host, realm): ... + +class ftpwrapper: + user = ... # type: Any + passwd = ... # type: Any + host = ... # type: Any + port = ... # type: Any + dirs = ... # type: Any + timeout = ... # type: Any + refcount = ... # type: Any + keepalive = ... # type: Any + def __init__(self, user, passwd, host, port, dirs, timeout=..., persistent=...) -> None: ... + busy = ... # type: Any + ftp = ... # type: Any + def init(self): ... + def retrfile(self, file, type): ... + def endtransfer(self): ... + def close(self): ... + def file_close(self): ... + def real_close(self): ... + +_AIUT = TypeVar("_AIUT", bound=addbase) + +class addbase: + fp = ... # type: Any + def read(self, n: int = ...) -> bytes: ... + def readline(self, limit: int = ...) -> bytes: ... + def readlines(self, hint: int = ...) -> List[bytes]: ... + def fileno(self) -> int: ... # Optional[int], but that is rare + def __iter__(self: _AIUT) -> _AIUT: ... + def next(self) -> bytes: ... + def __init__(self, fp) -> None: ... + def close(self) -> None: ... + +class addclosehook(addbase): + closehook = ... # type: Any + hookargs = ... # type: Any + def __init__(self, fp, closehook, *hookargs) -> None: ... + def close(self): ... + +class addinfo(addbase): + headers = ... # type: Any + def __init__(self, fp, headers) -> None: ... + def info(self): ... + +class addinfourl(addbase): + headers = ... # type: Any + url = ... # type: Any + code = ... # type: Any + def __init__(self, fp, headers, url, code=...) -> None: ... + def info(self): ... + def getcode(self): ... + def geturl(self): ... + +def unwrap(url): ... +def splittype(url): ... +def splithost(url): ... +def splituser(host): ... +def splitpasswd(user): ... +def splitport(host): ... +def splitnport(host, defport=...): ... +def splitquery(url): ... +def splittag(url): ... +def splitattr(url): ... +def splitvalue(attr): ... +def unquote(s: AnyStr) -> AnyStr: ... +def unquote_plus(s: AnyStr) -> AnyStr: ... +def quote(s: AnyStr, safe: Text = ...) -> AnyStr: ... +def quote_plus(s: AnyStr, safe: Text = ...) -> AnyStr: ... +def urlencode(query: Union[Sequence[Tuple[Any, Any]], Mapping[Any, Any]], doseq=...) -> str: ... + +def getproxies() -> Mapping[str, str]: ... +def proxy_bypass(host): ... + +# Names in __all__ with no definition: +# basejoin diff --git a/client/typeshed-fallback/stdlib/2/urllib2.pyi b/client/typeshed-fallback/stdlib/2/urllib2.pyi new file mode 100644 index 000000000..3da0cd80c --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/urllib2.pyi @@ -0,0 +1,182 @@ + +import ssl +from typing import Any, AnyStr, Dict, List, Union, Optional, Mapping, Callable, Sequence, Text, Tuple, Type +from urllib import addinfourl +from httplib import HTTPConnectionProtocol, HTTPResponse + +_string = Union[str, unicode] + +class URLError(IOError): + reason = ... # type: Union[str, BaseException] + +class HTTPError(URLError, addinfourl): + code = ... # type: int + headers: Mapping[str, str] + def __init__(self, url, code: int, msg: str, hdrs: Mapping[str, str], fp: addinfourl) -> None: ... + +class Request(object): + host = ... # type: str + port = ... # type: str + data = ... # type: str + headers = ... # type: Dict[str, str] + unverifiable = ... # type: bool + type = ... # type: Optional[str] + origin_req_host = ... + unredirected_hdrs: Dict[str, str] + + def __init__(self, url: str, data: Optional[str] = ..., headers: Dict[str, str] = ..., + origin_req_host: Optional[str] = ..., unverifiable: bool = ...) -> None: ... + def __getattr__(self, attr): ... + def get_method(self) -> str: ... + def add_data(self, data) -> None: ... + def has_data(self) -> bool: ... + def get_data(self) -> str: ... + def get_full_url(self) -> str: ... + def get_type(self): ... + def get_host(self) -> str: ... + def get_selector(self): ... + def set_proxy(self, host, type) -> None: ... + def has_proxy(self) -> bool: ... + def get_origin_req_host(self) -> str: ... + def is_unverifiable(self) -> bool: ... + def add_header(self, key: str, val: str) -> None: ... + def add_unredirected_header(self, key: str, val: str) -> None: ... + def has_header(self, header_name: str) -> bool: ... + def get_header(self, header_name: str, default: Optional[str] = ...) -> str: ... + def header_items(self): ... + +class OpenerDirector(object): + addheaders: List[Tuple[str, str]] + + def add_handler(self, handler: BaseHandler) -> None: ... + def open(self, fullurl: Union[Request, _string], data: Optional[_string] = ..., timeout: Optional[float] = ...) -> Optional[addinfourl]: ... + def error(self, proto: _string, *args: Any): ... + +# Note that this type is somewhat a lie. The return *can* be None if +# a custom opener has been installed that fails to handle the request. +def urlopen(url: Union[Request, _string], data: Optional[_string] = ..., timeout: Optional[float] = ..., + cafile: Optional[_string] = ..., capath: Optional[_string] = ..., cadefault: bool = ..., + context: Optional[ssl.SSLContext] = ...) -> addinfourl: ... +def install_opener(opener: OpenerDirector) -> None: ... +def build_opener(*handlers: Union[BaseHandler, Type[BaseHandler]]) -> OpenerDirector: ... + +class BaseHandler: + handler_order = ... # type: int + parent = ... # type: OpenerDirector + + def add_parent(self, parent: OpenerDirector) -> None: ... + def close(self) -> None: ... + def __lt__(self, other: Any) -> bool: ... + +class HTTPErrorProcessor(BaseHandler): + def http_response(self, request, response): ... + +class HTTPDefaultErrorHandler(BaseHandler): + def http_error_default(self, req: Request, fp: addinfourl, code: int, msg: str, hdrs: Mapping[str, str]): ... + +class HTTPRedirectHandler(BaseHandler): + max_repeats = ... # type: int + max_redirections = ... # type: int + def redirect_request(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str], newurl): ... + def http_error_301(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + def http_error_302(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + def http_error_303(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + def http_error_307(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + inf_msg = ... # type: str + + +class ProxyHandler(BaseHandler): + proxies: Mapping[str, str] + + def __init__(self, proxies: Optional[Mapping[str, str]] = ...): ... + def proxy_open(self, req: Request, proxy, type): ... + +class HTTPPasswordMgr: + def __init__(self) -> None: ... + def add_password(self, realm: Optional[Text], uri: Union[Text, Sequence[Text]], user: Text, passwd: Text) -> None: ... + def find_user_password(self, realm: Optional[Text], authuri: Text) -> Tuple[Any, Any]: ... + def reduce_uri(self, uri: _string, default_port: bool = ...) -> Tuple[Any, Any]: ... + def is_suburi(self, base: _string, test: _string) -> bool: ... + +class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr): ... + +class AbstractBasicAuthHandler: + def __init__(self, password_mgr: Optional[HTTPPasswordMgr] = ...) -> None: ... + def add_password(self, realm: Optional[Text], uri: Union[Text, Sequence[Text]], user: Text, passwd: Text) -> None: ... + def http_error_auth_reqed(self, authreq, host, req: Request, headers: Mapping[str, str]): ... + def retry_http_basic_auth(self, host, req: Request, realm): ... + +class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): + auth_header = ... # type: str + def http_error_401(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + +class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): + auth_header = ... # type: str + def http_error_407(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + +class AbstractDigestAuthHandler: + def __init__(self, passwd: Optional[HTTPPasswordMgr] = ...) -> None: ... + def add_password(self, realm: Optional[Text], uri: Union[Text, Sequence[Text]], user: Text, passwd: Text) -> None: ... + def reset_retry_count(self) -> None: ... + def http_error_auth_reqed(self, auth_header: str, host: str, req: Request, + headers: Mapping[str, str]) -> None: ... + def retry_http_digest_auth(self, req: Request, auth: str) -> Optional[HTTPResponse]: ... + def get_cnonce(self, nonce: str) -> str: ... + def get_authorization(self, req: Request, chal: Mapping[str, str]) -> str: ... + def get_algorithm_impls(self, algorithm: str) -> Tuple[Callable[[str], str], Callable[[str, str], str]]: ... + def get_entity_digest(self, data: Optional[bytes], chal: Mapping[str, str]) -> Optional[str]: ... + +class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): + auth_header = ... # type: str + handler_order = ... # type: int + def http_error_401(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + +class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): + auth_header = ... # type: str + handler_order = ... # type: int + def http_error_407(self, req: Request, fp: addinfourl, code: int, msg: str, headers: Mapping[str, str]): ... + +class AbstractHTTPHandler(BaseHandler): # undocumented + def __init__(self, debuglevel: int = ...) -> None: ... + def set_http_debuglevel(self, level: int) -> None: ... + def do_request_(self, request: Request) -> Request: ... + def do_open(self, + http_class: HTTPConnectionProtocol, + req: Request, + **http_conn_args: Optional[Any]) -> addinfourl: ... + +class HTTPHandler(AbstractHTTPHandler): + def http_open(self, req: Request) -> addinfourl: ... + def http_request(self, request: Request) -> Request: ... # undocumented + +class HTTPSHandler(AbstractHTTPHandler): + def __init__(self, debuglevel: int = ..., context: Optional[ssl.SSLContext] = ...) -> None: ... + def https_open(self, req: Request) -> addinfourl: ... + def https_request(self, request: Request) -> Request: ... # undocumented + +class HTTPCookieProcessor(BaseHandler): + def __init__(self, cookiejar: Optional[Any] = ...): ... + def http_request(self, request: Request): ... + def http_response(self, request: Request, response): ... + +class UnknownHandler(BaseHandler): + def unknown_open(self, req: Request): ... + +class FileHandler(BaseHandler): + def file_open(self, req: Request): ... + def get_names(self): ... + def open_local_file(self, req: Request): ... + +class FTPHandler(BaseHandler): + def ftp_open(self, req: Request): ... + def connect_ftp(self, user, passwd, host, port, dirs, timeout): ... + +class CacheFTPHandler(FTPHandler): + def __init__(self) -> None: ... + def setTimeout(self, t: Optional[float]): ... + def setMaxConns(self, m: int): ... + def check_cache(self): ... + def clear_cache(self): ... + +def parse_http_list(s: AnyStr) -> List[AnyStr]: ... +def parse_keqv_list(l: List[AnyStr]) -> Dict[AnyStr, AnyStr]: ... diff --git a/client/typeshed-fallback/stdlib/2/urlparse.pyi b/client/typeshed-fallback/stdlib/2/urlparse.pyi new file mode 100644 index 000000000..169de2ff0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/urlparse.pyi @@ -0,0 +1,70 @@ +# Stubs for urlparse (Python 2) + +from typing import AnyStr, Dict, List, NamedTuple, Tuple, Sequence, Union, overload + +_String = Union[str, unicode] + +uses_relative = ... # type: List[str] +uses_netloc = ... # type: List[str] +uses_params = ... # type: List[str] +non_hierarchical = ... # type: List[str] +uses_query = ... # type: List[str] +uses_fragment = ... # type: List[str] +scheme_chars = ... # type: str +MAX_CACHE_SIZE = 0 + +def clear_cache() -> None: ... + +class ResultMixin(object): + @property + def username(self) -> str: ... + @property + def password(self) -> str: ... + @property + def hostname(self) -> str: ... + @property + def port(self) -> int: ... + +class SplitResult( + NamedTuple( + 'SplitResult', + [ + ('scheme', str), ('netloc', str), ('path', str), ('query', str), ('fragment', str) + ] + ), + ResultMixin +): + def geturl(self) -> str: ... + +class ParseResult( + NamedTuple( + 'ParseResult', + [ + ('scheme', str), ('netloc', str), ('path', str), ('params', str), ('query', str), + ('fragment', str) + ] + ), + ResultMixin +): + def geturl(self) -> str: ... + +def urlparse(url: _String, scheme: _String = ..., + allow_fragments: bool = ...) -> ParseResult: ... +def urlsplit(url: _String, scheme: _String = ..., + allow_fragments: bool = ...) -> SplitResult: ... +@overload +def urlunparse(data: Tuple[_String, _String, _String, _String, _String, _String]) -> str: ... +@overload +def urlunparse(data: Sequence[_String]) -> str: ... +@overload +def urlunsplit(data: Tuple[_String, _String, _String, _String, _String]) -> str: ... +@overload +def urlunsplit(data: Sequence[_String]) -> str: ... +def urljoin(base: _String, url: _String, + allow_fragments: bool = ...) -> str: ... +def urldefrag(url: AnyStr) -> Tuple[AnyStr, str]: ... +def unquote(s: AnyStr) -> AnyStr: ... +def parse_qs(qs: AnyStr, keep_blank_values: bool = ..., + strict_parsing: bool = ...) -> Dict[AnyStr, List[AnyStr]]: ... +def parse_qsl(qs: AnyStr, keep_blank_values: int = ..., + strict_parsing: bool = ...) -> List[Tuple[AnyStr, AnyStr]]: ... diff --git a/client/typeshed-fallback/stdlib/2/user.pyi b/client/typeshed-fallback/stdlib/2/user.pyi new file mode 100644 index 000000000..e857a3a95 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/user.pyi @@ -0,0 +1,9 @@ +# Stubs for user (Python 2) + +# Docs: https://docs.python.org/2/library/user.html +# Source: https://hg.python.org/cpython/file/2.7/Lib/user.py +from typing import Any + +def __getattr__(name) -> Any: ... +home: str +pythonrc: str diff --git a/client/typeshed-fallback/stdlib/2/whichdb.pyi b/client/typeshed-fallback/stdlib/2/whichdb.pyi new file mode 100644 index 000000000..b1a69f481 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/whichdb.pyi @@ -0,0 +1,5 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/whichdb.py + +from typing import Optional, Text + +def whichdb(filename: Text) -> Optional[str]: ... diff --git a/client/typeshed-fallback/stdlib/2/xmlrpclib.pyi b/client/typeshed-fallback/stdlib/2/xmlrpclib.pyi new file mode 100644 index 000000000..9f6fb9858 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2/xmlrpclib.pyi @@ -0,0 +1,199 @@ +# Stubs for xmlrpclib (Python 2) + +from typing import Any, AnyStr, Callable, IO, Iterable, List, Mapping, MutableMapping, Optional, Tuple, Type, TypeVar, Union +from types import InstanceType +from datetime import datetime +from time import struct_time +from httplib import HTTPConnection, HTTPResponse, HTTPSConnection +from ssl import SSLContext +from StringIO import StringIO +from gzip import GzipFile + +_Unmarshaller = Any +_timeTuple = Tuple[int, int, int, int, int, int, int, int, int] +# Represents types that can be compared against a DateTime object +_dateTimeComp = Union[AnyStr, DateTime, datetime, _timeTuple] +# A "host description" used by Transport factories +_hostDesc = Union[str, Tuple[str, Mapping[Any, Any]]] + +def escape(s: AnyStr, replace: Callable[[AnyStr, AnyStr, AnyStr], AnyStr] = ...) -> AnyStr: ... + +MAXINT = ... # type: int +MININT = ... # type: int +PARSE_ERROR = ... # type: int +SERVER_ERROR = ... # type: int +APPLICATION_ERROR = ... # type: int +SYSTEM_ERROR = ... # type: int +TRANSPORT_ERROR = ... # type: int +NOT_WELLFORMED_ERROR = ... # type: int +UNSUPPORTED_ENCODING = ... # type: int +INVALID_ENCODING_CHAR = ... # type: int +INVALID_XMLRPC = ... # type: int +METHOD_NOT_FOUND = ... # type: int +INVALID_METHOD_PARAMS = ... # type: int +INTERNAL_ERROR = ... # type: int + +class Error(Exception): ... + +class ProtocolError(Error): + url = ... # type: str + errcode = ... # type: int + errmsg = ... # type: str + headers = ... # type: Any + def __init__(self, url: str, errcode: int, errmsg: str, headers: Any) -> None: ... + +class ResponseError(Error): ... + +class Fault(Error): + faultCode = ... # type: Any + faultString = ... # type: str + def __init__(self, faultCode: Any, faultString: str, **extra: Any) -> None: ... + +boolean = ... # type: Type[bool] +Boolean = ... # type: Type[bool] + +class DateTime: + value = ... # type: str + def __init__(self, value: Union[str, unicode, datetime, float, int, _timeTuple, struct_time] = ...) -> None: ... + def make_comparable(self, other: _dateTimeComp) -> Tuple[_dateTimeComp, _dateTimeComp]: ... + def __lt__(self, other: _dateTimeComp) -> bool: ... + def __le__(self, other: _dateTimeComp) -> bool: ... + def __gt__(self, other: _dateTimeComp) -> bool: ... + def __ge__(self, other: _dateTimeComp) -> bool: ... + def __eq__(self, other: _dateTimeComp) -> bool: ... + def __ne__(self, other: _dateTimeComp) -> bool: ... + def timetuple(self) -> struct_time: ... + def __cmp__(self, other: _dateTimeComp) -> int: ... + def decode(self, data: Any) -> None: ... + def encode(self, out: IO) -> None: ... + +class Binary: + data = ... # type: str + def __init__(self, data: Optional[str] = ...) -> None: ... + def __cmp__(self, other: Any) -> int: ... + def decode(self, data: str) -> None: ... + def encode(self, out: IO) -> None: ... + +WRAPPERS = ... # type: tuple + +# Still part of the public API, but see http://bugs.python.org/issue1773632 +FastParser = ... # type: None +FastUnmarshaller = ... # type: None +FastMarshaller = ... # type: None + +# xmlrpclib.py will leave ExpatParser undefined if it can't import expat from +# xml.parsers. Because this is Python 2.7, the import will succeed. +class ExpatParser: + def __init__(self, target: _Unmarshaller) -> None: ... + def feed(self, data: str): ... + def close(self): ... + +# TODO: Add xmllib.XMLParser as base class +class SlowParser: + handle_xml = ... # type: Callable[[str, bool], None] + unknown_starttag = ... # type: Callable[[str, Any], None] + handle_data = ... # type: Callable[[str], None] + handle_cdata = ... # type: Callable[[str], None] + unknown_endtag = ... # type: Callable[[str, Callable[[Iterable[str], str], str]], None] + def __init__(self, target: _Unmarshaller) -> None: ... + +class Marshaller: + memo = ... # type: MutableMapping[int, Any] + data = ... # type: Optional[str] + encoding = ... # type: Optional[str] + allow_none = ... # type: bool + def __init__(self, encoding: Optional[str] = ..., allow_none: bool = ...) -> None: ... + dispatch = ... # type: Mapping[type, Callable[[Marshaller, str, Callable[[str], None]], None]] + def dumps(self, values: Union[Iterable[Union[None, int, bool, long, float, str, unicode, List, Tuple, Mapping, datetime, InstanceType]], Fault]) -> str: ... + def dump_nil(self, value: None, write: Callable[[str], None]) -> None: ... + def dump_int(self, value: int, write: Callable[[str], None]) -> None: ... + def dump_bool(self, value: bool, write: Callable[[str], None]) -> None: ... + def dump_long(self, value: long, write: Callable[[str], None]) -> None: ... + def dump_double(self, value: float, write: Callable[[str], None]) -> None: ... + def dump_string(self, value: str, write: Callable[[str], None], escape: Callable[[AnyStr, Callable[[AnyStr, AnyStr, AnyStr], AnyStr]], AnyStr] = ...) -> None: ... + def dump_unicode(self, value: unicode, write: Callable[[str], None], escape: Callable[[AnyStr, Callable[[AnyStr, AnyStr, AnyStr], AnyStr]], AnyStr] = ...) -> None: ... + def dump_array(self, value: Union[List, Tuple], write: Callable[[str], None]) -> None: ... + def dump_struct(self, value: Mapping, write: Callable[[str], None], escape: Callable[[AnyStr, Callable[[AnyStr, AnyStr, AnyStr], AnyStr]], AnyStr] = ...) -> None: ... + def dump_datetime(self, value: datetime, write: Callable[[str], None]) -> None: ... + def dump_instance(self, value: InstanceType, write: Callable[[str], None]) -> None: ... + +class Unmarshaller: + def append(self, object: Any) -> None: ... + def __init__(self, use_datetime: bool = ...) -> None: ... + def close(self) -> tuple: ... + def getmethodname(self) -> Optional[str]: ... + def xml(self, encoding: str, standalone: bool) -> None: ... + def start(self, tag: str, attrs: Any) -> None: ... + def data(self, text: str) -> None: ... + def end(self, tag: str, join: Callable[[Iterable[str], str], str] = ...) -> None: ... + def end_dispatch(self, tag: str, data: str) -> None: ... + dispatch = ... # type: Mapping[str, Callable[[Unmarshaller, str], None]] + def end_nil(self, data: str): ... + def end_boolean(self, data: str) -> None: ... + def end_int(self, data: str) -> None: ... + def end_double(self, data: str) -> None: ... + def end_string(self, data: str) -> None: ... + def end_array(self, data: str) -> None: ... + def end_struct(self, data: str) -> None: ... + def end_base64(self, data: str) -> None: ... + def end_dateTime(self, data: str) -> None: ... + def end_value(self, data: str) -> None: ... + def end_params(self, data: str) -> None: ... + def end_fault(self, data: str) -> None: ... + def end_methodName(self, data: str) -> None: ... + +class _MultiCallMethod: + def __init__(self, call_list: List[Tuple[str, tuple]], name: str) -> None: ... +class MultiCallIterator: + def __init__(self, results: List) -> None: ... + +class MultiCall: + def __init__(self, server: ServerProxy) -> None: ... + def __getattr__(self, name: str) -> _MultiCallMethod: ... + def __call__(self) -> MultiCallIterator: ... + +def getparser(use_datetime: bool = ...) -> Tuple[Union[ExpatParser, SlowParser], Unmarshaller]: ... +def dumps(params: Union[tuple, Fault], methodname: Optional[str] = ..., methodresponse: Optional[bool] = ..., encoding: Optional[str] = ..., allow_none: bool = ...) -> str: ... +def loads(data: str, use_datetime: bool = ...) -> Tuple[tuple, Optional[str]]: ... + +def gzip_encode(data: str) -> str: ... +def gzip_decode(data: str, max_decode: int = ...) -> str: ... + +class GzipDecodedResponse(GzipFile): + stringio = ... # type: StringIO + def __init__(self, response: HTTPResponse) -> None: ... + def close(self): ... + +class _Method: + def __init__(self, send: Callable[[str, tuple], Any], name: str) -> None: ... + def __getattr__(self, name: str) -> _Method: ... + def __call__(self, *args: Any) -> Any: ... + +class Transport: + user_agent = ... # type: str + accept_gzip_encoding = ... # type: bool + encode_threshold = ... # type: Optional[int] + def __init__(self, use_datetime: bool = ...) -> None: ... + def request(self, host: _hostDesc, handler: str, request_body: str, verbose: bool = ...) -> tuple: ... + verbose = ... # type: bool + def single_request(self, host: _hostDesc, handler: str, request_body: str, verbose: bool = ...) -> tuple: ... + def getparser(self) -> Tuple[Union[ExpatParser, SlowParser], Unmarshaller]: ... + def get_host_info(self, host: _hostDesc) -> Tuple[str, Optional[List[Tuple[str, str]]], Optional[Mapping[Any, Any]]]: ... + def make_connection(self, host: _hostDesc) -> HTTPConnection: ... + def close(self) -> None: ... + def send_request(self, connection: HTTPConnection, handler: str, request_body: str) -> None: ... + def send_host(self, connection: HTTPConnection, host: str) -> None: ... + def send_user_agent(self, connection: HTTPConnection) -> None: ... + def send_content(self, connection: HTTPConnection, request_body: str) -> None: ... + def parse_response(self, response: HTTPResponse) -> tuple: ... + +class SafeTransport(Transport): + def __init__(self, use_datetime: bool = ..., context: Optional[SSLContext] = ...) -> None: ... + def make_connection(self, host: _hostDesc) -> HTTPSConnection: ... + +class ServerProxy: + def __init__(self, uri: str, transport: Optional[Transport] = ..., encoding: Optional[str] = ..., verbose: bool = ..., allow_none: bool = ..., use_datetime: bool = ..., context: Optional[SSLContext] = ...) -> None: ... + def __getattr__(self, name: str) -> _Method: ... + def __call__(self, attr: str) -> Optional[Transport]: ... + +Server = ServerProxy diff --git a/client/typeshed-fallback/stdlib/2and3/__future__.pyi b/client/typeshed-fallback/stdlib/2and3/__future__.pyi new file mode 100644 index 000000000..13db2dc6b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/__future__.pyi @@ -0,0 +1,24 @@ +import sys +from typing import List + +class _Feature: + def getOptionalRelease(self) -> sys._version_info: ... + def getMandatoryRelease(self) -> sys._version_info: ... + +absolute_import: _Feature +division: _Feature +generators: _Feature +nested_scopes: _Feature +print_function: _Feature +unicode_literals: _Feature +with_statement: _Feature +if sys.version_info >= (3, 0): + barry_as_FLUFL: _Feature + +if sys.version_info >= (3, 5): + generator_stop: _Feature + +if sys.version_info >= (3, 7): + annotations: _Feature + +all_feature_names: List[str] diff --git a/client/typeshed-fallback/stdlib/2and3/_bisect.pyi b/client/typeshed-fallback/stdlib/2and3/_bisect.pyi new file mode 100644 index 000000000..62335472f --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/_bisect.pyi @@ -0,0 +1,11 @@ +"""Stub file for the '_bisect' module.""" + +from typing import Sequence, TypeVar + +_T = TypeVar('_T') +def bisect(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> int: ... +def bisect_left(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> int: ... +def bisect_right(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> int: ... +def insort(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> None: ... +def insort_left(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> None: ... +def insort_right(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/_codecs.pyi b/client/typeshed-fallback/stdlib/2and3/_codecs.pyi new file mode 100644 index 000000000..32163eb91 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/_codecs.pyi @@ -0,0 +1,74 @@ +"""Stub file for the '_codecs' module.""" + +import sys +from typing import Any, Callable, Tuple, Optional, Dict, Text, Union + +import codecs + +# For convenience: +_Handler = Callable[[Exception], Tuple[Text, int]] +_String = Union[bytes, str] +_Errors = Union[str, Text, None] +if sys.version_info < (3, 0): + _Decodable = Union[bytes, Text] + _Encodable = Union[bytes, Text] +else: + _Decodable = bytes + _Encodable = str + +# This type is not exposed; it is defined in unicodeobject.c +class _EncodingMap(object): + def size(self) -> int: ... +_MapT = Union[Dict[int, int], _EncodingMap] + +def register(search_function: Callable[[str], Any]) -> None: ... +def register_error(errors: Union[str, Text], handler: _Handler) -> None: ... +def lookup(encoding: Union[str, Text]) -> codecs.CodecInfo: ... +def lookup_error(name: Union[str, Text]) -> _Handler: ... +def decode(obj: Any, encoding: Union[str, Text] = ..., errors: _Errors = ...) -> Any: ... +def encode(obj: Any, encoding: Union[str, Text] = ..., errors: _Errors = ...) -> Any: ... +def charmap_build(map: Text) -> _MapT: ... + +def ascii_decode(data: _Decodable, errors: _Errors = ...) -> Tuple[Text, int]: ... +def ascii_encode(data: _Encodable, errors: _Errors = ...) -> Tuple[bytes, int]: ... +def charbuffer_encode(data: _Encodable, errors: _Errors = ...) -> Tuple[bytes, int]: ... +def charmap_decode(data: _Decodable, errors: _Errors = ..., mapping: Optional[_MapT] = ...) -> Tuple[Text, int]: ... +def charmap_encode(data: _Encodable, errors: _Errors, mapping: Optional[_MapT] = ...) -> Tuple[bytes, int]: ... +def escape_decode(data: _String, errors: _Errors = ...) -> Tuple[str, int]: ... +def escape_encode(data: bytes, errors: _Errors = ...) -> Tuple[bytes, int]: ... +def latin_1_decode(data: _Decodable, errors: _Errors = ...) -> Tuple[Text, int]: ... +def latin_1_encode(data: _Encodable, errors: _Errors = ...) -> Tuple[bytes, int]: ... +def raw_unicode_escape_decode(data: _String, errors: _Errors = ...) -> Tuple[Text, int]: ... +def raw_unicode_escape_encode(data: _Encodable, errors: _Errors = ...) -> Tuple[bytes, int]: ... +def readbuffer_encode(data: _String, errors: _Errors = ...) -> Tuple[bytes, int]: ... +def unicode_escape_decode(data: _String, errors: _Errors = ...) -> Tuple[Text, int]: ... +def unicode_escape_encode(data: _Encodable, errors: _Errors = ...) -> Tuple[bytes, int]: ... +def unicode_internal_decode(data: _String, errors: _Errors = ...) -> Tuple[Text, int]: ... +def unicode_internal_encode(data: _String, errors: _Errors = ...) -> Tuple[bytes, int]: ... +def utf_16_be_decode(data: _Decodable, errors: _Errors = ..., final: int = ...) -> Tuple[Text, int]: ... +def utf_16_be_encode(data: _Encodable, errors: _Errors = ...) -> Tuple[bytes, int]: ... +def utf_16_decode(data: _Decodable, errors: _Errors = ..., final: int = ...) -> Tuple[Text, int]: ... +def utf_16_encode(data: _Encodable, errors: _Errors = ..., byteorder: int = ...) -> Tuple[bytes, int]: ... +def utf_16_ex_decode(data: _Decodable, errors: _Errors = ..., final: int = ...) -> Tuple[Text, int, int]: ... +def utf_16_le_decode(data: _Decodable, errors: _Errors = ..., final: int = ...) -> Tuple[Text, int]: ... +def utf_16_le_encode(data: _Encodable, errors: _Errors = ...) -> Tuple[bytes, int]: ... +def utf_32_be_decode(data: _Decodable, errors: _Errors = ..., final: int = ...) -> Tuple[Text, int]: ... +def utf_32_be_encode(data: _Encodable, errors: _Errors = ...) -> Tuple[bytes, int]: ... +def utf_32_decode(data: _Decodable, errors: _Errors = ..., final: int = ...) -> Tuple[Text, int]: ... +def utf_32_encode(data: _Encodable, errors: _Errors = ..., byteorder: int = ...) -> Tuple[bytes, int]: ... +def utf_32_ex_decode(data: _Decodable, errors: _Errors = ..., final: int = ...) -> Tuple[Text, int, int]: ... +def utf_32_le_decode(data: _Decodable, errors: _Errors = ..., final: int = ...) -> Tuple[Text, int]: ... +def utf_32_le_encode(data: _Encodable, errors: _Errors = ...) -> Tuple[bytes, int]: ... +def utf_7_decode(data: _Decodable, errors: _Errors = ..., final: int = ...) -> Tuple[Text, int]: ... +def utf_7_encode(data: _Encodable, errors: _Errors = ...) -> Tuple[bytes, int]: ... +def utf_8_decode(data: _Decodable, errors: _Errors = ..., final: int = ...) -> Tuple[Text, int]: ... +def utf_8_encode(data: _Encodable, errors: _Errors = ...) -> Tuple[bytes, int]: ... + +if sys.platform == 'win32': + def mbcs_decode(data: _Decodable, errors: _Errors = ..., final: int = ...) -> Tuple[Text, int]: ... + def mbcs_encode(str: _Encodable, errors: _Errors = ...) -> Tuple[bytes, int]: ... + if sys.version_info >= (3, 0): + def oem_decode(data: bytes, errors: _Errors = ..., final: int = ...) -> Tuple[Text, int]: ... + def code_page_decode(codepage: int, data: bytes, errors: _Errors = ..., final: int = ...) -> Tuple[Text, int]: ... + def oem_encode(str: Text, errors: _Errors = ...) -> Tuple[bytes, int]: ... + def code_page_encode(code_page: int, str: Text, errors: _Errors = ...) -> Tuple[bytes, int]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/_csv.pyi b/client/typeshed-fallback/stdlib/2and3/_csv.pyi new file mode 100644 index 000000000..ff7111a87 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/_csv.pyi @@ -0,0 +1,49 @@ +import sys + +from typing import Any, Iterable, Iterator, List, Optional, Sequence, Text + +QUOTE_ALL = ... # type: int +QUOTE_MINIMAL = ... # type: int +QUOTE_NONE = ... # type: int +QUOTE_NONNUMERIC = ... # type: int + +class Error(Exception): ... + +class Dialect: + delimiter = ... # type: str + quotechar = ... # type: Optional[str] + escapechar = ... # type: Optional[str] + doublequote = ... # type: bool + skipinitialspace = ... # type: bool + lineterminator = ... # type: str + quoting = ... # type: int + strict = ... # type: int + def __init__(self) -> None: ... + +class _reader(Iterator[List[str]]): + dialect = ... # type: Dialect + line_num = ... # type: int + if sys.version_info >= (3, 0): + def __next__(self) -> List[str]: ... + else: + def next(self) -> List[str]: ... + +class _writer: + dialect = ... # type: Dialect + + if sys.version_info >= (3, 5): + def writerow(self, row: Iterable[Any]) -> None: ... + def writerows(self, rows: Iterable[Iterable[Any]]) -> None: ... + else: + def writerow(self, row: Sequence[Any]) -> None: ... + def writerows(self, rows: Iterable[Sequence[Any]]) -> None: ... + + +# TODO: precise type +def writer(csvfile: Any, dialect: Any = ..., **fmtparams: Any) -> _writer: ... +def reader(csvfile: Iterable[Text], dialect: Any = ..., **fmtparams: Any) -> _reader: ... +def register_dialect(name: str, dialect: Any = ..., **fmtparams: Any) -> None: ... +def unregister_dialect(name: str) -> None: ... +def get_dialect(name: str) -> Dialect: ... +def list_dialects() -> List[str]: ... +def field_size_limit(new_limit: int = ...) -> int: ... diff --git a/client/typeshed-fallback/stdlib/2and3/_heapq.pyi b/client/typeshed-fallback/stdlib/2and3/_heapq.pyi new file mode 100644 index 000000000..8b7f6eac0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/_heapq.pyi @@ -0,0 +1,15 @@ +"""Stub file for the '_heapq' module.""" + +from typing import TypeVar, List + +_T = TypeVar("_T") + +def heapify(heap: List[_T]) -> None: ... +def heappop(heap: List[_T]) -> _T: + raise IndexError() # if list is empty +def heappush(heap: List[_T], item: _T) -> None: ... +def heappushpop(heap: List[_T], item: _T) -> _T: ... +def heapreplace(heap: List[_T], item: _T) -> _T: + raise IndexError() # if list is empty +def nlargest(a: int, b: List[_T]) -> List[_T]: ... +def nsmallest(a: int, b: List[_T]) -> List[_T]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/_random.pyi b/client/typeshed-fallback/stdlib/2and3/_random.pyi new file mode 100644 index 000000000..a37149da0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/_random.pyi @@ -0,0 +1,17 @@ +# Stubs for _random + +import sys +from typing import Tuple + +# Actually Tuple[(int,) * 625] +_State = Tuple[int, ...] + +class Random(object): + def __init__(self, seed: object = ...) -> None: ... + def seed(self, x: object = ...) -> None: ... + def getstate(self) -> _State: ... + def setstate(self, state: _State) -> None: ... + def random(self) -> float: ... + def getrandbits(self, k: int) -> int: ... + if sys.version_info < (3,): + def jumpahead(self, i: int) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/_weakref.pyi b/client/typeshed-fallback/stdlib/2and3/_weakref.pyi new file mode 100644 index 000000000..6a527c189 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/_weakref.pyi @@ -0,0 +1,28 @@ +import sys +from typing import Any, Callable, Generic, Optional, TypeVar, overload + +_C = TypeVar('_C', bound=Callable[..., Any]) +_T = TypeVar('_T') + +class CallableProxyType(object): # "weakcallableproxy" + def __getattr__(self, attr: str) -> Any: ... + +class ProxyType(object): # "weakproxy" + def __getattr__(self, attr: str) -> Any: ... + +class ReferenceType(Generic[_T]): + if sys.version_info >= (3, 4): + __callback__: Callable[[ReferenceType[_T]], Any] + def __init__(self, o: _T, callback: Optional[Callable[[ReferenceType[_T]], Any]] = ...) -> None: ... + def __call__(self) -> Optional[_T]: ... + def __hash__(self) -> int: ... + +ref = ReferenceType + +def getweakrefcount(object: Any) -> int: ... +def getweakrefs(object: Any) -> int: ... +@overload +def proxy(object: _C, callback: Optional[Callable[[_C], Any]] = ...) -> CallableProxyType: ... +# Return CallableProxyType if object is callable, ProxyType otherwise +@overload +def proxy(object: _T, callback: Optional[Callable[[_T], Any]] = ...) -> Any: ... diff --git a/client/typeshed-fallback/stdlib/2and3/_weakrefset.pyi b/client/typeshed-fallback/stdlib/2and3/_weakrefset.pyi new file mode 100644 index 000000000..950d3fe64 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/_weakrefset.pyi @@ -0,0 +1,43 @@ +from typing import Iterator, Any, Iterable, MutableSet, Optional, TypeVar, Generic, Union + +_S = TypeVar('_S') +_T = TypeVar('_T') +_SelfT = TypeVar('_SelfT', bound=WeakSet) + +class WeakSet(MutableSet[_T], Generic[_T]): + def __init__(self, data: Optional[Iterable[_T]] = ...) -> None: ... + + def add(self, item: _T) -> None: ... + def clear(self) -> None: ... + def discard(self, item: _T) -> None: ... + def copy(self: _SelfT) -> _SelfT: ... + def pop(self) -> _T: ... + def remove(self, item: _T) -> None: ... + def update(self, other: Iterable[_T]) -> None: ... + def __contains__(self, item: object) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + + def __ior__(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... + def difference(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def __sub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def difference_update(self: _SelfT, other: Iterable[_T]) -> None: ... + def __isub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def intersection(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def __and__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def intersection_update(self, other: Iterable[_T]) -> None: ... + def __iand__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def issubset(self, other: Iterable[_T]) -> bool: ... + def __le__(self, other: Iterable[_T]) -> bool: ... + def __lt__(self, other: Iterable[_T]) -> bool: ... + def issuperset(self, other: Iterable[_T]) -> bool: ... + def __ge__(self, other: Iterable[_T]) -> bool: ... + def __gt__(self, other: Iterable[_T]) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def symmetric_difference(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... + def __xor__(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... + def symmetric_difference_update(self, other: Iterable[_S]) -> None: ... + def __ixor__(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... + def union(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... + def __or__(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... + def isdisjoint(self, other: Iterable[_T]) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/2and3/argparse.pyi b/client/typeshed-fallback/stdlib/2and3/argparse.pyi new file mode 100644 index 000000000..d4dd5b5bb --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/argparse.pyi @@ -0,0 +1,408 @@ +# Stubs for argparse (Python 2.7 and 3.4) + +from typing import ( + Any, Callable, Dict, Generator, Iterable, List, IO, NoReturn, Optional, + Pattern, Sequence, Tuple, Type, Union, TypeVar, overload +) +import sys + +_T = TypeVar('_T') +_ActionT = TypeVar('_ActionT', bound='Action') +_N = TypeVar('_N') + +if sys.version_info >= (3,): + _Text = str +else: + _Text = Union[str, unicode] + +ONE_OR_MORE: str +OPTIONAL: str +PARSER: str +REMAINDER: str +SUPPRESS: str +ZERO_OR_MORE: str +_UNRECOGNIZED_ARGS_ATTR: str # undocumented + +class ArgumentError(Exception): ... + +# undocumented +class _AttributeHolder: + def _get_kwargs(self) -> List[Tuple[str, Any]]: ... + def _get_args(self) -> List[Any]: ... + +# undocumented +class _ActionsContainer: + description: Optional[_Text] + prefix_chars: _Text + argument_default: Optional[_Text] + conflict_handler: _Text + + _registries: Dict[_Text, Dict[Any, Any]] + _actions: List[Action] + _option_string_actions: Dict[_Text, Action] + _action_groups: List[_ArgumentGroup] + _mutually_exclusive_groups: List[_MutuallyExclusiveGroup] + _defaults: Dict[str, Any] + _negative_number_matcher: Pattern[str] + _has_negative_number_optionals: List[bool] + + def __init__(self, description: Optional[_Text], prefix_chars: _Text, + argument_default: Optional[_Text], conflict_handler: _Text) -> None: ... + def register(self, registry_name: _Text, value: Any, object: Any) -> None: ... + def _registry_get(self, registry_name: _Text, value: Any, default: Any = ...) -> Any: ... + def set_defaults(self, **kwargs: Any) -> None: ... + def get_default(self, dest: _Text) -> Any: ... + def add_argument(self, + *name_or_flags: _Text, + action: Union[_Text, Type[Action]] = ..., + nargs: Union[int, _Text] = ..., + const: Any = ..., + default: Any = ..., + type: Union[Callable[[str], _T], FileType] = ..., + choices: Iterable[_T] = ..., + required: bool = ..., + help: Optional[_Text] = ..., + metavar: Optional[Union[_Text, Tuple[_Text, ...]]] = ..., + dest: Optional[_Text] = ..., + version: _Text = ..., + **kwargs: Any) -> Action: ... + def add_argument_group(self, *args: Any, **kwargs: Any) -> _ArgumentGroup: ... + def add_mutually_exclusive_group(self, **kwargs: Any) -> _MutuallyExclusiveGroup: ... + def _add_action(self, action: _ActionT) -> _ActionT: ... + def _remove_action(self, action: Action) -> None: ... + def _add_container_actions(self, container: _ActionsContainer) -> None: ... + def _get_positional_kwargs(self, dest: _Text, **kwargs: Any) -> Dict[str, Any]: ... + def _get_optional_kwargs(self, *args: Any, **kwargs: Any) -> Dict[str, Any]: ... + def _pop_action_class(self, kwargs: Any, default: Optional[Type[Action]] = ...) -> Type[Action]: ... + def _get_handler(self) -> Callable[[Action, Iterable[Tuple[_Text, Action]]], Any]: ... + def _check_conflict(self, action: Action) -> None: ... + def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[Tuple[_Text, Action]]) -> NoReturn: ... + def _handle_conflict_resolve(self, action: Action, conflicting_actions: Iterable[Tuple[_Text, Action]]) -> None: ... + +class ArgumentParser(_AttributeHolder, _ActionsContainer): + prog: _Text + usage: Optional[_Text] + epilog: Optional[_Text] + formatter_class: Type[HelpFormatter] + fromfile_prefix_chars: Optional[_Text] + add_help: bool + + if sys.version_info >= (3, 5): + allow_abbrev: bool + + # undocumented + _positionals: _ArgumentGroup + _optionals: _ArgumentGroup + _subparsers: Optional[_ArgumentGroup] + + if sys.version_info >= (3, 5): + def __init__(self, + prog: Optional[str] = ..., + usage: Optional[str] = ..., + description: Optional[str] = ..., + epilog: Optional[str] = ..., + parents: Sequence[ArgumentParser] = ..., + formatter_class: Type[HelpFormatter] = ..., + prefix_chars: _Text = ..., + fromfile_prefix_chars: Optional[str] = ..., + argument_default: Optional[str] = ..., + conflict_handler: _Text = ..., + add_help: bool = ..., + allow_abbrev: bool = ...) -> None: ... + else: + def __init__(self, + prog: Optional[_Text] = ..., + usage: Optional[_Text] = ..., + description: Optional[_Text] = ..., + epilog: Optional[_Text] = ..., + parents: Sequence[ArgumentParser] = ..., + formatter_class: Type[HelpFormatter] = ..., + prefix_chars: _Text = ..., + fromfile_prefix_chars: Optional[_Text] = ..., + argument_default: Optional[_Text] = ..., + conflict_handler: _Text = ..., + add_help: bool = ...) -> None: ... + + # The type-ignores in these overloads should be temporary. See: + # https://github.com/python/typeshed/pull/2643#issuecomment-442280277 + @overload + def parse_args(self, args: Optional[Sequence[_Text]] = ...) -> Namespace: ... + @overload + def parse_args(self, args: Optional[Sequence[_Text]], namespace: None) -> Namespace: ... # type: ignore + @overload + def parse_args(self, args: Optional[Sequence[_Text]], namespace: _N) -> _N: ... + @overload + def parse_args(self, *, namespace: None) -> Namespace: ... # type: ignore + @overload + def parse_args(self, *, namespace: _N) -> _N: ... + + if sys.version_info >= (3, 7): + def add_subparsers(self, title: _Text = ..., + description: Optional[_Text] = ..., + prog: _Text = ..., + parser_class: Type[ArgumentParser] = ..., + action: Type[Action] = ..., + option_string: _Text = ..., + dest: Optional[_Text] = ..., + required: bool = ..., + help: Optional[_Text] = ..., + metavar: Optional[_Text] = ...) -> _SubParsersAction: ... + else: + def add_subparsers(self, title: _Text = ..., + description: Optional[_Text] = ..., + prog: _Text = ..., + parser_class: Type[ArgumentParser] = ..., + action: Type[Action] = ..., + option_string: _Text = ..., + dest: Optional[_Text] = ..., + help: Optional[_Text] = ..., + metavar: Optional[_Text] = ...) -> _SubParsersAction: ... + + def print_usage(self, file: Optional[IO[str]] = ...) -> None: ... + def print_help(self, file: Optional[IO[str]] = ...) -> None: ... + def format_usage(self) -> str: ... + def format_help(self) -> str: ... + def parse_known_args(self, args: Optional[Sequence[_Text]] = ..., + namespace: Optional[Namespace] = ...) -> Tuple[Namespace, List[str]]: ... + def convert_arg_line_to_args(self, arg_line: _Text) -> List[str]: ... + def exit(self, status: int = ..., message: Optional[_Text] = ...) -> NoReturn: ... + def error(self, message: _Text) -> NoReturn: ... + if sys.version_info >= (3, 7): + def parse_intermixed_args(self, args: Optional[Sequence[_Text]] = ..., + namespace: Optional[Namespace] = ...) -> Namespace: ... + def parse_known_intermixed_args(self, + args: Optional[Sequence[_Text]] = ..., + namespace: Optional[Namespace] = ...) -> Tuple[Namespace, List[str]]: ... + # undocumented + def _get_optional_actions(self) -> List[Action]: ... + def _get_positional_actions(self) -> List[Action]: ... + def _parse_known_args(self, arg_strings: List[_Text], namespace: Namespace) -> Tuple[Namespace, List[str]]: ... + def _read_args_from_files(self, arg_strings: List[_Text]) -> List[_Text]: ... + def _match_argument(self, action: Action, arg_strings_pattern: _Text) -> int: ... + def _match_arguments_partial(self, actions: Sequence[Action], arg_strings_pattern: _Text) -> List[int]: ... + def _parse_optional(self, arg_string: _Text) -> Optional[Tuple[Optional[Action], _Text, Optional[_Text]]]: ... + def _get_option_tuples(self, option_string: _Text) -> List[Tuple[Action, _Text, Optional[_Text]]]: ... + def _get_nargs_pattern(self, action: Action) -> _Text: ... + def _get_values(self, action: Action, arg_strings: List[_Text]) -> Any: ... + def _get_value(self, action: Action, arg_string: _Text) -> Any: ... + def _check_value(self, action: Action, value: Any) -> None: ... + def _get_formatter(self) -> HelpFormatter: ... + def _print_message(self, message: str, file: Optional[IO[str]] = ...) -> None: ... + +class HelpFormatter: + # undocumented + _prog: _Text + _indent_increment: int + _max_help_position: int + _width: int + _current_indent: int + _level: int + _action_max_length: int + _root_section: Any + _current_section: Any + _whitespace_matcher: Pattern[str] + _long_break_matcher: Pattern[str] + _Section: Type[Any] # Nested class + def __init__(self, prog: _Text, indent_increment: int = ..., + max_help_position: int = ..., + width: Optional[int] = ...) -> None: ... + def _indent(self) -> None: ... + def _dedent(self) -> None: ... + def _add_item(self, func: Callable[..., _Text], args: Iterable[Any]) -> None: ... + def start_section(self, heading: Optional[_Text]) -> None: ... + def end_section(self) -> None: ... + def add_text(self, text: Optional[_Text]) -> None: ... + def add_usage(self, usage: _Text, actions: Iterable[Action], groups: Iterable[_ArgumentGroup], prefix: Optional[_Text] = ...) -> None: ... + def add_argument(self, action: Action) -> None: ... + def add_arguments(self, actions: Iterable[Action]) -> None: ... + def format_help(self) -> _Text: ... + def _join_parts(self, part_strings: Iterable[_Text]) -> _Text: ... + def _format_usage(self, usage: _Text, actions: Iterable[Action], groups: Iterable[_ArgumentGroup], prefix: Optional[_Text]) -> _Text: ... + def _format_actions_usage(self, actions: Iterable[Action], groups: Iterable[_ArgumentGroup]) -> _Text: ... + def _format_text(self, text: _Text) -> _Text: ... + def _format_action(self, action: Action) -> _Text: ... + def _format_action_invocation(self, action: Action) -> _Text: ... + def _metavar_formatter(self, action: Action, default_metavar: _Text) -> Callable[[int], Tuple[_Text, ...]]: ... + def _format_args(self, action: Action, default_metavar: _Text) -> _Text: ... + def _expand_help(self, action: Action) -> _Text: ... + def _iter_indented_subactions(self, action: Action) -> Generator[Action, None, None]: ... + def _split_lines(self, text: _Text, width: int) -> List[_Text]: ... + def _fill_text(self, text: _Text, width: int, indent: int) -> _Text: ... + def _get_help_string(self, action: Action) -> Optional[_Text]: ... + def _get_default_metavar_for_optional(self, action: Action) -> _Text: ... + def _get_default_metavar_for_positional(self, action: Action) -> _Text: ... + +class RawDescriptionHelpFormatter(HelpFormatter): ... +class RawTextHelpFormatter(HelpFormatter): ... +class ArgumentDefaultsHelpFormatter(HelpFormatter): ... +if sys.version_info >= (3,): + class MetavarTypeHelpFormatter(HelpFormatter): ... + +class Action(_AttributeHolder): + option_strings: Sequence[_Text] + dest: _Text + nargs: Optional[Union[int, _Text]] + const: Any + default: Any + type: Union[Callable[[str], Any], FileType, None] + choices: Optional[Iterable[Any]] + required: bool + help: Optional[_Text] + metavar: Optional[Union[_Text, Tuple[_Text, ...]]] + + def __init__(self, + option_strings: Sequence[_Text], + dest: _Text, + nargs: Optional[Union[int, _Text]] = ..., + const: Any = ..., + default: Any = ..., + type: Optional[Union[Callable[[str], _T], FileType]] = ..., + choices: Optional[Iterable[_T]] = ..., + required: bool = ..., + help: Optional[_Text] = ..., + metavar: Optional[Union[_Text, Tuple[_Text, ...]]] = ...) -> None: ... + def __call__(self, parser: ArgumentParser, namespace: Namespace, + values: Union[_Text, Sequence[Any], None], + option_string: Optional[_Text] = ...) -> None: ... + +class Namespace(_AttributeHolder): + def __init__(self, **kwargs: Any) -> None: ... + def __getattr__(self, name: _Text) -> Any: ... + def __setattr__(self, name: _Text, value: Any) -> None: ... + def __contains__(self, key: str) -> bool: ... + +class FileType: + # undocumented + _mode: _Text + _bufsize: int + if sys.version_info >= (3, 4): + _encoding: Optional[_Text] + _errors: Optional[_Text] + if sys.version_info >= (3, 4): + def __init__(self, mode: _Text = ..., bufsize: int = ..., + encoding: Optional[_Text] = ..., + errors: Optional[_Text] = ...) -> None: ... + elif sys.version_info >= (3,): + def __init__(self, + mode: _Text = ..., bufsize: int = ...) -> None: ... + else: + def __init__(self, + mode: _Text = ..., bufsize: Optional[int] = ...) -> None: ... + def __call__(self, string: _Text) -> IO[Any]: ... + +# undocumented +class _ArgumentGroup(_ActionsContainer): + title: Optional[_Text] + _group_actions: List[Action] + def __init__(self, container: _ActionsContainer, + title: Optional[_Text] = ..., + description: Optional[_Text] = ..., **kwargs: Any) -> None: ... + +# undocumented +class _MutuallyExclusiveGroup(_ArgumentGroup): + required: bool + _container: _ActionsContainer + def __init__(self, container: _ActionsContainer, required: bool = ...) -> None: ... + +# undocumented +class _StoreAction(Action): ... + +# undocumented +class _StoreConstAction(Action): + def __init__(self, + option_strings: Sequence[_Text], + dest: _Text, + const: Any, + default: Any = ..., + required: bool = ..., + help: Optional[_Text] = ..., + metavar: Optional[Union[_Text, Tuple[_Text, ...]]] = ...) -> None: ... + +# undocumented +class _StoreTrueAction(_StoreConstAction): + def __init__(self, + option_strings: Sequence[_Text], + dest: _Text, + default: bool = ..., + required: bool = ..., + help: Optional[_Text] = ...) -> None: ... + +# undocumented +class _StoreFalseAction(_StoreConstAction): + def __init__(self, + option_strings: Sequence[_Text], + dest: _Text, + default: bool = ..., + required: bool = ..., + help: Optional[_Text] = ...) -> None: ... + +# undocumented +class _AppendAction(Action): ... + +# undocumented +class _AppendConstAction(Action): + def __init__(self, + option_strings: Sequence[_Text], + dest: _Text, + const: Any, + default: Any = ..., + required: bool = ..., + help: Optional[_Text] = ..., + metavar: Optional[Union[_Text, Tuple[_Text, ...]]] = ...) -> None: ... + +# undocumented +class _CountAction(Action): + def __init__(self, + option_strings: Sequence[_Text], + dest: _Text, + default: Any = ..., + required: bool = ..., + help: Optional[_Text] = ...) -> None: ... + +# undocumented +class _HelpAction(Action): + def __init__(self, + option_strings: Sequence[_Text], + dest: _Text = ..., + default: _Text = ..., + help: Optional[_Text] = ...) -> None: ... + +# undocumented +class _VersionAction(Action): + version: Optional[_Text] + def __init__(self, + option_strings: Sequence[_Text], + version: Optional[_Text] = ..., + dest: _Text = ..., + default: _Text = ..., + help: _Text = ...) -> None: ... + +# undocumented +class _SubParsersAction(Action): + _ChoicesPseudoAction: Type[Any] # nested class + _prog_prefix: _Text + _parser_class: Type[ArgumentParser] + _name_parser_map: Dict[_Text, ArgumentParser] + choices: Dict[_Text, ArgumentParser] + _choices_actions: List[Action] + def __init__(self, + option_strings: Sequence[_Text], + prog: _Text, + parser_class: Type[ArgumentParser], + dest: _Text = ..., + required: bool = ..., + help: Optional[_Text] = ..., + metavar: Optional[Union[_Text, Tuple[_Text, ...]]] = ...) -> None: ... + # TODO: Type keyword args properly. + def add_parser(self, name: _Text, **kwargs: Any) -> ArgumentParser: ... + def _get_subactions(self) -> List[Action]: ... + +# undocumented +class ArgumentTypeError(Exception): ... + +if sys.version_info < (3, 7): + # undocumented + def _ensure_value(namespace: Namespace, name: _Text, value: Any) -> Any: ... + +# undocumented +def _get_action_name(argument: Optional[Action]) -> Optional[str]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/array.pyi b/client/typeshed-fallback/stdlib/2and3/array.pyi new file mode 100644 index 000000000..84e7e5ef4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/array.pyi @@ -0,0 +1,73 @@ +# Stubs for array + +# Based on http://docs.python.org/3.6/library/array.html + +import sys +from typing import (Any, BinaryIO, Generic, Iterable, Iterator, List, MutableSequence, + overload, Text, Tuple, TypeVar, Union) + +_T = TypeVar('_T', int, float, Text) + +if sys.version_info >= (3,): + typecodes = ... # type: str + +class array(MutableSequence[_T], Generic[_T]): + typecode = ... # type: str + itemsize = ... # type: int + def __init__(self, typecode: str, + __initializer: Union[bytes, Iterable[_T]] = ...) -> None: ... + def append(self, x: _T) -> None: ... + def buffer_info(self) -> Tuple[int, int]: ... + def byteswap(self) -> None: ... + def count(self, x: Any) -> int: ... + def extend(self, iterable: Iterable[_T]) -> None: ... + if sys.version_info >= (3, 2): + def frombytes(self, s: bytes) -> None: ... + def fromfile(self, f: BinaryIO, n: int) -> None: ... + def fromlist(self, list: List[_T]) -> None: ... + def fromstring(self, s: bytes) -> None: ... + def fromunicode(self, s: str) -> None: ... + def index(self, x: _T) -> int: ... # type: ignore # Overrides Sequence + def insert(self, i: int, x: _T) -> None: ... + def pop(self, i: int = ...) -> _T: ... + if sys.version_info < (3,): + def read(self, f: BinaryIO, n: int) -> None: ... + def remove(self, x: Any) -> None: ... + def reverse(self) -> None: ... + if sys.version_info >= (3, 2): + def tobytes(self) -> bytes: ... + def tofile(self, f: BinaryIO) -> None: ... + def tolist(self) -> List[_T]: ... + def tostring(self) -> bytes: ... + def tounicode(self) -> str: ... + if sys.version_info < (3,): + def write(self, f: BinaryIO) -> None: ... + + def __len__(self) -> int: ... + + @overload + def __getitem__(self, i: int) -> _T: ... + @overload + def __getitem__(self, s: slice) -> array[_T]: ... + + @overload # type: ignore # Overrides MutableSequence + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + def __setitem__(self, s: slice, o: array[_T]) -> None: ... + + def __delitem__(self, i: Union[int, slice]) -> None: ... + def __add__(self, x: array[_T]) -> array[_T]: ... + def __ge__(self, other: array[_T]) -> bool: ... + def __gt__(self, other: array[_T]) -> bool: ... + def __iadd__(self, x: array[_T]) -> array[_T]: ... # type: ignore # Overrides MutableSequence + def __imul__(self, n: int) -> array[_T]: ... + def __le__(self, other: array[_T]) -> bool: ... + def __lt__(self, other: array[_T]) -> bool: ... + def __mul__(self, n: int) -> array[_T]: ... + def __rmul__(self, n: int) -> array[_T]: ... + if sys.version_info < (3,): + def __delslice__(self, i: int, j: int) -> None: ... + def __getslice__(self, i: int, j: int) -> array[_T]: ... + def __setslice__(self, i: int, j: int, y: array[_T]) -> None: ... + +ArrayType = array diff --git a/client/typeshed-fallback/stdlib/2and3/asynchat.pyi b/client/typeshed-fallback/stdlib/2and3/asynchat.pyi new file mode 100644 index 000000000..0e6ca7eb8 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/asynchat.pyi @@ -0,0 +1,41 @@ +from abc import abstractmethod +import asyncore +import socket +import sys +from typing import Optional, Sequence, Tuple, Union + + +class simple_producer: + def __init__(self, data: bytes, buffer_size: int = ...) -> None: ... + def more(self) -> bytes: ... + +class async_chat(asyncore.dispatcher): + ac_in_buffer_size = ... # type: int + ac_out_buffer_size = ... # type: int + def __init__(self, sock: Optional[socket.socket] = ..., map: Optional[asyncore._maptype] = ...) -> None: ... + + @abstractmethod + def collect_incoming_data(self, data: bytes) -> None: ... + @abstractmethod + def found_terminator(self) -> None: ... + def set_terminator(self, term: Union[bytes, int, None]) -> None: ... + def get_terminator(self) -> Union[bytes, int, None]: ... + def handle_read(self) -> None: ... + def handle_write(self) -> None: ... + def handle_close(self) -> None: ... + def push(self, data: bytes) -> None: ... + def push_with_producer(self, producer: simple_producer) -> None: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def close_when_done(self) -> None: ... + def initiate_send(self) -> None: ... + def discard_buffers(self) -> None: ... + +if sys.version_info < (3, 0): + class fifo: + def __init__(self, list: Sequence[Union[bytes, simple_producer]] = ...) -> None: ... + def __len__(self) -> int: ... + def is_empty(self) -> bool: ... + def first(self) -> bytes: ... + def push(self, data: Union[bytes, simple_producer]) -> None: ... + def pop(self) -> Tuple[int, bytes]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/asyncore.pyi b/client/typeshed-fallback/stdlib/2and3/asyncore.pyi new file mode 100644 index 000000000..a5126ccb3 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/asyncore.pyi @@ -0,0 +1,144 @@ +from typing import Tuple, Union, Optional, Any, Dict, overload + +import os +import select +import sys +import time +import warnings +from socket import SocketType +from typing import Optional + +from errno import (EALREADY, EINPROGRESS, EWOULDBLOCK, ECONNRESET, EINVAL, + ENOTCONN, ESHUTDOWN, EINTR, EISCONN, EBADF, ECONNABORTED, + EPIPE, EAGAIN, errorcode) + +# cyclic dependence with asynchat +_maptype = Dict[str, Any] + + +class ExitNow(Exception): ... + +def read(obj: Any) -> None: ... +def write(obj: Any) -> None: ... +def readwrite(obj: Any, flags: int) -> None: ... +def poll(timeout: float = ..., map: _maptype = ...) -> None: ... +def poll2(timeout: float = ..., map: _maptype = ...) -> None: ... + +poll3 = poll2 + +def loop(timeout: float = ..., use_poll: bool = ..., map: _maptype = ..., count: Optional[int] = ...) -> None: ... + + +# Not really subclass of socket.socket; it's only delegation. +# It is not covariant to it. +class dispatcher: + + debug = ... # type: bool + connected = ... # type: bool + accepting = ... # type: bool + connecting = ... # type: bool + closing = ... # type: bool + ignore_log_types = ... # type: frozenset[str] + socket = ... # type: Optional[SocketType] # undocumented + + def __init__(self, sock: Optional[SocketType] = ..., map: _maptype = ...) -> None: ... + def add_channel(self, map: _maptype = ...) -> None: ... + def del_channel(self, map: _maptype = ...) -> None: ... + def create_socket(self, family: int, type: int) -> None: ... + def set_socket(self, sock: SocketType, map: _maptype = ...) -> None: ... + def set_reuse_addr(self) -> None: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def listen(self, backlog: int) -> None: ... + def bind(self, address: Union[tuple, str]) -> None: ... + def connect(self, address: Union[tuple, str]) -> None: ... + def accept(self) -> Optional[Tuple[SocketType, Any]]: ... + def send(self, data: bytes) -> int: ... + def recv(self, buffer_size: int) -> bytes: ... + def close(self) -> None: ... + + def log(self, message: Any) -> None: ... + def log_info(self, message: Any, type: str = ...) -> None: ... + def handle_read_event(self) -> None: ... + def handle_connect_event(self) -> None: ... + def handle_write_event(self) -> None: ... + def handle_expt_event(self) -> None: ... + def handle_error(self) -> None: ... + def handle_expt(self) -> None: ... + def handle_read(self) -> None: ... + def handle_write(self) -> None: ... + def handle_connect(self) -> None: ... + def handle_accept(self) -> None: ... + def handle_close(self) -> None: ... + + if sys.version_info < (3, 5): + # Historically, some methods were "imported" from `self.socket` by + # means of `__getattr__`. This was long deprecated, and as of Python + # 3.5 has been removed; simply call the relevant methods directly on + # self.socket if necessary. + + def detach(self) -> int: ... + def fileno(self) -> int: ... + + # return value is an address + def getpeername(self) -> Any: ... + def getsockname(self) -> Any: ... + + @overload + def getsockopt(self, level: int, optname: int) -> int: ... + @overload + def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... + + def gettimeout(self) -> float: ... + def ioctl(self, control: object, + option: Tuple[int, int, int]) -> None: ... + # TODO the return value may be BinaryIO or TextIO, depending on mode + def makefile(self, mode: str = ..., buffering: int = ..., + encoding: str = ..., errors: str = ..., + newline: str = ...) -> Any: + ... + + # return type is an address + def recvfrom(self, bufsize: int, flags: int = ...) -> Any: ... + def recvfrom_into(self, buffer: bytes, nbytes: int, flags: int = ...) -> Any: ... + def recv_into(self, buffer: bytes, nbytes: int, flags: int = ...) -> Any: ... + def sendall(self, data: bytes, flags: int = ...) -> None: ... + def sendto(self, data: bytes, address: Union[tuple, str], flags: int = ...) -> int: ... + def setblocking(self, flag: bool) -> None: ... + def settimeout(self, value: Union[float, None]) -> None: ... + def setsockopt(self, level: int, optname: int, value: Union[int, bytes]) -> None: ... + def shutdown(self, how: int) -> None: ... + +class dispatcher_with_send(dispatcher): + def __init__(self, sock: SocketType = ..., map: _maptype = ...) -> None: ... + def initiate_send(self) -> None: ... + def handle_write(self) -> None: ... + # incompatible signature: + # def send(self, data: bytes) -> Optional[int]: ... + +def compact_traceback() -> Tuple[Tuple[str, str, str], type, type, str]: ... +def close_all(map: _maptype = ..., ignore_all: bool = ...) -> None: ... + +# if os.name == 'posix': +# import fcntl +class file_wrapper: + fd = ... # type: int + + def __init__(self, fd: int) -> None: ... + def recv(self, bufsize: int, flags: int = ...) -> bytes: ... + def send(self, data: bytes, flags: int = ...) -> int: ... + + @overload + def getsockopt(self, level: int, optname: int) -> int: ... + @overload + def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... + + def read(self, bufsize: int, flags: int = ...) -> bytes: ... + def write(self, data: bytes, flags: int = ...) -> int: ... + + def close(self) -> None: ... + def fileno(self) -> int: ... + +class file_dispatcher(dispatcher): + def __init__(self, fd: int, map: _maptype = ...) -> None: ... + def set_file(self, fd: int) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/base64.pyi b/client/typeshed-fallback/stdlib/2and3/base64.pyi new file mode 100644 index 000000000..7c648c8b5 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/base64.pyi @@ -0,0 +1,38 @@ +# Stubs for base64 + +from typing import IO, Union, Text +import sys + +if sys.version_info < (3,): + _encodable = Union[bytes, unicode] + _decodable = Union[bytes, unicode] +else: + _encodable = bytes + _decodable = Union[bytes, str] + +def b64encode(s: _encodable, altchars: bytes = ...) -> bytes: ... +def b64decode(s: _decodable, altchars: bytes = ..., + validate: bool = ...) -> bytes: ... +def standard_b64encode(s: _encodable) -> bytes: ... +def standard_b64decode(s: _decodable) -> bytes: ... +def urlsafe_b64encode(s: _encodable) -> bytes: ... +def urlsafe_b64decode(s: _decodable) -> bytes: ... +def b32encode(s: _encodable) -> bytes: ... +def b32decode(s: _decodable, casefold: bool = ..., + map01: bytes = ...) -> bytes: ... +def b16encode(s: _encodable) -> bytes: ... +def b16decode(s: _decodable, casefold: bool = ...) -> bytes: ... +if sys.version_info >= (3, 4): + def a85encode(b: _encodable, *, foldspaces: bool = ..., wrapcol: int = ..., + pad: bool = ..., adobe: bool = ...) -> bytes: ... + def a85decode(b: _decodable, *, foldspaces: bool = ..., + adobe: bool = ..., ignorechars: Union[str, bytes] = ...) -> bytes: ... + def b85encode(b: _encodable, pad: bool = ...) -> bytes: ... + def b85decode(b: _decodable) -> bytes: ... + +def decode(input: IO[bytes], output: IO[bytes]) -> None: ... +def decodebytes(s: bytes) -> bytes: ... +def decodestring(s: bytes) -> bytes: ... +def encode(input: IO[bytes], output: IO[bytes]) -> None: ... +def encodebytes(s: bytes) -> bytes: ... +def encodestring(s: bytes) -> bytes: ... diff --git a/client/typeshed-fallback/stdlib/2and3/binascii.pyi b/client/typeshed-fallback/stdlib/2and3/binascii.pyi new file mode 100644 index 000000000..9689b712b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/binascii.pyi @@ -0,0 +1,47 @@ +# Stubs for binascii + +# Based on http://docs.python.org/3.2/library/binascii.html + +import sys +from typing import Union, Text + + +if sys.version_info < (3,): + # Python 2 accepts unicode ascii pretty much everywhere. + _Bytes = Union[bytes, Text] + _Ascii = Union[bytes, Text] +elif sys.version_info < (3, 3): + # Python 3.2 and below only accepts bytes. + _Bytes = bytes + _Ascii = bytes +else: + # But since Python 3.3 ASCII-only unicode strings are accepted by the + # a2b_* functions. + _Bytes = bytes + _Ascii = Union[bytes, Text] + +def a2b_uu(string: _Ascii) -> bytes: ... +if sys.version_info >= (3, 7): + def b2a_uu(data: _Bytes, *, backtick: bool = ...) -> bytes: ... +else: + def b2a_uu(data: _Bytes) -> bytes: ... +def a2b_base64(string: _Ascii) -> bytes: ... +if sys.version_info >= (3, 6): + def b2a_base64(data: _Bytes, *, newline: bool = ...) -> bytes: ... +else: + def b2a_base64(data: _Bytes) -> bytes: ... +def a2b_qp(string: _Ascii, header: bool = ...) -> bytes: ... +def b2a_qp(data: _Bytes, quotetabs: bool = ..., istext: bool = ..., header: bool = ...) -> bytes: ... +def a2b_hqx(string: _Ascii) -> bytes: ... +def rledecode_hqx(data: _Bytes) -> bytes: ... +def rlecode_hqx(data: _Bytes) -> bytes: ... +def b2a_hqx(data: _Bytes) -> bytes: ... +def crc_hqx(data: _Bytes, crc: int) -> int: ... +def crc32(data: _Bytes, crc: int = ...) -> int: ... +def b2a_hex(data: _Bytes) -> bytes: ... +def hexlify(data: _Bytes) -> bytes: ... +def a2b_hex(hexstr: _Ascii) -> bytes: ... +def unhexlify(hexlify: _Ascii) -> bytes: ... + +class Error(Exception): ... +class Incomplete(Exception): ... diff --git a/client/typeshed-fallback/stdlib/2and3/binhex.pyi b/client/typeshed-fallback/stdlib/2and3/binhex.pyi new file mode 100644 index 000000000..40ead7668 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/binhex.pyi @@ -0,0 +1,48 @@ +from typing import ( + Any, + IO, + Tuple, + Union, +) + + +class Error(Exception): ... + +REASONABLY_LARGE = ... # type: int +LINELEN = ... # type: int +RUNCHAR = ... # type: bytes + +class FInfo: + def __init__(self) -> None: ... + Type = ... # type: str + Creator = ... # type: str + Flags = ... # type: int + +_FileInfoTuple = Tuple[str, FInfo, int, int] +_FileHandleUnion = Union[str, IO[bytes]] + +def getfileinfo(name: str) -> _FileInfoTuple: ... + +class openrsrc: + def __init__(self, *args: Any) -> None: ... + def read(self, *args: Any) -> bytes: ... + def write(self, *args: Any) -> None: ... + def close(self) -> None: ... + +class BinHex: + def __init__(self, name_finfo_dlen_rlen: _FileInfoTuple, ofp: _FileHandleUnion) -> None: ... + def write(self, data: bytes) -> None: ... + def close_data(self) -> None: ... + def write_rsrc(self, data: bytes) -> None: ... + def close(self) -> None: ... + +def binhex(inp: str, out: str) -> None: ... + +class HexBin: + def __init__(self, ifp: _FileHandleUnion) -> None: ... + def read(self, *n: int) -> bytes: ... + def close_data(self) -> None: ... + def read_rsrc(self, *n: int) -> bytes: ... + def close(self) -> None: ... + +def hexbin(inp: str, out: str) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/bisect.pyi b/client/typeshed-fallback/stdlib/2and3/bisect.pyi new file mode 100644 index 000000000..5c541124a --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/bisect.pyi @@ -0,0 +1,22 @@ +# Stubs for bisect + +from typing import Any, Sequence, TypeVar + +_T = TypeVar('_T') + +# TODO uncomment when mypy# 2035 is fixed +# def bisect_left(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> int: ... +# def bisect_right(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> int: ... +# def bisect(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> int: ... +# +# def insort_left(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> int: ... +# def insort_right(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> int: ... +# def insort(a: Sequence[_T], x: _T, lo: int = ..., hi: int = ...) -> int: ... + +def bisect_left(a: Sequence, x: Any, lo: int = ..., hi: int = ...) -> int: ... +def bisect_right(a: Sequence, x: Any, lo: int = ..., hi: int = ...) -> int: ... +def bisect(a: Sequence, x: Any, lo: int = ..., hi: int = ...) -> int: ... + +def insort_left(a: Sequence, x: Any, lo: int = ..., hi: int = ...) -> int: ... +def insort_right(a: Sequence, x: Any, lo: int = ..., hi: int = ...) -> int: ... +def insort(a: Sequence, x: Any, lo: int = ..., hi: int = ...) -> int: ... diff --git a/client/typeshed-fallback/stdlib/2and3/builtins.pyi b/client/typeshed-fallback/stdlib/2and3/builtins.pyi new file mode 100644 index 000000000..db00c557e --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/builtins.pyi @@ -0,0 +1,1611 @@ +# True and False are deliberately omitted because they are keywords in +# Python 3, and stub files conform to Python 3 syntax. + +from typing import ( + TypeVar, Iterator, Iterable, NoReturn, overload, Container, + Sequence, MutableSequence, Mapping, MutableMapping, Tuple, List, Any, Dict, Callable, Generic, + Set, AbstractSet, FrozenSet, MutableSet, Sized, Reversible, SupportsInt, SupportsFloat, SupportsAbs, + SupportsComplex, SupportsRound, IO, BinaryIO, Union, + ItemsView, KeysView, ValuesView, ByteString, Optional, AnyStr, Type, Text, +) +from abc import abstractmethod, ABCMeta +from ast import mod +from types import TracebackType, CodeType +import sys + +if sys.version_info >= (3,): + from typing import SupportsBytes + +_T = TypeVar('_T') +_T_co = TypeVar('_T_co', covariant=True) +_KT = TypeVar('_KT') +_VT = TypeVar('_VT') +_S = TypeVar('_S') +_T1 = TypeVar('_T1') +_T2 = TypeVar('_T2') +_T3 = TypeVar('_T3') +_T4 = TypeVar('_T4') +_T5 = TypeVar('_T5') +_TT = TypeVar('_TT', bound='type') + +class object: + __doc__: Optional[str] + __dict__: Dict[str, Any] + __slots__: Union[Text, Iterable[Text]] + __module__: str + if sys.version_info >= (3, 6): + __annotations__: Dict[str, Any] + + @property + def __class__(self: _T) -> Type[_T]: ... + @__class__.setter + def __class__(self, __type: Type[object]) -> None: ... + def __init__(self) -> None: ... + def __new__(cls) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __eq__(self, o: object) -> bool: ... + def __ne__(self, o: object) -> bool: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __hash__(self) -> int: ... + def __format__(self, format_spec: str) -> str: ... + def __getattribute__(self, name: str) -> Any: ... + def __delattr__(self, name: str) -> None: ... + def __sizeof__(self) -> int: ... + def __reduce__(self) -> tuple: ... + def __reduce_ex__(self, protocol: int) -> tuple: ... + if sys.version_info >= (3,): + def __dir__(self) -> Iterable[str]: ... + if sys.version_info >= (3, 6): + def __init_subclass__(cls) -> None: ... + +class staticmethod(object): # Special, only valid as a decorator. + __func__: Callable + if sys.version_info >= (3,): + __isabstractmethod__: bool + + def __init__(self, f: Callable) -> None: ... + def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable: ... + +class classmethod(object): # Special, only valid as a decorator. + __func__: Callable + if sys.version_info >= (3,): + __isabstractmethod__: bool + + def __init__(self, f: Callable) -> None: ... + def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __get__(self, obj: _T, type: Optional[Type[_T]] = ...) -> Callable: ... + +class type(object): + __base__: type + __bases__: Tuple[type, ...] + __basicsize__: int + __dict__: Dict[str, Any] + __dictoffset__: int + __flags__: int + __itemsize__: int + __module__: str + __mro__: Tuple[type, ...] + __name__: str + if sys.version_info >= (3,): + __qualname__: str + __text_signature__: Optional[str] + __weakrefoffset__: int + + @overload + def __init__(self, o: object) -> None: ... + @overload + def __init__(self, name: str, bases: Tuple[type, ...], dict: Dict[str, Any]) -> None: ... + @overload + def __new__(cls, o: object) -> type: ... + @overload + def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ... + def __call__(self, *args: Any, **kwds: Any) -> Any: ... + def __subclasses__(self: _TT) -> List[_TT]: ... + # Note: the documentation doesnt specify what the return type is, the standard + # implementation seems to be returning a list. + def mro(self) -> List[type]: ... + def __instancecheck__(self, instance: Any) -> bool: ... + def __subclasscheck__(self, subclass: type) -> bool: ... + if sys.version_info >= (3,): + @classmethod + def __prepare__(metacls, __name: str, __bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, Any]: ... + +class super(object): + if sys.version_info >= (3,): + @overload + def __init__(self, t: Any, obj: Any) -> None: ... + @overload + def __init__(self, t: Any) -> None: ... + @overload + def __init__(self) -> None: ... + else: + @overload + def __init__(self, t: Any, obj: Any) -> None: ... + @overload + def __init__(self, t: Any) -> None: ... + +class int: + @overload + def __init__(self, x: Union[Text, bytes, SupportsInt] = ...) -> None: ... + @overload + def __init__(self, x: Union[Text, bytes, bytearray], base: int) -> None: ... + + @property + def real(self) -> int: ... + @property + def imag(self) -> int: ... + @property + def numerator(self) -> int: ... + @property + def denominator(self) -> int: ... + def conjugate(self) -> int: ... + + def bit_length(self) -> int: ... + if sys.version_info >= (3,): + def to_bytes(self, length: int, byteorder: str, *, signed: bool = ...) -> bytes: ... + @classmethod + def from_bytes(cls, bytes: Sequence[int], byteorder: str, *, + signed: bool = ...) -> int: ... # TODO buffer object argument + + def __add__(self, x: int) -> int: ... + def __sub__(self, x: int) -> int: ... + def __mul__(self, x: int) -> int: ... + def __floordiv__(self, x: int) -> int: ... + if sys.version_info < (3,): + def __div__(self, x: int) -> int: ... + def __truediv__(self, x: int) -> float: ... + def __mod__(self, x: int) -> int: ... + def __divmod__(self, x: int) -> Tuple[int, int]: ... + def __radd__(self, x: int) -> int: ... + def __rsub__(self, x: int) -> int: ... + def __rmul__(self, x: int) -> int: ... + def __rfloordiv__(self, x: int) -> int: ... + if sys.version_info < (3,): + def __rdiv__(self, x: int) -> int: ... + def __rtruediv__(self, x: int) -> float: ... + def __rmod__(self, x: int) -> int: ... + def __rdivmod__(self, x: int) -> Tuple[int, int]: ... + def __pow__(self, x: int) -> Any: ... # Return type can be int or float, depending on x. + def __rpow__(self, x: int) -> Any: ... + def __and__(self, n: int) -> int: ... + def __or__(self, n: int) -> int: ... + def __xor__(self, n: int) -> int: ... + def __lshift__(self, n: int) -> int: ... + def __rshift__(self, n: int) -> int: ... + def __rand__(self, n: int) -> int: ... + def __ror__(self, n: int) -> int: ... + def __rxor__(self, n: int) -> int: ... + def __rlshift__(self, n: int) -> int: ... + def __rrshift__(self, n: int) -> int: ... + def __neg__(self) -> int: ... + def __pos__(self) -> int: ... + def __invert__(self) -> int: ... + if sys.version_info >= (3,): + def __round__(self, ndigits: Optional[int] = ...) -> int: ... + def __getnewargs__(self) -> Tuple[int]: ... + + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: int) -> bool: ... + def __le__(self, x: int) -> bool: ... + def __gt__(self, x: int) -> bool: ... + def __ge__(self, x: int) -> bool: ... + + def __str__(self) -> str: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + def __abs__(self) -> int: ... + def __hash__(self) -> int: ... + if sys.version_info >= (3,): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + def __index__(self) -> int: ... + +class float: + def __init__(self, x: Union[SupportsFloat, Text, bytes, bytearray] = ...) -> None: ... + def as_integer_ratio(self) -> Tuple[int, int]: ... + def hex(self) -> str: ... + def is_integer(self) -> bool: ... + @classmethod + def fromhex(cls, s: str) -> float: ... + + @property + def real(self) -> float: ... + @property + def imag(self) -> float: ... + def conjugate(self) -> float: ... + + def __add__(self, x: float) -> float: ... + def __sub__(self, x: float) -> float: ... + def __mul__(self, x: float) -> float: ... + def __floordiv__(self, x: float) -> float: ... + if sys.version_info < (3,): + def __div__(self, x: float) -> float: ... + def __truediv__(self, x: float) -> float: ... + def __mod__(self, x: float) -> float: ... + def __divmod__(self, x: float) -> Tuple[float, float]: ... + def __pow__(self, x: float) -> float: ... # In Python 3, returns complex if self is negative and x is not whole + def __radd__(self, x: float) -> float: ... + def __rsub__(self, x: float) -> float: ... + def __rmul__(self, x: float) -> float: ... + def __rfloordiv__(self, x: float) -> float: ... + if sys.version_info < (3,): + def __rdiv__(self, x: float) -> float: ... + def __rtruediv__(self, x: float) -> float: ... + def __rmod__(self, x: float) -> float: ... + def __rdivmod__(self, x: float) -> Tuple[float, float]: ... + def __rpow__(self, x: float) -> float: ... + def __getnewargs__(self) -> Tuple[float]: ... + if sys.version_info >= (3,): + @overload + def __round__(self) -> int: ... + @overload + def __round__(self, ndigits: None) -> int: ... + @overload + def __round__(self, ndigits: int) -> float: ... + + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: float) -> bool: ... + def __le__(self, x: float) -> bool: ... + def __gt__(self, x: float) -> bool: ... + def __ge__(self, x: float) -> bool: ... + def __neg__(self) -> float: ... + def __pos__(self) -> float: ... + + def __str__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __abs__(self) -> float: ... + def __hash__(self) -> int: ... + if sys.version_info >= (3,): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + +class complex: + @overload + def __init__(self, re: float = ..., im: float = ...) -> None: ... + @overload + def __init__(self, s: str) -> None: ... + @overload + def __init__(self, s: SupportsComplex) -> None: ... + + @property + def real(self) -> float: ... + @property + def imag(self) -> float: ... + + def conjugate(self) -> complex: ... + + def __add__(self, x: complex) -> complex: ... + def __sub__(self, x: complex) -> complex: ... + def __mul__(self, x: complex) -> complex: ... + def __pow__(self, x: complex) -> complex: ... + if sys.version_info < (3,): + def __div__(self, x: complex) -> complex: ... + def __truediv__(self, x: complex) -> complex: ... + def __radd__(self, x: complex) -> complex: ... + def __rsub__(self, x: complex) -> complex: ... + def __rmul__(self, x: complex) -> complex: ... + def __rpow__(self, x: complex) -> complex: ... + if sys.version_info < (3,): + def __rdiv__(self, x: complex) -> complex: ... + def __rtruediv__(self, x: complex) -> complex: ... + + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __neg__(self) -> complex: ... + def __pos__(self) -> complex: ... + + def __str__(self) -> str: ... + def __complex__(self) -> complex: ... + def __abs__(self) -> float: ... + def __hash__(self) -> int: ... + if sys.version_info >= (3,): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + +if sys.version_info >= (3,): + _str_base = object +else: + class basestring(metaclass=ABCMeta): ... + + class unicode(basestring, Sequence[unicode]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, o: object) -> None: ... + @overload + def __init__(self, o: str, encoding: unicode = ..., errors: unicode = ...) -> None: ... + def capitalize(self) -> unicode: ... + def center(self, width: int, fillchar: unicode = ...) -> unicode: ... + def count(self, x: unicode) -> int: ... + def decode(self, encoding: unicode = ..., errors: unicode = ...) -> unicode: ... + def encode(self, encoding: unicode = ..., errors: unicode = ...) -> str: ... + def endswith(self, suffix: Union[unicode, Tuple[unicode, ...]], start: int = ..., + end: int = ...) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> unicode: ... + def find(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def format(self, *args: Any, **kwargs: Any) -> unicode: ... + def format_map(self, map: Mapping[unicode, Any]) -> unicode: ... + def index(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + def isidentifier(self) -> bool: ... + def islower(self) -> bool: ... + def isnumeric(self) -> bool: ... + def isprintable(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, iterable: Iterable[unicode]) -> unicode: ... + def ljust(self, width: int, fillchar: unicode = ...) -> unicode: ... + def lower(self) -> unicode: ... + def lstrip(self, chars: unicode = ...) -> unicode: ... + def partition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def replace(self, old: unicode, new: unicode, count: int = ...) -> unicode: ... + def rfind(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def rindex(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... + def rjust(self, width: int, fillchar: unicode = ...) -> unicode: ... + def rpartition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def rsplit(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... + def rstrip(self, chars: unicode = ...) -> unicode: ... + def split(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... + def splitlines(self, keepends: bool = ...) -> List[unicode]: ... + def startswith(self, prefix: Union[unicode, Tuple[unicode, ...]], start: int = ..., + end: int = ...) -> bool: ... + def strip(self, chars: unicode = ...) -> unicode: ... + def swapcase(self) -> unicode: ... + def title(self) -> unicode: ... + def translate(self, table: Union[Dict[int, Any], unicode]) -> unicode: ... + def upper(self) -> unicode: ... + def zfill(self, width: int) -> unicode: ... + + @overload + def __getitem__(self, i: int) -> unicode: ... + @overload + def __getitem__(self, s: slice) -> unicode: ... + def __getslice__(self, start: int, stop: int) -> unicode: ... + def __add__(self, s: unicode) -> unicode: ... + def __mul__(self, n: int) -> unicode: ... + def __rmul__(self, n: int) -> unicode: ... + def __mod__(self, x: Any) -> unicode: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: unicode) -> bool: ... + def __le__(self, x: unicode) -> bool: ... + def __gt__(self, x: unicode) -> bool: ... + def __ge__(self, x: unicode) -> bool: ... + + def __len__(self) -> int: ... + def __contains__(self, s: object) -> bool: ... + def __iter__(self) -> Iterator[unicode]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __hash__(self) -> int: ... + def __getnewargs__(self) -> Tuple[unicode]: ... + + _str_base = basestring + +class str(Sequence[str], _str_base): + if sys.version_info >= (3,): + @overload + def __init__(self, o: object = ...) -> None: ... + @overload + def __init__(self, o: bytes, encoding: str = ..., errors: str = ...) -> None: ... + else: + def __init__(self, o: object = ...) -> None: ... + + def capitalize(self) -> str: ... + if sys.version_info >= (3, 3): + def casefold(self) -> str: ... + def center(self, width: int, fillchar: str = ...) -> str: ... + def count(self, x: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + if sys.version_info < (3,): + def decode(self, encoding: Text = ..., errors: Text = ...) -> unicode: ... + def encode(self, encoding: Text = ..., errors: Text = ...) -> bytes: ... + if sys.version_info >= (3,): + def endswith(self, suffix: Union[Text, Tuple[Text, ...]], start: Optional[int] = ..., + end: Optional[int] = ...) -> bool: ... + else: + def endswith(self, suffix: Union[Text, Tuple[Text, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> str: ... + def find(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def format(self, *args: Any, **kwargs: Any) -> str: ... + if sys.version_info >= (3,): + def format_map(self, map: Mapping[str, Any]) -> str: ... + def index(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + if sys.version_info >= (3, 7): + def isascii(self) -> bool: ... + if sys.version_info >= (3,): + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + if sys.version_info >= (3,): + def isidentifier(self) -> bool: ... + def islower(self) -> bool: ... + if sys.version_info >= (3,): + def isnumeric(self) -> bool: ... + def isprintable(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + if sys.version_info >= (3,): + def join(self, iterable: Iterable[str]) -> str: ... + else: + def join(self, iterable: Iterable[AnyStr]) -> AnyStr: ... + def ljust(self, width: int, fillchar: str = ...) -> str: ... + def lower(self) -> str: ... + if sys.version_info >= (3,): + def lstrip(self, chars: Optional[str] = ...) -> str: ... + def partition(self, sep: str) -> Tuple[str, str, str]: ... + def replace(self, old: str, new: str, count: int = ...) -> str: ... + else: + @overload + def lstrip(self, chars: str = ...) -> str: ... + @overload + def lstrip(self, chars: unicode) -> unicode: ... + @overload + def partition(self, sep: bytearray) -> Tuple[str, bytearray, str]: ... + @overload + def partition(self, sep: str) -> Tuple[str, str, str]: ... + @overload + def partition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def replace(self, old: AnyStr, new: AnyStr, count: int = ...) -> AnyStr: ... + def rfind(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rindex(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rjust(self, width: int, fillchar: str = ...) -> str: ... + if sys.version_info >= (3,): + def rpartition(self, sep: str) -> Tuple[str, str, str]: ... + def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + def rstrip(self, chars: Optional[str] = ...) -> str: ... + def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + else: + @overload + def rpartition(self, sep: bytearray) -> Tuple[str, bytearray, str]: ... + @overload + def rpartition(self, sep: str) -> Tuple[str, str, str]: ... + @overload + def rpartition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + @overload + def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + @overload + def rsplit(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... + @overload + def rstrip(self, chars: str = ...) -> str: ... + @overload + def rstrip(self, chars: unicode) -> unicode: ... + @overload + def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + @overload + def split(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... + def splitlines(self, keepends: bool = ...) -> List[str]: ... + if sys.version_info >= (3,): + def startswith(self, prefix: Union[Text, Tuple[Text, ...]], start: Optional[int] = ..., + end: Optional[int] = ...) -> bool: ... + def strip(self, chars: Optional[str] = ...) -> str: ... + else: + def startswith(self, prefix: Union[Text, Tuple[Text, ...]]) -> bool: ... + @overload + def strip(self, chars: str = ...) -> str: ... + @overload + def strip(self, chars: unicode) -> unicode: ... + def swapcase(self) -> str: ... + def title(self) -> str: ... + if sys.version_info >= (3,): + def translate(self, table: Union[Mapping[int, Union[int, str, None]], Sequence[Union[int, str, None]]]) -> str: ... + else: + def translate(self, table: Optional[AnyStr], deletechars: AnyStr = ...) -> AnyStr: ... + def upper(self) -> str: ... + def zfill(self, width: int) -> str: ... + if sys.version_info >= (3,): + @staticmethod + @overload + def maketrans(x: Union[Dict[int, _T], Dict[str, _T], Dict[Union[str, int], _T]]) -> Dict[int, _T]: ... + @staticmethod + @overload + def maketrans(x: str, y: str, z: str = ...) -> Dict[int, Union[int, None]]: ... + + if sys.version_info >= (3,): + def __add__(self, s: str) -> str: ... + else: + def __add__(self, s: AnyStr) -> AnyStr: ... + def __contains__(self, o: object) -> bool: ... + def __eq__(self, x: object) -> bool: ... + def __ge__(self, x: Text) -> bool: ... + def __getitem__(self, i: Union[int, slice]) -> str: ... + def __gt__(self, x: Text) -> bool: ... + def __hash__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + def __le__(self, x: Text) -> bool: ... + def __len__(self) -> int: ... + def __lt__(self, x: Text) -> bool: ... + def __mod__(self, x: Any) -> str: ... + def __mul__(self, n: int) -> str: ... + def __ne__(self, x: object) -> bool: ... + def __repr__(self) -> str: ... + def __rmul__(self, n: int) -> str: ... + def __str__(self) -> str: ... + def __getnewargs__(self) -> Tuple[str]: ... + + if sys.version_info < (3,): + def __getslice__(self, start: int, stop: int) -> str: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + +if sys.version_info >= (3,): + class bytes(ByteString): + @overload + def __init__(self, ints: Iterable[int]) -> None: ... + @overload + def __init__(self, string: str, encoding: str, + errors: str = ...) -> None: ... + @overload + def __init__(self, length: int) -> None: ... + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, o: SupportsBytes) -> None: ... + def capitalize(self) -> bytes: ... + def center(self, width: int, fillchar: bytes = ...) -> bytes: ... + def count(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def decode(self, encoding: str = ..., errors: str = ...) -> str: ... + def endswith(self, suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> bytes: ... + def find(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + if sys.version_info >= (3, 5): + def hex(self) -> str: ... + def index(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + if sys.version_info >= (3, 7): + def isascii(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, iterable: Iterable[Union[ByteString, memoryview]]) -> bytes: ... + def ljust(self, width: int, fillchar: bytes = ...) -> bytes: ... + def lower(self) -> bytes: ... + def lstrip(self, chars: Optional[bytes] = ...) -> bytes: ... + def partition(self, sep: bytes) -> Tuple[bytes, bytes, bytes]: ... + def replace(self, old: bytes, new: bytes, count: int = ...) -> bytes: ... + def rfind(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def rindex(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def rjust(self, width: int, fillchar: bytes = ...) -> bytes: ... + def rpartition(self, sep: bytes) -> Tuple[bytes, bytes, bytes]: ... + def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... + def rstrip(self, chars: Optional[bytes] = ...) -> bytes: ... + def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... + def splitlines(self, keepends: bool = ...) -> List[bytes]: ... + def startswith( + self, + prefix: Union[bytes, Tuple[bytes, ...]], + start: Optional[int] = ..., + end: Optional[int] = ..., + ) -> bool: ... + def strip(self, chars: Optional[bytes] = ...) -> bytes: ... + def swapcase(self) -> bytes: ... + def title(self) -> bytes: ... + def translate(self, table: Optional[bytes], delete: bytes = ...) -> bytes: ... + def upper(self) -> bytes: ... + def zfill(self, width: int) -> bytes: ... + @classmethod + def fromhex(cls, s: str) -> bytes: ... + @classmethod + def maketrans(cls, frm: bytes, to: bytes) -> bytes: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __hash__(self) -> int: ... + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> bytes: ... + def __add__(self, s: bytes) -> bytes: ... + def __mul__(self, n: int) -> bytes: ... + def __rmul__(self, n: int) -> bytes: ... + if sys.version_info >= (3, 5): + def __mod__(self, value: Any) -> bytes: ... + def __contains__(self, o: object) -> bool: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: bytes) -> bool: ... + def __le__(self, x: bytes) -> bool: ... + def __gt__(self, x: bytes) -> bool: ... + def __ge__(self, x: bytes) -> bool: ... + def __getnewargs__(self) -> Tuple[bytes]: ... +else: + bytes = str + +class bytearray(MutableSequence[int], ByteString): + if sys.version_info >= (3,): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, ints: Iterable[int]) -> None: ... + @overload + def __init__(self, string: Text, encoding: Text, errors: Text = ...) -> None: ... + @overload + def __init__(self, length: int) -> None: ... + else: + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, ints: Iterable[int]) -> None: ... + @overload + def __init__(self, string: str) -> None: ... + @overload + def __init__(self, string: Text, encoding: Text, errors: Text = ...) -> None: ... + @overload + def __init__(self, length: int) -> None: ... + def capitalize(self) -> bytearray: ... + def center(self, width: int, fillchar: bytes = ...) -> bytearray: ... + if sys.version_info >= (3,): + def count(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def copy(self) -> bytearray: ... + else: + def count(self, x: str) -> int: ... + def decode(self, encoding: Text = ..., errors: Text = ...) -> str: ... + def endswith(self, suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... + def expandtabs(self, tabsize: int = ...) -> bytearray: ... + if sys.version_info >= (3,): + def find(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + if sys.version_info >= (3, 5): + def hex(self) -> str: ... + def index(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + else: + def find(self, sub: str, start: int = ..., end: int = ...) -> int: ... + def index(self, sub: str, start: int = ..., end: int = ...) -> int: ... + def insert(self, index: int, object: int) -> None: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + if sys.version_info >= (3, 7): + def isascii(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + if sys.version_info >= (3,): + def join(self, iterable: Iterable[Union[ByteString, memoryview]]) -> bytearray: ... + def ljust(self, width: int, fillchar: bytes = ...) -> bytearray: ... + else: + def join(self, iterable: Iterable[str]) -> bytearray: ... + def ljust(self, width: int, fillchar: str = ...) -> bytearray: ... + def lower(self) -> bytearray: ... + def lstrip(self, chars: Optional[bytes] = ...) -> bytearray: ... + def partition(self, sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... + def replace(self, old: bytes, new: bytes, count: int = ...) -> bytearray: ... + if sys.version_info >= (3,): + def rfind(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def rindex(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + else: + def rfind(self, sub: bytes, start: int = ..., end: int = ...) -> int: ... + def rindex(self, sub: bytes, start: int = ..., end: int = ...) -> int: ... + def rjust(self, width: int, fillchar: bytes = ...) -> bytearray: ... + def rpartition(self, sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... + def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... + def rstrip(self, chars: Optional[bytes] = ...) -> bytearray: ... + def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... + def splitlines(self, keepends: bool = ...) -> List[bytearray]: ... + def startswith( + self, + prefix: Union[bytes, Tuple[bytes, ...]], + start: Optional[int] = ..., + end: Optional[int] = ..., + ) -> bool: ... + def strip(self, chars: Optional[bytes] = ...) -> bytearray: ... + def swapcase(self) -> bytearray: ... + def title(self) -> bytearray: ... + if sys.version_info >= (3,): + def translate(self, table: Optional[bytes], delete: bytes = ...) -> bytearray: ... + else: + def translate(self, table: str) -> bytearray: ... + def upper(self) -> bytearray: ... + def zfill(self, width: int) -> bytearray: ... + @staticmethod + def fromhex(s: str) -> bytearray: ... + if sys.version_info >= (3,): + @classmethod + def maketrans(cls, frm: bytes, to: bytes) -> bytes: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __hash__(self) -> int: ... + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> bytearray: ... + @overload + def __setitem__(self, i: int, x: int) -> None: ... + @overload + def __setitem__(self, s: slice, x: Union[Iterable[int], bytes]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + if sys.version_info < (3,): + def __getslice__(self, start: int, stop: int) -> bytearray: ... + def __setslice__(self, start: int, stop: int, x: Union[Sequence[int], str]) -> None: ... + def __delslice__(self, start: int, stop: int) -> None: ... + def __add__(self, s: bytes) -> bytearray: ... + if sys.version_info >= (3,): + def __iadd__(self, s: Iterable[int]) -> bytearray: ... + def __mul__(self, n: int) -> bytearray: ... + if sys.version_info >= (3,): + def __rmul__(self, n: int) -> bytearray: ... + def __imul__(self, n: int) -> bytearray: ... + if sys.version_info >= (3, 5): + def __mod__(self, value: Any) -> bytes: ... + def __contains__(self, o: object) -> bool: ... + def __eq__(self, x: object) -> bool: ... + def __ne__(self, x: object) -> bool: ... + def __lt__(self, x: bytes) -> bool: ... + def __le__(self, x: bytes) -> bool: ... + def __gt__(self, x: bytes) -> bool: ... + def __ge__(self, x: bytes) -> bool: ... + +if sys.version_info >= (3,): + _mv_container_type = int +else: + _mv_container_type = str + +class memoryview(Sized, Container[_mv_container_type]): + format: str + itemsize: int + shape: Optional[Tuple[int, ...]] + strides: Optional[Tuple[int, ...]] + suboffsets: Optional[Tuple[int, ...]] + readonly: bool + ndim: int + + if sys.version_info >= (3,): + c_contiguous: bool + f_contiguous: bool + contiguous: bool + def __init__(self, obj: Union[bytes, bytearray, memoryview]) -> None: ... + def __enter__(self) -> memoryview: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> bool: ... + else: + def __init__(self, obj: Union[bytes, bytearray, buffer, memoryview]) -> None: ... + + @overload + def __getitem__(self, i: int) -> _mv_container_type: ... + @overload + def __getitem__(self, s: slice) -> memoryview: ... + + def __contains__(self, x: object) -> bool: ... + def __iter__(self) -> Iterator[_mv_container_type]: ... + def __len__(self) -> int: ... + + @overload + def __setitem__(self, i: int, o: bytes) -> None: ... + @overload + def __setitem__(self, s: slice, o: Sequence[bytes]) -> None: ... + @overload + def __setitem__(self, s: slice, o: memoryview) -> None: ... + + def tobytes(self) -> bytes: ... + def tolist(self) -> List[int]: ... + + if sys.version_info >= (3, 5): + def hex(self) -> str: ... + +class bool(int): + def __init__(self, o: object = ...) -> None: ... + @overload + def __and__(self, x: bool) -> bool: ... + @overload + def __and__(self, x: int) -> int: ... + @overload + def __or__(self, x: bool) -> bool: ... + @overload + def __or__(self, x: int) -> int: ... + @overload + def __xor__(self, x: bool) -> bool: ... + @overload + def __xor__(self, x: int) -> int: ... + @overload + def __rand__(self, x: bool) -> bool: ... + @overload + def __rand__(self, x: int) -> int: ... + @overload + def __ror__(self, x: bool) -> bool: ... + @overload + def __ror__(self, x: int) -> int: ... + @overload + def __rxor__(self, x: bool) -> bool: ... + @overload + def __rxor__(self, x: int) -> int: ... + def __getnewargs__(self) -> Tuple[int]: ... + +class slice(object): + start: Optional[int] + step: Optional[int] + stop: Optional[int] + @overload + def __init__(self, stop: Optional[int]) -> None: ... + @overload + def __init__(self, start: Optional[int], stop: Optional[int], step: Optional[int] = ...) -> None: ... + def indices(self, len: int) -> Tuple[int, int, int]: ... + +class tuple(Sequence[_T_co], Generic[_T_co]): + def __new__(cls: Type[_T], iterable: Iterable[_T_co] = ...) -> _T: ... + def __len__(self) -> int: ... + def __contains__(self, x: object) -> bool: ... + @overload + def __getitem__(self, x: int) -> _T_co: ... + @overload + def __getitem__(self, x: slice) -> Tuple[_T_co, ...]: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __lt__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __le__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __gt__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __ge__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __add__(self, x: Tuple[_T_co, ...]) -> Tuple[_T_co, ...]: ... + def __mul__(self, n: int) -> Tuple[_T_co, ...]: ... + def __rmul__(self, n: int) -> Tuple[_T_co, ...]: ... + def count(self, x: Any) -> int: ... + if sys.version_info >= (3, 5): + def index(self, x: Any, start: int = ..., end: int = ...) -> int: ... + else: + def index(self, x: Any) -> int: ... + +class function: + # TODO not defined in builtins! + __name__: str + __module__: str + if sys.version_info >= (3,): + __qualname__: str + __code__: CodeType + __annotations__: Dict[str, Any] + +class list(MutableSequence[_T], Generic[_T]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T]) -> None: ... + if sys.version_info >= (3,): + def clear(self) -> None: ... + def copy(self) -> List[_T]: ... + def append(self, object: _T) -> None: ... + def extend(self, iterable: Iterable[_T]) -> None: ... + def pop(self, index: int = ...) -> _T: ... + def index(self, object: _T, start: int = ..., stop: int = ...) -> int: ... + def count(self, object: _T) -> int: ... + def insert(self, index: int, object: _T) -> None: ... + def remove(self, object: _T) -> None: ... + def reverse(self) -> None: ... + if sys.version_info >= (3,): + def sort(self, *, key: Optional[Callable[[_T], Any]] = ..., reverse: bool = ...) -> None: ... + else: + def sort(self, cmp: Callable[[_T, _T], Any] = ..., key: Callable[[_T], Any] = ..., reverse: bool = ...) -> None: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + def __hash__(self) -> int: ... + @overload + def __getitem__(self, i: int) -> _T: ... + @overload + def __getitem__(self, s: slice) -> List[_T]: ... + @overload + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + if sys.version_info < (3,): + def __getslice__(self, start: int, stop: int) -> List[_T]: ... + def __setslice__(self, start: int, stop: int, o: Sequence[_T]) -> None: ... + def __delslice__(self, start: int, stop: int) -> None: ... + def __add__(self, x: List[_T]) -> List[_T]: ... + def __iadd__(self: _S, x: Iterable[_T]) -> _S: ... + def __mul__(self, n: int) -> List[_T]: ... + def __rmul__(self, n: int) -> List[_T]: ... + if sys.version_info >= (3,): + def __imul__(self: _S, n: int) -> _S: ... + def __contains__(self, o: object) -> bool: ... + def __reversed__(self) -> Iterator[_T]: ... + def __gt__(self, x: List[_T]) -> bool: ... + def __ge__(self, x: List[_T]) -> bool: ... + def __lt__(self, x: List[_T]) -> bool: ... + def __le__(self, x: List[_T]) -> bool: ... + +class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): + # NOTE: Keyword arguments are special. If they are used, _KT must include + # str, but we have no way of enforcing it here. + @overload + def __init__(self, **kwargs: _VT) -> None: ... + @overload + def __init__(self, map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def __init__(self, iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + + def __new__(cls: Type[_T1], *args: Any, **kwargs: Any) -> _T1: ... + + if sys.version_info < (3,): + def has_key(self, k: _KT) -> bool: ... + def clear(self) -> None: ... + def copy(self) -> Dict[_KT, _VT]: ... + def popitem(self) -> Tuple[_KT, _VT]: ... + def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ... + @overload + def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + @overload + def update(self, **kwargs: _VT) -> None: ... + if sys.version_info >= (3,): + def keys(self) -> KeysView[_KT]: ... + def values(self) -> ValuesView[_VT]: ... + def items(self) -> ItemsView[_KT, _VT]: ... + else: + def iterkeys(self) -> Iterator[_KT]: ... + def itervalues(self) -> Iterator[_VT]: ... + def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... + def viewkeys(self) -> KeysView[_KT]: ... + def viewvalues(self) -> ValuesView[_VT]: ... + def viewitems(self) -> ItemsView[_KT, _VT]: ... + @staticmethod + @overload + def fromkeys(seq: Iterable[_T]) -> Dict[_T, Any]: ... # TODO: Actually a class method (mypy/issues#328) + @staticmethod + @overload + def fromkeys(seq: Iterable[_T], value: _S) -> Dict[_T, _S]: ... + def __len__(self) -> int: ... + def __getitem__(self, k: _KT) -> _VT: ... + def __setitem__(self, k: _KT, v: _VT) -> None: ... + def __delitem__(self, v: _KT) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + def __str__(self) -> str: ... + +class set(MutableSet[_T], Generic[_T]): + def __init__(self, iterable: Iterable[_T] = ...) -> None: ... + def add(self, element: _T) -> None: ... + def clear(self) -> None: ... + def copy(self) -> Set[_T]: ... + def difference(self, *s: Iterable[Any]) -> Set[_T]: ... + def difference_update(self, *s: Iterable[Any]) -> None: ... + def discard(self, element: _T) -> None: ... + def intersection(self, *s: Iterable[Any]) -> Set[_T]: ... + def intersection_update(self, *s: Iterable[Any]) -> None: ... + def isdisjoint(self, s: Iterable[Any]) -> bool: ... + def issubset(self, s: Iterable[Any]) -> bool: ... + def issuperset(self, s: Iterable[Any]) -> bool: ... + def pop(self) -> _T: ... + def remove(self, element: _T) -> None: ... + def symmetric_difference(self, s: Iterable[_T]) -> Set[_T]: ... + def symmetric_difference_update(self, s: Iterable[_T]) -> None: ... + def union(self, *s: Iterable[_T]) -> Set[_T]: ... + def update(self, *s: Iterable[_T]) -> None: ... + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + def __and__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __iand__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __or__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __ior__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __sub__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __isub__(self, s: AbstractSet[object]) -> Set[_T]: ... + def __xor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __ixor__(self, s: AbstractSet[_S]) -> Set[Union[_T, _S]]: ... + def __le__(self, s: AbstractSet[object]) -> bool: ... + def __lt__(self, s: AbstractSet[object]) -> bool: ... + def __ge__(self, s: AbstractSet[object]) -> bool: ... + def __gt__(self, s: AbstractSet[object]) -> bool: ... + +class frozenset(AbstractSet[_T], Generic[_T]): + def __init__(self, iterable: Iterable[_T] = ...) -> None: ... + def copy(self) -> FrozenSet[_T]: ... + def difference(self, *s: Iterable[object]) -> FrozenSet[_T]: ... + def intersection(self, *s: Iterable[object]) -> FrozenSet[_T]: ... + def isdisjoint(self, s: Iterable[_T]) -> bool: ... + def issubset(self, s: Iterable[object]) -> bool: ... + def issuperset(self, s: Iterable[object]) -> bool: ... + def symmetric_difference(self, s: Iterable[_T]) -> FrozenSet[_T]: ... + def union(self, *s: Iterable[_T]) -> FrozenSet[_T]: ... + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + def __and__(self, s: AbstractSet[_T]) -> FrozenSet[_T]: ... + def __or__(self, s: AbstractSet[_S]) -> FrozenSet[Union[_T, _S]]: ... + def __sub__(self, s: AbstractSet[_T]) -> FrozenSet[_T]: ... + def __xor__(self, s: AbstractSet[_S]) -> FrozenSet[Union[_T, _S]]: ... + def __le__(self, s: AbstractSet[object]) -> bool: ... + def __lt__(self, s: AbstractSet[object]) -> bool: ... + def __ge__(self, s: AbstractSet[object]) -> bool: ... + def __gt__(self, s: AbstractSet[object]) -> bool: ... + +class enumerate(Iterator[Tuple[int, _T]], Generic[_T]): + def __init__(self, iterable: Iterable[_T], start: int = ...) -> None: ... + def __iter__(self) -> Iterator[Tuple[int, _T]]: ... + if sys.version_info >= (3,): + def __next__(self) -> Tuple[int, _T]: ... + else: + def next(self) -> Tuple[int, _T]: ... + +if sys.version_info >= (3,): + class range(Sequence[int]): + start: int + stop: int + step: int + @overload + def __init__(self, stop: int) -> None: ... + @overload + def __init__(self, start: int, stop: int, step: int = ...) -> None: ... + def count(self, value: int) -> int: ... + def index(self, value: int, start: int = ..., stop: Optional[int] = ...) -> int: ... + def __len__(self) -> int: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[int]: ... + @overload + def __getitem__(self, i: int) -> int: ... + @overload + def __getitem__(self, s: slice) -> range: ... + def __repr__(self) -> str: ... + def __reversed__(self) -> Iterator[int]: ... +else: + class xrange(Sized, Iterable[int], Reversible[int]): + @overload + def __init__(self, stop: int) -> None: ... + @overload + def __init__(self, start: int, stop: int, step: int = ...) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __getitem__(self, i: int) -> int: ... + def __reversed__(self) -> Iterator[int]: ... + +class property(object): + def __init__(self, fget: Optional[Callable[[Any], Any]] = ..., + fset: Optional[Callable[[Any, Any], None]] = ..., + fdel: Optional[Callable[[Any], None]] = ..., + doc: Optional[str] = ...) -> None: ... + def getter(self, fget: Callable[[Any], Any]) -> property: ... + def setter(self, fset: Callable[[Any, Any], None]) -> property: ... + def deleter(self, fdel: Callable[[Any], None]) -> property: ... + def __get__(self, obj: Any, type: Optional[type] = ...) -> Any: ... + def __set__(self, obj: Any, value: Any) -> None: ... + def __delete__(self, obj: Any) -> None: ... + def fget(self) -> Any: ... + def fset(self, value: Any) -> None: ... + def fdel(self) -> None: ... + +if sys.version_info < (3,): + long = int + +NotImplemented: Any + +def abs(n: SupportsAbs[_T]) -> _T: ... +def all(i: Iterable[object]) -> bool: ... +def any(i: Iterable[object]) -> bool: ... +if sys.version_info < (3,): + def apply(func: Callable[..., _T], args: Optional[Sequence[Any]] = ..., kwds: Optional[Mapping[str, Any]] = ...) -> _T: ... +if sys.version_info >= (3,): + def ascii(o: object) -> str: ... +def bin(number: int) -> str: ... +if sys.version_info >= (3, 7): + def breakpoint(*args: Any, **kws: Any) -> None: ... +def callable(o: object) -> bool: ... +def chr(code: int) -> str: ... +if sys.version_info < (3,): + def cmp(x: Any, y: Any) -> int: ... + _N1 = TypeVar('_N1', bool, int, float, complex) + def coerce(x: _N1, y: _N1) -> Tuple[_N1, _N1]: ... +if sys.version_info >= (3, 6): + # This class is to be exported as PathLike from os, + # but we define it here as _PathLike to avoid import cycle issues. + # See https://github.com/python/typeshed/pull/991#issuecomment-288160993 + class _PathLike(Generic[AnyStr]): + def __fspath__(self) -> AnyStr: ... + def compile(source: Union[str, bytes, mod], filename: Union[str, bytes, _PathLike], mode: str, flags: int = ..., dont_inherit: int = ..., optimize: int = ...) -> Any: ... +elif sys.version_info >= (3,): + def compile(source: Union[str, bytes, mod], filename: Union[str, bytes], mode: str, flags: int = ..., dont_inherit: int = ..., optimize: int = ...) -> Any: ... +else: + def compile(source: Union[Text, mod], filename: Text, mode: Text, flags: int = ..., dont_inherit: int = ...) -> Any: ... +if sys.version_info >= (3,): + def copyright() -> None: ... + def credits() -> None: ... +def delattr(o: Any, name: Text) -> None: ... +def dir(o: object = ...) -> List[str]: ... +_N2 = TypeVar('_N2', int, float) +def divmod(a: _N2, b: _N2) -> Tuple[_N2, _N2]: ... +def eval(source: Union[Text, bytes, CodeType], globals: Optional[Dict[str, Any]] = ..., locals: Optional[Mapping[str, Any]] = ...) -> Any: ... +if sys.version_info >= (3,): + def exec(object: Union[str, bytes, CodeType], globals: Optional[Dict[str, Any]] = ..., locals: Optional[Mapping[str, Any]] = ...) -> Any: ... +else: + def execfile(filename: str, globals: Optional[Dict[str, Any]] = ..., locals: Optional[Dict[str, Any]] = ...) -> None: ... +def exit(code: Any = ...) -> NoReturn: ... +if sys.version_info >= (3,): + @overload + def filter(__function: None, __iterable: Iterable[Optional[_T]]) -> Iterator[_T]: ... + @overload + def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> Iterator[_T]: ... +else: + @overload + def filter(__function: Callable[[AnyStr], Any], # type: ignore + __iterable: AnyStr) -> AnyStr: ... + @overload + def filter(__function: None, # type: ignore + __iterable: Tuple[Optional[_T], ...]) -> Tuple[_T, ...]: ... + @overload + def filter(__function: Callable[[_T], Any], # type: ignore + __iterable: Tuple[_T, ...]) -> Tuple[_T, ...]: ... + @overload + def filter(__function: None, + __iterable: Iterable[Optional[_T]]) -> List[_T]: ... + @overload + def filter(__function: Callable[[_T], Any], + __iterable: Iterable[_T]) -> List[_T]: ... +def format(o: object, format_spec: str = ...) -> str: ... # TODO unicode +def getattr(o: Any, name: Text, default: Any = ...) -> Any: ... +def globals() -> Dict[str, Any]: ... +def hasattr(o: Any, name: Text) -> bool: ... +def hash(o: object) -> int: ... +if sys.version_info >= (3,): + def help(*args: Any, **kwds: Any) -> None: ... +def hex(i: int) -> str: ... # TODO __index__ +def id(o: object) -> int: ... +if sys.version_info >= (3,): + def input(prompt: Any = ...) -> str: ... +else: + def input(prompt: Any = ...) -> Any: ... + def intern(string: str) -> str: ... +@overload +def iter(iterable: Iterable[_T]) -> Iterator[_T]: ... +@overload +def iter(function: Callable[[], _T], sentinel: _T) -> Iterator[_T]: ... +def isinstance(o: object, t: Union[type, Tuple[Union[type, Tuple], ...]]) -> bool: ... +def issubclass(cls: type, classinfo: Union[type, Tuple[Union[type, Tuple], ...]]) -> bool: ... +def len(o: Sized) -> int: ... +if sys.version_info >= (3,): + def license() -> None: ... +def locals() -> Dict[str, Any]: ... +if sys.version_info >= (3,): + @overload + def map(func: Callable[[_T1], _S], iter1: Iterable[_T1]) -> Iterator[_S]: ... + @overload + def map(func: Callable[[_T1, _T2], _S], iter1: Iterable[_T1], + iter2: Iterable[_T2]) -> Iterator[_S]: ... + @overload + def map(func: Callable[[_T1, _T2, _T3], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> Iterator[_S]: ... + @overload + def map(func: Callable[[_T1, _T2, _T3, _T4], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> Iterator[_S]: ... + @overload + def map(func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5]) -> Iterator[_S]: ... + @overload + def map(func: Callable[..., _S], + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + *iterables: Iterable[Any]) -> Iterator[_S]: ... +else: + @overload + def map(func: None, iter1: Iterable[_T1]) -> List[_T1]: ... + @overload + def map(func: None, + iter1: Iterable[_T1], + iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... + @overload + def map(func: None, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... + @overload + def map(func: None, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def map(func: None, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5]) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def map(func: None, + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + *iterables: Iterable[Any]) -> List[Tuple[Any, ...]]: ... + @overload + def map(func: Callable[[_T1], _S], iter1: Iterable[_T1]) -> List[_S]: ... + @overload + def map(func: Callable[[_T1, _T2], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2]) -> List[_S]: ... + @overload + def map(func: Callable[[_T1, _T2, _T3], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> List[_S]: ... + @overload + def map(func: Callable[[_T1, _T2, _T3, _T4], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> List[_S]: ... + @overload + def map(func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5]) -> List[_S]: ... + @overload + def map(func: Callable[..., _S], + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + *iterables: Iterable[Any]) -> List[_S]: ... +if sys.version_info >= (3,): + @overload + def max(_arg1: _T, _arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... + @overload + def max(_iterable: Iterable[_T], *, key: Callable[[_T], Any] = ..., default: _VT = ...) -> Union[_T, _VT]: ... +else: + @overload + def max(_arg1: _T, _arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... + @overload + def max(_iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... +if sys.version_info >= (3,): + @overload + def min(_arg1: _T, _arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... + @overload + def min(_iterable: Iterable[_T], *, key: Callable[[_T], Any] = ..., default: _VT = ...) -> Union[_T, _VT]: ... +else: + @overload + def min(_arg1: _T, _arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... + @overload + def min(_iterable: Iterable[_T], *, key: Callable[[_T], Any] = ...) -> _T: ... +@overload +def next(i: Iterator[_T]) -> _T: ... +@overload +def next(i: Iterator[_T], default: _VT) -> Union[_T, _VT]: ... +def oct(i: int) -> str: ... # TODO __index__ + +if sys.version_info >= (3, 6): + def open(file: Union[str, bytes, int, _PathLike], mode: str = ..., buffering: int = ..., encoding: Optional[str] = ..., + errors: Optional[str] = ..., newline: Optional[str] = ..., closefd: bool = ...) -> IO[Any]: ... +elif sys.version_info >= (3,): + def open(file: Union[str, bytes, int], mode: str = ..., buffering: int = ..., encoding: Optional[str] = ..., + errors: Optional[str] = ..., newline: Optional[str] = ..., closefd: bool = ...) -> IO[Any]: ... +else: + def open(file: Union[unicode, int], mode: unicode = ..., buffering: int = ...) -> BinaryIO: ... + +def ord(c: Union[Text, bytes]) -> int: ... +if sys.version_info >= (3,): + def print(*values: Any, sep: Text = ..., end: Text = ..., file: Optional[IO[str]] = ..., flush: bool = ...) -> None: ... +else: + # This is only available after from __future__ import print_function. + def print(*values: Any, sep: Text = ..., end: Text = ..., file: Optional[IO[Any]] = ...) -> None: ... +@overload +def pow(x: int, y: int) -> Any: ... # The return type can be int or float, depending on y +@overload +def pow(x: int, y: int, z: int) -> Any: ... +@overload +def pow(x: float, y: float) -> float: ... +@overload +def pow(x: float, y: float, z: float) -> float: ... +def quit(code: Optional[int] = ...) -> None: ... +if sys.version_info < (3,): + def range(x: int, y: int = ..., step: int = ...) -> List[int]: ... + def raw_input(prompt: Any = ...) -> str: ... + @overload + def reduce(function: Callable[[_T, _S], _T], iterable: Iterable[_S], initializer: _T) -> _T: ... + @overload + def reduce(function: Callable[[_T, _T], _T], iterable: Iterable[_T]) -> _T: ... + def reload(module: Any) -> Any: ... +@overload +def reversed(object: Sequence[_T]) -> Iterator[_T]: ... +@overload +def reversed(object: Reversible[_T]) -> Iterator[_T]: ... +def repr(o: object) -> str: ... +if sys.version_info >= (3,): + @overload + def round(number: float) -> int: ... + @overload + def round(number: float, ndigits: None) -> int: ... + @overload + def round(number: float, ndigits: int) -> float: ... + @overload + def round(number: SupportsRound[_T]) -> int: ... + @overload + def round(number: SupportsRound[_T], ndigits: None) -> int: ... # type: ignore + @overload + def round(number: SupportsRound[_T], ndigits: int) -> _T: ... +else: + @overload + def round(number: float) -> float: ... + @overload + def round(number: float, ndigits: int) -> float: ... + @overload + def round(number: SupportsRound[_T]) -> _T: ... + @overload + def round(number: SupportsRound[_T], ndigits: int) -> _T: ... +def setattr(object: Any, name: Text, value: Any) -> None: ... +if sys.version_info >= (3,): + def sorted(iterable: Iterable[_T], *, + key: Optional[Callable[[_T], Any]] = ..., + reverse: bool = ...) -> List[_T]: ... +else: + def sorted(iterable: Iterable[_T], *, + cmp: Callable[[_T, _T], int] = ..., + key: Callable[[_T], Any] = ..., + reverse: bool = ...) -> List[_T]: ... +@overload +def sum(iterable: Iterable[_T]) -> Union[_T, int]: ... +@overload +def sum(iterable: Iterable[_T], start: _S) -> Union[_T, _S]: ... +if sys.version_info < (3,): + def unichr(i: int) -> unicode: ... +def vars(object: Any = ...) -> Dict[str, Any]: ... +if sys.version_info >= (3,): + @overload + def zip(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... + @overload + def zip(iter1: Iterable[_T1], iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... + @overload + def zip(iter1: Iterable[_T1], iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... + @overload + def zip(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def zip(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], + iter4: Iterable[_T4], iter5: Iterable[_T5]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def zip(iter1: Iterable[Any], iter2: Iterable[Any], iter3: Iterable[Any], + iter4: Iterable[Any], iter5: Iterable[Any], iter6: Iterable[Any], + *iterables: Iterable[Any]) -> Iterator[Tuple[Any, ...]]: ... +else: + @overload + def zip(iter1: Iterable[_T1]) -> List[Tuple[_T1]]: ... + @overload + def zip(iter1: Iterable[_T1], + iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... + @overload + def zip(iter1: Iterable[_T1], iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... + @overload + def zip(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def zip(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], + iter4: Iterable[_T4], iter5: Iterable[_T5]) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def zip(iter1: Iterable[Any], iter2: Iterable[Any], iter3: Iterable[Any], + iter4: Iterable[Any], iter5: Iterable[Any], iter6: Iterable[Any], + *iterables: Iterable[Any]) -> List[Tuple[Any, ...]]: ... +def __import__(name: Text, globals: Dict[str, Any] = ..., locals: Dict[str, Any] = ..., + fromlist: List[str] = ..., level: int = ...) -> Any: ... + +# Actually the type of Ellipsis is , but since it's +# not exposed anywhere under that name, we make it private here. +class ellipsis: ... +Ellipsis: ellipsis + +if sys.version_info < (3,): + # TODO: buffer support is incomplete; e.g. some_string.startswith(some_buffer) doesn't type check. + _AnyBuffer = TypeVar('_AnyBuffer', str, unicode, bytearray, buffer) + + class buffer(Sized): + def __init__(self, object: _AnyBuffer, offset: int = ..., size: int = ...) -> None: ... + def __add__(self, other: _AnyBuffer) -> str: ... + def __cmp__(self, other: _AnyBuffer) -> bool: ... + def __getitem__(self, key: Union[int, slice]) -> str: ... + def __getslice__(self, i: int, j: int) -> str: ... + def __len__(self) -> int: ... + def __mul__(self, x: int) -> str: ... + +class BaseException(object): + args: Tuple[Any, ...] + if sys.version_info < (3,): + message: Any + if sys.version_info >= (3,): + __cause__: Optional[BaseException] + __context__: Optional[BaseException] + __traceback__: Optional[TracebackType] + def __init__(self, *args: object) -> None: ... + if sys.version_info < (3,): + def __getitem__(self, i: int) -> Any: ... + def __getslice__(self, start: int, stop: int) -> Tuple[Any, ...]: ... + if sys.version_info >= (3,): + def with_traceback(self, tb: Optional[TracebackType]) -> BaseException: ... + +class GeneratorExit(BaseException): ... +class KeyboardInterrupt(BaseException): ... +class SystemExit(BaseException): + code: int +class Exception(BaseException): ... +class StopIteration(Exception): + if sys.version_info >= (3,): + value: Any +if sys.version_info >= (3,): + _StandardError = Exception + class OSError(Exception): + errno: int + strerror: str + # filename, filename2 are actually Union[str, bytes, None] + filename: Any + filename2: Any + EnvironmentError = OSError + IOError = OSError +else: + class StandardError(Exception): ... + _StandardError = StandardError + class EnvironmentError(StandardError): + errno: int + strerror: str + # TODO can this be unicode? + filename: str + class OSError(EnvironmentError): ... + class IOError(EnvironmentError): ... + +class ArithmeticError(_StandardError): ... +class AssertionError(_StandardError): ... +class AttributeError(_StandardError): ... +class BufferError(_StandardError): ... +class EOFError(_StandardError): ... +class ImportError(_StandardError): + if sys.version_info >= (3,): + name: str + path: str +class LookupError(_StandardError): ... +class MemoryError(_StandardError): ... +class NameError(_StandardError): ... +class ReferenceError(_StandardError): ... +class RuntimeError(_StandardError): ... +if sys.version_info >= (3, 5): + class StopAsyncIteration(Exception): + value: Any +class SyntaxError(_StandardError): + msg: str + lineno: int + offset: Optional[int] + text: str + filename: str +class SystemError(_StandardError): ... +class TypeError(_StandardError): ... +class ValueError(_StandardError): ... + +class FloatingPointError(ArithmeticError): ... +class OverflowError(ArithmeticError): ... +class ZeroDivisionError(ArithmeticError): ... + +if sys.version_info >= (3, 6): + class ModuleNotFoundError(ImportError): ... + +class IndexError(LookupError): ... +class KeyError(LookupError): ... + +class UnboundLocalError(NameError): ... + +class WindowsError(OSError): + winerror: int +if sys.version_info >= (3,): + class BlockingIOError(OSError): + characters_written: int + class ChildProcessError(OSError): ... + class ConnectionError(OSError): ... + class BrokenPipeError(ConnectionError): ... + class ConnectionAbortedError(ConnectionError): ... + class ConnectionRefusedError(ConnectionError): ... + class ConnectionResetError(ConnectionError): ... + class FileExistsError(OSError): ... + class FileNotFoundError(OSError): ... + class InterruptedError(OSError): ... + class IsADirectoryError(OSError): ... + class NotADirectoryError(OSError): ... + class PermissionError(OSError): ... + class ProcessLookupError(OSError): ... + class TimeoutError(OSError): ... + +class NotImplementedError(RuntimeError): ... +if sys.version_info >= (3, 5): + class RecursionError(RuntimeError): ... + +class IndentationError(SyntaxError): ... +class TabError(IndentationError): ... + +class UnicodeError(ValueError): ... +class UnicodeDecodeError(UnicodeError): + encoding: str + object: bytes + start: int + end: int + reason: str + def __init__(self, __encoding: str, __object: bytes, __start: int, __end: int, + __reason: str) -> None: ... +class UnicodeEncodeError(UnicodeError): + encoding: str + object: Text + start: int + end: int + reason: str + def __init__(self, __encoding: str, __object: Text, __start: int, __end: int, + __reason: str) -> None: ... +class UnicodeTranslateError(UnicodeError): ... + +class Warning(Exception): ... +class UserWarning(Warning): ... +class DeprecationWarning(Warning): ... +class SyntaxWarning(Warning): ... +class RuntimeWarning(Warning): ... +class FutureWarning(Warning): ... +class PendingDeprecationWarning(Warning): ... +class ImportWarning(Warning): ... +class UnicodeWarning(Warning): ... +class BytesWarning(Warning): ... +if sys.version_info >= (3, 2): + class ResourceWarning(Warning): ... + +if sys.version_info < (3,): + class file(BinaryIO): + @overload + def __init__(self, file: str, mode: str = ..., buffering: int = ...) -> None: ... + @overload + def __init__(self, file: unicode, mode: str = ..., buffering: int = ...) -> None: ... + @overload + def __init__(self, file: int, mode: str = ..., buffering: int = ...) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def next(self) -> str: ... + def read(self, n: int = ...) -> str: ... + def __enter__(self) -> BinaryIO: ... + def __exit__(self, t: Optional[type] = ..., exc: Optional[BaseException] = ..., tb: Optional[Any] = ...) -> bool: ... + def flush(self) -> None: ... + def fileno(self) -> int: ... + def isatty(self) -> bool: ... + def close(self) -> None: ... + + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + def readline(self, limit: int = ...) -> str: ... + def readlines(self, hint: int = ...) -> List[str]: ... + def write(self, data: str) -> int: ... + def writelines(self, data: Iterable[str]) -> None: ... + def truncate(self, pos: Optional[int] = ...) -> int: ... diff --git a/client/typeshed-fallback/stdlib/2and3/bz2.pyi b/client/typeshed-fallback/stdlib/2and3/bz2.pyi new file mode 100644 index 000000000..2cb329ce9 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/bz2.pyi @@ -0,0 +1,48 @@ +import io +import sys +from typing import Any, IO, Optional, Union + +if sys.version_info >= (3, 6): + from os import PathLike + _PathOrFile = Union[str, bytes, IO[Any], PathLike[Any]] +elif sys.version_info >= (3, 3): + _PathOrFile = Union[str, bytes, IO[Any]] +else: + _PathOrFile = str + +def compress(data: bytes, compresslevel: int = ...) -> bytes: ... +def decompress(data: bytes) -> bytes: ... + +if sys.version_info >= (3, 3): + def open(filename: _PathOrFile, + mode: str = ..., + compresslevel: int = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ...) -> IO[Any]: ... + +class BZ2File(io.BufferedIOBase, IO[bytes]): # type: ignore # python/mypy#5027 + def __init__(self, + filename: _PathOrFile, + mode: str = ..., + buffering: Optional[Any] = ..., + compresslevel: int = ...) -> None: ... + +class BZ2Compressor(object): + def __init__(self, compresslevel: int = ...) -> None: ... + def compress(self, data: bytes) -> bytes: ... + def flush(self) -> bytes: ... + +class BZ2Decompressor(object): + if sys.version_info >= (3, 5): + def decompress(self, data: bytes, max_length: int = ...) -> bytes: ... + else: + def decompress(self, data: bytes) -> bytes: ... + if sys.version_info >= (3, 3): + @property + def eof(self) -> bool: ... + if sys.version_info >= (3, 5): + @property + def needs_input(self) -> bool: ... + @property + def unused_data(self) -> bytes: ... diff --git a/client/typeshed-fallback/stdlib/2and3/cProfile.pyi b/client/typeshed-fallback/stdlib/2and3/cProfile.pyi new file mode 100644 index 000000000..71e25edb8 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/cProfile.pyi @@ -0,0 +1,24 @@ +import os +import sys +from typing import Any, Callable, Dict, Optional, Text, TypeVar, Union + +def run(statement: str, filename: Optional[str] = ..., sort: Union[str, int] = ...) -> None: ... +def runctx(statement: str, globals: Dict[str, Any], locals: Dict[str, Any], filename: Optional[str] = ..., sort: Union[str, int] = ...) -> None: ... + +_SelfT = TypeVar('_SelfT', bound='Profile') +_T = TypeVar('_T') +if sys.version_info >= (3, 6): + _Path = Union[bytes, Text, os.PathLike[Any]] +else: + _Path = Union[bytes, Text] + +class Profile: + def __init__(self, custom_timer: Callable[[], float] = ..., time_unit: float = ..., subcalls: bool = ..., builtins: bool = ...) -> None: ... + def enable(self) -> None: ... + def disable(self) -> None: ... + def print_stats(self, sort: Union[str, int] = ...) -> None: ... + def dump_stats(self, file: _Path) -> None: ... + def create_stats(self) -> None: ... + def run(self: _SelfT, cmd: str) -> _SelfT: ... + def runctx(self: _SelfT, cmd: str, globals: Dict[str, Any], locals: Dict[str, Any]) -> _SelfT: ... + def runcall(self, func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... diff --git a/client/typeshed-fallback/stdlib/2and3/calendar.pyi b/client/typeshed-fallback/stdlib/2and3/calendar.pyi new file mode 100644 index 000000000..2843d46de --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/calendar.pyi @@ -0,0 +1,122 @@ +import datetime +import sys +from time import struct_time +from typing import Any, Iterable, List, Optional, Sequence, Tuple, Union + + +_LocaleType = Tuple[Optional[str], Optional[str]] + +class IllegalMonthError(ValueError): + def __init__(self, month: int) -> None: ... + def __str__(self) -> str: ... + +class IllegalWeekdayError(ValueError): + def __init__(self, weekday: int) -> None: ... + def __str__(self) -> str: ... + +def isleap(year: int) -> bool: ... +def leapdays(y1: int, y2: int) -> int: ... +def weekday(year: int, month: int, day: int) -> int: ... +def monthrange(year: int, month: int) -> Tuple[int, int]: ... + +class Calendar: + def __init__(self, firstweekday: int = ...) -> None: ... + def getfirstweekday(self) -> int: ... + def setfirstweekday(self, firstweekday: int) -> None: ... + def iterweekdays(self) -> Iterable[int]: ... + def itermonthdates(self, year: int, month: int) -> Iterable[datetime.date]: ... + def itermonthdays2(self, year: int, month: int) -> Iterable[Tuple[int, int]]: ... + def itermonthdays(self, year: int, month: int) -> Iterable[int]: ... + def monthdatescalendar(self, year: int, month: int) -> List[List[datetime.date]]: ... + def monthdays2calendar(self, year: int, month: int) -> List[List[Tuple[int, int]]]: ... + def monthdayscalendar(self, year: int, month: int) -> List[List[int]]: ... + def yeardatescalendar(self, year: int, width: int = ...) -> List[List[int]]: ... + def yeardays2calendar(self, year: int, width: int = ...) -> List[List[Tuple[int, int]]]: ... + def yeardayscalendar(self, year: int, width: int = ...) -> List[List[int]]: ... + if sys.version_info >= (3, 7): + def itermonthdays3(self, year: int, month: int) -> Iterable[Tuple[int, int, int]]: ... + def itermonthdays4(self, year: int, month: int) -> Iterable[Tuple[int, int, int, int]]: ... + +class TextCalendar(Calendar): + def prweek(self, theweek: int, width: int) -> None: ... + def formatday(self, day: int, weekday: int, width: int) -> str: ... + def formatweek(self, theweek: int, width: int) -> str: ... + def formatweekday(self, day: int, width: int) -> str: ... + def formatweekheader(self, width: int) -> str: ... + def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = ...) -> str: ... + def prmonth(self, theyear: int, themonth: int, w: int = ..., l: int = ...) -> None: ... + def formatmonth(self, theyear: int, themonth: int, w: int = ..., l: int = ...) -> str: ... + def formatyear(self, theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> str: ... + def pryear(self, theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> None: ... + +def firstweekday() -> int: ... +def monthcalendar(year: int, month: int) -> List[List[int]]: ... +def prweek(theweek: int, width: int) -> None: ... +def week(theweek: int, width: int) -> str: ... +def weekheader(width: int) -> str: ... +def prmonth(theyear: int, themonth: int, w: int = ..., l: int = ...) -> None: ... +def month(theyear: int, themonth: int, w: int = ..., l: int = ...) -> str: ... +def calendar(theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> str: ... +def prcal(theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> None: ... + +class HTMLCalendar(Calendar): + def formatday(self, day: int, weekday: int) -> str: ... + def formatweek(self, theweek: int) -> str: ... + def formatweekday(self, day: int) -> str: ... + def formatweekheader(self) -> str: ... + def formatmonthname(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ... + def formatmonth(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ... + def formatyear(self, theyear: int, width: int = ...) -> str: ... + def formatyearpage(self, theyear: int, width: int = ..., css: Optional[str] = ..., encoding: Optional[str] = ...) -> str: ... + if sys.version_info >= (3, 7): + cssclasses: List[str] + cssclass_noday: str + cssclasses_weekday_head: List[str] + cssclass_month_head: str + cssclass_month: str + cssclass_year: str + cssclass_year_head: str + +if sys.version_info < (3, 0): + class TimeEncoding: + def __init__(self, locale: _LocaleType) -> None: ... + def __enter__(self) -> _LocaleType: ... + def __exit__(self, *args: Any) -> None: ... +else: + class different_locale: + def __init__(self, locale: _LocaleType) -> None: ... + def __enter__(self) -> _LocaleType: ... + def __exit__(self, *args: Any) -> None: ... + +class LocaleTextCalendar(TextCalendar): + def __init__(self, firstweekday: int = ..., locale: Optional[_LocaleType] = ...) -> None: ... + def formatweekday(self, day: int, width: int) -> str: ... + def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = ...) -> str: ... + +class LocaleHTMLCalendar(HTMLCalendar): + def __init__(self, firstweekday: int = ..., locale: Optional[_LocaleType] = ...) -> None: ... + def formatweekday(self, day: int) -> str: ... + def formatmonthname(self, theyear: int, themonth: int, withyear: bool = ...) -> str: ... + +c = ... # type: TextCalendar +def setfirstweekday(firstweekday: int) -> None: ... +def format(cols: int, colwidth: int = ..., spacing: int = ...) -> str: ... +def formatstring(cols: int, colwidth: int = ..., spacing: int = ...) -> str: ... +def timegm(tuple: Union[Tuple[int, ...], struct_time]) -> int: ... + +# Data attributes +day_name = ... # type: Sequence[str] +day_abbr = ... # type: Sequence[str] +month_name = ... # type: Sequence[str] +month_abbr = ... # type: Sequence[str] + +# Below constants are not in docs or __all__, but enough people have used them +# they are now effectively public. + +MONDAY = ... # type: int +TUESDAY = ... # type: int +WEDNESDAY = ... # type: int +THURSDAY = ... # type: int +FRIDAY = ... # type: int +SATURDAY = ... # type: int +SUNDAY = ... # type: int diff --git a/client/typeshed-fallback/stdlib/2and3/cgi.pyi b/client/typeshed-fallback/stdlib/2and3/cgi.pyi new file mode 100644 index 000000000..045c0ce67 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/cgi.pyi @@ -0,0 +1,122 @@ +import sys +from typing import Any, AnyStr, Dict, IO, Iterable, List, Mapping, Optional, Tuple, TypeVar, Union + +_T = TypeVar('_T', bound=FieldStorage) + +def parse(fp: IO[Any] = ..., environ: Mapping[str, str] = ..., + keep_blank_values: bool = ..., strict_parsing: bool = ...) -> Dict[str, List[str]]: ... +def parse_qs(qs: str, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> Dict[str, List[str]]: ... +def parse_qsl(qs: str, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> Dict[str, List[str]]: ... +if sys.version_info >= (3, 7): + def parse_multipart(fp: IO[Any], pdict: Mapping[str, bytes], encoding: str = ..., errors: str = ...) -> Dict[str, List[Any]]: ... +else: + def parse_multipart(fp: IO[Any], pdict: Mapping[str, bytes]) -> Dict[str, List[bytes]]: ... +def parse_header(s: str) -> Tuple[str, Dict[str, str]]: ... +def test(environ: Mapping[str, str] = ...) -> None: ... +def print_environ(environ: Mapping[str, str] = ...) -> None: ... +def print_form(form: Dict[str, Any]) -> None: ... +def print_directory() -> None: ... +def print_environ_usage() -> None: ... +if sys.version_info >= (3, 0): + def escape(s: str, quote: bool = ...) -> str: ... +else: + def escape(s: AnyStr, quote: bool = ...) -> AnyStr: ... + + +class MiniFieldStorage: + # The first five "Any" attributes here are always None, but mypy doesn't support that + filename = ... # type: Any + list = ... # type: Any + type = ... # type: Any + file = ... # type: Optional[IO[bytes]] # Always None + type_options = ... # type: Dict[Any, Any] + disposition = ... # type: Any + disposition_options = ... # type: Dict[Any, Any] + headers = ... # type: Dict[Any, Any] + name = ... # type: Any + value = ... # type: Any + + def __init__(self, name: Any, value: Any) -> None: ... + def __repr__(self) -> str: ... + + +class FieldStorage(object): + FieldStorageClass = ... # type: Optional[type] + keep_blank_values = ... # type: int + strict_parsing = ... # type: int + qs_on_post = ... # type: Optional[str] + headers = ... # type: Mapping[str, str] + fp = ... # type: IO[bytes] + encoding = ... # type: str + errors = ... # type: str + outerboundary = ... # type: bytes + bytes_read = ... # type: int + limit = ... # type: Optional[int] + disposition = ... # type: str + disposition_options = ... # type: Dict[str, str] + filename = ... # type: Optional[str] + file = ... # type: Optional[IO[bytes]] + type = ... # type: str + type_options = ... # type: Dict[str, str] + innerboundary = ... # type: bytes + length = ... # type: int + done = ... # type: int + list = ... # type: Optional[List[Any]] + value = ... # type: Union[None, bytes, List[Any]] + + if sys.version_info >= (3, 0): + def __init__(self, fp: IO[Any] = ..., headers: Mapping[str, str] = ..., outerboundary: bytes = ..., + environ: Mapping[str, str] = ..., keep_blank_values: int = ..., strict_parsing: int = ..., + limit: int = ..., encoding: str = ..., errors: str = ...) -> None: ... + else: + def __init__(self, fp: IO[Any] = ..., headers: Mapping[str, str] = ..., outerboundary: bytes = ..., + environ: Mapping[str, str] = ..., keep_blank_values: int = ..., strict_parsing: int = ...) -> None: ... + + if sys.version_info >= (3, 0): + def __enter__(self: _T) -> _T: ... + def __exit__(self, *args: Any) -> None: ... + def __repr__(self) -> str: ... + def __iter__(self) -> Iterable[str]: ... + def __getitem__(self, key: str) -> Any: ... + def getvalue(self, key: str, default: Any = ...) -> Any: ... + def getfirst(self, key: str, default: Any = ...) -> Any: ... + def getlist(self, key: str) -> List[Any]: ... + def keys(self) -> List[str]: ... + if sys.version_info < (3, 0): + def has_key(self, key: str) -> bool: ... + def __contains__(self, key: str) -> bool: ... + def __len__(self) -> int: ... + if sys.version_info >= (3, 0): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + if sys.version_info >= (3, 0): + # In Python 3 it returns bytes or str IO depending on an internal flag + def make_file(self) -> IO[Any]: ... + else: + # In Python 2 it always returns bytes and ignores the "binary" flag + def make_file(self, binary: Any = ...) -> IO[bytes]: ... + + +if sys.version_info < (3, 0): + from UserDict import UserDict + + class FormContentDict(UserDict): + query_string = ... # type: str + def __init__(self, environ: Mapping[str, str] = ..., keep_blank_values: int = ..., strict_parsing: int = ...) -> None: ... + + class SvFormContentDict(FormContentDict): + def getlist(self, key: Any) -> Any: ... + + class InterpFormContentDict(SvFormContentDict): ... + + class FormContent(FormContentDict): + # TODO this should have + # def values(self, key: Any) -> Any: ... + # but this is incompatible with the supertype, and adding '# type: ignore' triggers + # a parse error in pytype (https://github.com/google/pytype/issues/53) + def indexed_value(self, key: Any, location: int) -> Any: ... + def value(self, key: Any) -> Any: ... + def length(self, key: Any) -> int: ... + def stripped(self, key: Any) -> Any: ... + def pars(self) -> Dict[Any, Any]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/chunk.pyi b/client/typeshed-fallback/stdlib/2and3/chunk.pyi new file mode 100644 index 000000000..79255c22f --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/chunk.pyi @@ -0,0 +1,23 @@ +# Source(py2): https://hg.python.org/cpython/file/2.7/Lib/chunk.py +# Source(py3): https://github.com/python/cpython/blob/master/Lib/chunk.py + +from typing import IO + +class Chunk: + closed = ... # type: bool + align = ... # type: bool + file = ... # type: IO[bytes] + chunkname = ... # type: bytes + chunksize = ... # type: int + size_read = ... # type: int + offset = ... # type: int + seekable = ... # type: bool + def __init__(self, file: IO[bytes], align: bool = ..., bigendian: bool = ..., inclheader: bool = ...) -> None: ... + def getname(self) -> bytes: ... + def getsize(self) -> int: ... + def close(self) -> None: ... + def isatty(self) -> bool: ... + def seek(self, pos: int, whence: int = ...) -> None: ... + def tell(self) -> int: ... + def read(self, size: int = ...) -> bytes: ... + def skip(self) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/cmath.pyi b/client/typeshed-fallback/stdlib/2and3/cmath.pyi new file mode 100644 index 000000000..ada931c23 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/cmath.pyi @@ -0,0 +1,34 @@ +"""Stub file for the 'cmath' module.""" + +import sys +from typing import Union, Tuple + +e = ... # type: float +pi = ... # type: float + +_C = Union[float, complex] + +def acos(x: _C) -> complex: ... +def acosh(x: _C) -> complex: ... +def asin(x: _C) -> complex: ... +def asinh(x: _C) -> complex: ... +def atan(x: _C) -> complex: ... +def atanh(x: _C) -> complex: ... +def cos(x: _C) -> complex: ... +def cosh(x: _C) -> complex: ... +def exp(x: _C) -> complex: ... +def isinf(z: _C) -> bool: ... +def isnan(z: _C) -> bool: ... +def log(x: _C, base: _C = ...) -> complex: ... +def log10(x: _C) -> complex: ... +def phase(z: _C) -> float: ... +def polar(z: _C) -> Tuple[float, float]: ... +def rect(r: float, phi: float) -> complex: ... +def sin(x: _C) -> complex: ... +def sinh(x: _C) -> complex: ... +def sqrt(x: _C) -> complex: ... +def tan(x: _C) -> complex: ... +def tanh(x: _C) -> complex: ... + +if sys.version_info >= (3,): + def isfinite(z: _C) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/2and3/cmd.pyi b/client/typeshed-fallback/stdlib/2and3/cmd.pyi new file mode 100644 index 000000000..dc305c95c --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/cmd.pyi @@ -0,0 +1,41 @@ +# Stubs for cmd (Python 2/3) + +from typing import Any, Optional, Text, IO, List, Callable, Tuple + +class Cmd: + prompt = ... # type: str + identchars = ... # type: str + ruler = ... # type: str + lastcmd = ... # type: str + intro = ... # type: Optional[Any] + doc_leader = ... # type: str + doc_header = ... # type: str + misc_header = ... # type: str + undoc_header = ... # type: str + nohelp = ... # type: str + use_rawinput = ... # type: bool + stdin = ... # type: IO[str] + stdout = ... # type: IO[str] + cmdqueue = ... # type: List[str] + completekey = ... # type: str + def __init__(self, completekey: str = ..., stdin: Optional[IO[str]] = ..., stdout: Optional[IO[str]] = ...) -> None: ... + old_completer = ... # type: Optional[Callable[[str, int], Optional[str]]] + def cmdloop(self, intro: Optional[Any] = ...) -> None: ... + def precmd(self, line: str) -> str: ... + def postcmd(self, stop: bool, line: str) -> bool: ... + def preloop(self) -> None: ... + def postloop(self) -> None: ... + def parseline(self, line: str) -> Tuple[Optional[str], Optional[str], str]: ... + def onecmd(self, line: str) -> bool: ... + def emptyline(self) -> bool: ... + def default(self, line: str) -> bool: ... + def completedefault(self, *ignored: Any) -> List[str]: ... + def completenames(self, text: str, *ignored: Any) -> List[str]: ... + completion_matches = ... # type: Optional[List[str]] + def complete(self, text: str, state: int) -> Optional[List[str]]: ... + def get_names(self) -> List[str]: ... + # Only the first element of args matters. + def complete_help(self, *args: Any) -> List[str]: ... + def do_help(self, arg: Optional[str]) -> None: ... + def print_topics(self, header: str, cmds: Optional[List[str]], cmdlen: Any, maxcol: int) -> None: ... + def columnize(self, list: Optional[List[str]], displaywidth: int = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/code.pyi b/client/typeshed-fallback/stdlib/2and3/code.pyi new file mode 100644 index 000000000..293ab9b98 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/code.pyi @@ -0,0 +1,38 @@ +# Stubs for code + +import sys +from typing import Any, Callable, Mapping, Optional +from types import CodeType + +class InteractiveInterpreter: + def __init__(self, locals: Optional[Mapping[str, Any]] = ...) -> None: ... + def runsource(self, source: str, filename: str = ..., + symbol: str = ...) -> bool: ... + def runcode(self, code: CodeType) -> None: ... + def showsyntaxerror(self, filename: Optional[str] = ...) -> None: ... + def showtraceback(self) -> None: ... + def write(self, data: str) -> None: ... + +class InteractiveConsole(InteractiveInterpreter): + def __init__(self, locals: Optional[Mapping[str, Any]] = ..., + filename: str = ...) -> None: ... + if sys.version_info >= (3, 6): + def interact(self, banner: Optional[str] = ..., + exitmsg: Optional[str] = ...) -> None: ... + else: + def interact(self, banner: Optional[str] = ...) -> None: ... + def push(self, line: str) -> bool: ... + def resetbuffer(self) -> None: ... + def raw_input(self, prompt: str = ...) -> str: ... + +if sys.version_info >= (3, 6): + def interact(banner: Optional[str] = ..., + readfunc: Optional[Callable[[str], str]] = ..., + local: Optional[Mapping[str, Any]] = ..., + exitmsg: Optional[str] = ...) -> None: ... +else: + def interact(banner: Optional[str] = ..., + readfunc: Optional[Callable[[str], str]] = ..., + local: Optional[Mapping[str, Any]] = ...) -> None: ... +def compile_command(source: str, filename: str = ..., + symbol: str = ...) -> Optional[CodeType]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/codecs.pyi b/client/typeshed-fallback/stdlib/2and3/codecs.pyi new file mode 100644 index 000000000..b99ce9134 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/codecs.pyi @@ -0,0 +1,242 @@ +import sys +from typing import Any, BinaryIO, Callable, Generator, IO, Iterable, Iterator, List, Optional, Protocol, Text, TextIO, Tuple, Type, TypeVar, Union + +from abc import abstractmethod +import types + +# TODO: this only satisfies the most common interface, where +# bytes (py2 str) is the raw form and str (py2 unicode) is the cooked form. +# In the long run, both should become template parameters maybe? +# There *are* bytes->bytes and str->str encodings in the standard library. +# They are much more common in Python 2 than in Python 3. + +_Decoded = Text +_Encoded = bytes + +class _Encoder(Protocol): + def __call__(self, input: _Decoded, errors: str = ...) -> Tuple[_Encoded, int]: ... # signature of Codec().encode +class _Decoder(Protocol): + def __call__(self, input: _Encoded, errors: str = ...) -> Tuple[_Decoded, int]: ... # signature of Codec().decode + +class _StreamReader(Protocol): + def __call__(self, stream: IO[_Encoded], errors: str = ...) -> StreamReader: ... +class _StreamWriter(Protocol): + def __call__(self, stream: IO[_Encoded], errors: str = ...) -> StreamWriter: ... + +class _IncrementalEncoder(Protocol): + def __call__(self, errors: str = ...) -> IncrementalEncoder: ... +class _IncrementalDecoder(Protocol): + def __call__(self, errors: str = ...) -> IncrementalDecoder: ... + +def encode(obj: _Decoded, encoding: str = ..., errors: str = ...) -> _Encoded: ... +def decode(obj: _Encoded, encoding: str = ..., errors: str = ...) -> _Decoded: ... +def lookup(encoding: str) -> CodecInfo: ... + +class CodecInfo(Tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): + @property + def encode(self) -> _Encoder: ... + @property + def decode(self) -> _Decoder: ... + @property + def streamreader(self) -> _StreamReader: ... + @property + def streamwriter(self) -> _StreamWriter: ... + @property + def incrementalencoder(self) -> _IncrementalEncoder: ... + @property + def incrementaldecoder(self) -> _IncrementalDecoder: ... + name: str + def __init__( + self, + encode: _Encoder, + decode: _Decoder, + streamreader: _StreamReader = ..., + streamwriter: _StreamWriter = ..., + incrementalencoder: _IncrementalEncoder = ..., + incrementaldecoder: _IncrementalDecoder = ..., + name: str = ..., + ) -> None: ... + +def getencoder(encoding: str) -> _Encoder: ... +def getdecoder(encoding: str) -> _Decoder: ... +def getincrementalencoder(encoding: str) -> _IncrementalEncoder: ... +def getincrementaldecoder(encoding: str) -> _IncrementalDecoder: ... +def getreader(encoding: str) -> _StreamReader: ... +def getwriter(encoding: str) -> _StreamWriter: ... +def register(search_function: Callable[[str], CodecInfo]) -> None: ... +def open(filename: str, mode: str = ..., encoding: str = ..., errors: str = ..., buffering: int = ...) -> StreamReaderWriter: ... +def EncodedFile(file: IO[_Encoded], data_encoding: str, file_encoding: str = ..., errors: str = ...) -> StreamRecoder: ... +def iterencode(iterator: Iterable[_Decoded], encoding: str, errors: str = ...) -> Generator[_Encoded, None, None]: ... +def iterdecode(iterator: Iterable[_Encoded], encoding: str, errors: str = ...) -> Generator[_Decoded, None, None]: ... + +BOM: bytes +BOM_BE: bytes +BOM_LE: bytes +BOM_UTF8: bytes +BOM_UTF16: bytes +BOM_UTF16_BE: bytes +BOM_UTF16_LE: bytes +BOM_UTF32: bytes +BOM_UTF32_BE: bytes +BOM_UTF32_LE: bytes + +# It is expected that different actions be taken depending on which of the +# three subclasses of `UnicodeError` is actually ...ed. However, the Union +# is still needed for at least one of the cases. +def register_error(name: str, error_handler: Callable[[UnicodeError], Tuple[Union[str, bytes], int]]) -> None: ... +def lookup_error(name: str) -> Callable[[UnicodeError], Tuple[Union[str, bytes], int]]: ... +def strict_errors(exception: UnicodeError) -> Tuple[Union[str, bytes], int]: ... +def replace_errors(exception: UnicodeError) -> Tuple[Union[str, bytes], int]: ... +def ignore_errors(exception: UnicodeError) -> Tuple[Union[str, bytes], int]: ... +def xmlcharrefreplace_errors(exception: UnicodeError) -> Tuple[Union[str, bytes], int]: ... +def backslashreplace_errors(exception: UnicodeError) -> Tuple[Union[str, bytes], int]: ... + +class Codec: + # These are sort of @abstractmethod but sort of not. + # The StreamReader and StreamWriter subclasses only implement one. + def encode(self, input: _Decoded, errors: str = ...) -> Tuple[_Encoded, int]: ... + def decode(self, input: _Encoded, errors: str = ...) -> Tuple[_Decoded, int]: ... + +class IncrementalEncoder: + errors: str + def __init__(self, errors: str = ...) -> None: ... + @abstractmethod + def encode(self, object: _Decoded, final: bool = ...) -> _Encoded: ... + def reset(self) -> None: ... + # documentation says int but str is needed for the subclass. + def getstate(self) -> Union[int, _Decoded]: ... + def setstate(self, state: Union[int, _Decoded]) -> None: ... + +class IncrementalDecoder: + errors: str + def __init__(self, errors: str = ...) -> None: ... + @abstractmethod + def decode(self, object: _Encoded, final: bool = ...) -> _Decoded: ... + def reset(self) -> None: ... + def getstate(self) -> Tuple[_Encoded, int]: ... + def setstate(self, state: Tuple[_Encoded, int]) -> None: ... + +# These are not documented but used in encodings/*.py implementations. +class BufferedIncrementalEncoder(IncrementalEncoder): + buffer: str + def __init__(self, errors: str = ...) -> None: ... + @abstractmethod + def _buffer_encode(self, input: _Decoded, errors: str, final: bool) -> _Encoded: ... + def encode(self, input: _Decoded, final: bool = ...) -> _Encoded: ... + +class BufferedIncrementalDecoder(IncrementalDecoder): + buffer: bytes + def __init__(self, errors: str = ...) -> None: ... + @abstractmethod + def _buffer_decode(self, input: _Encoded, errors: str, final: bool) -> Tuple[_Decoded, int]: ... + def decode(self, object: _Encoded, final: bool = ...) -> _Decoded: ... + +_SW = TypeVar("_SW", bound=StreamWriter) + +# TODO: it is not possible to specify the requirement that all other +# attributes and methods are passed-through from the stream. +class StreamWriter(Codec): + errors: str + def __init__(self, stream: IO[_Encoded], errors: str = ...) -> None: ... + def write(self, obj: _Decoded) -> None: ... + def writelines(self, list: Iterable[_Decoded]) -> None: ... + def reset(self) -> None: ... + def __enter__(self: _SW) -> _SW: ... + def __exit__( + self, typ: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[types.TracebackType] + ) -> None: ... + def __getattr__(self, name: str) -> Any: ... + +_SR = TypeVar("_SR", bound=StreamReader) + +class StreamReader(Codec): + errors: str + def __init__(self, stream: IO[_Encoded], errors: str = ...) -> None: ... + def read(self, size: int = ..., chars: int = ..., firstline: bool = ...) -> _Decoded: ... + def readline(self, size: int = ..., keepends: bool = ...) -> _Decoded: ... + def readlines(self, sizehint: int = ..., keepends: bool = ...) -> List[_Decoded]: ... + def reset(self) -> None: ... + def __enter__(self: _SR) -> _SR: ... + def __exit__( + self, typ: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[types.TracebackType] + ) -> None: ... + def __iter__(self) -> Iterator[_Decoded]: ... + def __getattr__(self, name: str) -> Any: ... + +_T = TypeVar("_T", bound=StreamReaderWriter) + +# Doesn't actually inherit from TextIO, but wraps a BinaryIO to provide text reading and writing +# and delegates attributes to the underlying binary stream with __getattr__. +class StreamReaderWriter(TextIO): + def __init__(self, stream: IO[_Encoded], Reader: _StreamReader, Writer: _StreamWriter, errors: str = ...) -> None: ... + def read(self, size: int = ...) -> _Decoded: ... + def readline(self, size: Optional[int] = ...) -> _Decoded: ... + def readlines(self, sizehint: Optional[int] = ...) -> List[_Decoded]: ... + if sys.version_info >= (3,): + def __next__(self) -> Text: ... + else: + def next(self) -> Text: ... + def __iter__(self: _T) -> _T: ... + # This actually returns None, but that's incompatible with the supertype + def write(self, data: _Decoded) -> int: ... + def writelines(self, list: Iterable[_Decoded]) -> None: ... + def reset(self) -> None: ... + # Same as write() + def seek(self, offset: int, whence: int = ...) -> int: ... + def __enter__(self: _T) -> _T: ... + def __exit__( + self, typ: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[types.TracebackType] + ) -> bool: ... + def __getattr__(self, name: str) -> Any: ... + # These methods don't actually exist directly, but they are needed to satisfy the TextIO + # interface. At runtime, they are delegated through __getattr__. + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def writable(self) -> bool: ... + +_SRT = TypeVar("_SRT", bound=StreamRecoder) + +class StreamRecoder(BinaryIO): + def __init__( + self, + stream: IO[_Encoded], + encode: _Encoder, + decode: _Decoder, + Reader: _StreamReader, + Writer: _StreamWriter, + errors: str = ..., + ) -> None: ... + def read(self, size: int = ...) -> bytes: ... + def readline(self, size: Optional[int] = ...) -> bytes: ... + def readlines(self, sizehint: Optional[int] = ...) -> List[bytes]: ... + if sys.version_info >= (3,): + def __next__(self) -> bytes: ... + else: + def next(self) -> bytes: ... + def __iter__(self: _SRT) -> _SRT: ... + def write(self, data: bytes) -> int: ... + def writelines(self, list: Iterable[bytes]) -> int: ... # type: ignore # it's supposed to return None + def reset(self) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __enter__(self: _SRT) -> _SRT: ... + def __exit__( + self, type: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[types.TracebackType] + ) -> bool: ... + # These methods don't actually exist directly, but they are needed to satisfy the BinaryIO + # interface. At runtime, they are delegated through __getattr__. + def seek(self, offset: int, whence: int = ...) -> int: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def writable(self) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/2and3/codeop.pyi b/client/typeshed-fallback/stdlib/2and3/codeop.pyi new file mode 100644 index 000000000..826e40882 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/codeop.pyi @@ -0,0 +1,17 @@ +# Source(py2): https://hg.python.org/cpython/file/2.7/Lib/codeop.py +# Source(py3): https://github.com/python/cpython/blob/master/Lib/codeop.py + +from types import CodeType +from typing import Optional + +def compile_command(source: str, filename: str = ..., symbol: str = ...) -> Optional[CodeType]: ... + +class Compile: + flags = ... # type: int + def __init__(self) -> None: ... + def __call__(self, source: str, filename: str, symbol: str) -> CodeType: ... + +class CommandCompiler: + compiler = ... # type: Compile + def __init__(self) -> None: ... + def __call__(self, source: str, filename: str = ..., symbol: str = ...) -> Optional[CodeType]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/colorsys.pyi b/client/typeshed-fallback/stdlib/2and3/colorsys.pyi new file mode 100644 index 000000000..ee17ba9a2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/colorsys.pyi @@ -0,0 +1,15 @@ +# Stubs for colorsys + +from typing import Tuple + +def rgb_to_yiq(r: float, g: float, b: float) -> Tuple[float, float, float]: ... +def yiq_to_rgb(y: float, i: float, q: float) -> Tuple[float, float, float]: ... +def rgb_to_hls(r: float, g: float, b: float) -> Tuple[float, float, float]: ... +def hls_to_rgb(h: float, l: float, s: float) -> Tuple[float, float, float]: ... +def rgb_to_hsv(r: float, g: float, b: float) -> Tuple[float, float, float]: ... +def hsv_to_rgb(h: float, s: float, v: float) -> Tuple[float, float, float]: ... + +# TODO undocumented +ONE_SIXTH = ... # type: float +ONE_THIRD = ... # type: float +TWO_THIRD = ... # type: float diff --git a/client/typeshed-fallback/stdlib/2and3/contextlib.pyi b/client/typeshed-fallback/stdlib/2and3/contextlib.pyi new file mode 100644 index 000000000..dec1b411d --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/contextlib.pyi @@ -0,0 +1,99 @@ +# Stubs for contextlib + +from typing import ( + Any, Callable, Generator, IO, Iterable, Iterator, Optional, Type, + Generic, TypeVar, overload +) +from types import TracebackType +import sys +# Aliased here for backwards compatibility; TODO eventually remove this +from typing import ContextManager as ContextManager + +if sys.version_info >= (3, 5): + from typing import AsyncContextManager, AsyncIterator + +if sys.version_info >= (3, 6): + from typing import ContextManager as AbstractContextManager +if sys.version_info >= (3, 7): + from typing import AsyncContextManager as AbstractAsyncContextManager + +_T = TypeVar('_T') + +_ExitFunc = Callable[[Optional[Type[BaseException]], + Optional[BaseException], + Optional[TracebackType]], bool] +_CM_EF = TypeVar('_CM_EF', ContextManager, _ExitFunc) + +if sys.version_info >= (3, 2): + class GeneratorContextManager(ContextManager[_T], Generic[_T]): + def __call__(self, func: Callable[..., _T]) -> Callable[..., _T]: ... + def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., GeneratorContextManager[_T]]: ... +else: + def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_T]]: ... + +if sys.version_info >= (3, 7): + def asynccontextmanager(func: Callable[..., AsyncIterator[_T]]) -> Callable[..., AsyncContextManager[_T]]: ... + +if sys.version_info < (3,): + def nested(*mgr: ContextManager[Any]) -> ContextManager[Iterable[Any]]: ... + +class closing(ContextManager[_T], Generic[_T]): + def __init__(self, thing: _T) -> None: ... + +if sys.version_info >= (3, 4): + class suppress(ContextManager[None]): + def __init__(self, *exceptions: Type[BaseException]) -> None: ... + + class redirect_stdout(ContextManager[None]): + def __init__(self, new_target: IO[str]) -> None: ... + +if sys.version_info >= (3, 5): + class redirect_stderr(ContextManager[None]): + def __init__(self, new_target: IO[str]) -> None: ... + +if sys.version_info >= (3,): + class ContextDecorator: + def __call__(self, func: Callable[..., None]) -> Callable[..., ContextManager[None]]: ... + + _U = TypeVar('_U', bound='ExitStack') + + class ExitStack(ContextManager[ExitStack]): + def __init__(self) -> None: ... + def enter_context(self, cm: ContextManager[_T]) -> _T: ... + def push(self, exit: _CM_EF) -> _CM_EF: ... + def callback(self, callback: Callable[..., Any], + *args: Any, **kwds: Any) -> Callable[..., Any]: ... + def pop_all(self: _U) -> _U: ... + def close(self) -> None: ... + def __enter__(self: _U) -> _U: ... + +if sys.version_info >= (3, 7): + from typing import Awaitable + + _S = TypeVar('_S', bound='AsyncExitStack') + + _ExitCoroFunc = Callable[[Optional[Type[BaseException]], + Optional[BaseException], + Optional[TracebackType]], Awaitable[bool]] + _CallbackCoroFunc = Callable[..., Awaitable[Any]] + _ACM_EF = TypeVar('_ACM_EF', AsyncContextManager, _ExitCoroFunc) + + class AsyncExitStack(AsyncContextManager[AsyncExitStack]): + def __init__(self) -> None: ... + def enter_context(self, cm: ContextManager[_T]) -> _T: ... + def enter_async_context(self, cm: AsyncContextManager[_T]) -> Awaitable[_T]: ... + def push(self, exit: _CM_EF) -> _CM_EF: ... + def push_async_exit(self, exit: _ACM_EF) -> _ACM_EF: ... + def callback(self, callback: Callable[..., Any], + *args: Any, **kwds: Any) -> Callable[..., Any]: ... + def push_async_callback(self, callback: _CallbackCoroFunc, + *args: Any, **kwds: Any) -> _CallbackCoroFunc: ... + def pop_all(self: _S) -> _S: ... + def aclose(self) -> Awaitable[None]: ... + def __aenter__(self: _S) -> Awaitable[_S]: ... + +if sys.version_info >= (3, 7): + @overload + def nullcontext(enter_result: _T) -> ContextManager[_T]: ... + @overload + def nullcontext() -> ContextManager[None]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/copy.pyi b/client/typeshed-fallback/stdlib/2and3/copy.pyi new file mode 100644 index 000000000..523802a84 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/copy.pyi @@ -0,0 +1,14 @@ +# Stubs for copy + +from typing import TypeVar, Optional, Dict, Any + +_T = TypeVar('_T') + +# None in CPython but non-None in Jython +PyStringMap: Any + +# Note: memo and _nil are internal kwargs. +def deepcopy(x: _T, memo: Optional[Dict[int, _T]] = ..., _nil: Any = ...) -> _T: ... +def copy(x: _T) -> _T: ... +class Error(Exception): ... +error = Error diff --git a/client/typeshed-fallback/stdlib/2and3/crypt.pyi b/client/typeshed-fallback/stdlib/2and3/crypt.pyi new file mode 100644 index 000000000..d55fc263e --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/crypt.pyi @@ -0,0 +1,23 @@ +import sys +from typing import List, NamedTuple, Optional, Union + + +if sys.version_info >= (3, 3): + class _Method: ... + + METHOD_CRYPT: _Method + METHOD_MD5: _Method + METHOD_SHA256: _Method + METHOD_SHA512: _Method + if sys.version_info >= (3, 7): + METHOD_BLOWFISH: _Method + + methods: List[_Method] + + if sys.version_info >= (3, 7): + def mksalt(method: Optional[_Method] = ..., *, rounds: Optional[int] = ...) -> str: ... + else: + def mksalt(method: Optional[_Method] = ...) -> str: ... + def crypt(word: str, salt: Optional[Union[str, _Method]] = ...) -> str: ... +else: + def crypt(word: str, salt: str) -> str: ... diff --git a/client/typeshed-fallback/stdlib/2and3/csv.pyi b/client/typeshed-fallback/stdlib/2and3/csv.pyi new file mode 100644 index 000000000..5376c3cde --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/csv.pyi @@ -0,0 +1,93 @@ +from collections import OrderedDict +import sys +from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Union + +from _csv import (_reader, + _writer, + reader as reader, + writer as writer, + register_dialect as register_dialect, + unregister_dialect as unregister_dialect, + get_dialect as get_dialect, + list_dialects as list_dialects, + field_size_limit as field_size_limit, + QUOTE_ALL as QUOTE_ALL, + QUOTE_MINIMAL as QUOTE_MINIMAL, + QUOTE_NONE as QUOTE_NONE, + QUOTE_NONNUMERIC as QUOTE_NONNUMERIC, + Error as Error, + ) + +_Dialect = Union[str, Dialect] +_DictRow = Mapping[str, Any] + +class Dialect(object): + delimiter = ... # type: str + quotechar = ... # type: Optional[str] + escapechar = ... # type: Optional[str] + doublequote = ... # type: bool + skipinitialspace = ... # type: bool + lineterminator = ... # type: str + quoting = ... # type: int + def __init__(self) -> None: ... + +class excel(Dialect): + delimiter = ... # type: str + quotechar = ... # type: str + doublequote = ... # type: bool + skipinitialspace = ... # type: bool + lineterminator = ... # type: str + quoting = ... # type: int + +class excel_tab(excel): + delimiter = ... # type: str + +if sys.version_info >= (3,): + class unix_dialect(Dialect): + delimiter = ... # type: str + quotechar = ... # type: str + doublequote = ... # type: bool + skipinitialspace = ... # type: bool + lineterminator = ... # type: str + quoting = ... # type: int + +if sys.version_info >= (3, 6): + _DRMapping = OrderedDict[str, str] +else: + _DRMapping = Dict[str, str] + + +class DictReader(Iterator[_DRMapping]): + restkey = ... # type: Optional[str] + restval = ... # type: Optional[str] + reader = ... # type: _reader + dialect = ... # type: _Dialect + line_num = ... # type: int + fieldnames = ... # type: Sequence[str] + def __init__(self, f: Iterable[str], fieldnames: Sequence[str] = ..., + restkey: Optional[str] = ..., restval: Optional[str] = ..., dialect: _Dialect = ..., + *args: Any, **kwds: Any) -> None: ... + def __iter__(self) -> DictReader: ... + if sys.version_info >= (3,): + def __next__(self) -> _DRMapping: ... + else: + def next(self) -> _DRMapping: ... + + +class DictWriter(object): + fieldnames = ... # type: Sequence[str] + restval = ... # type: Optional[Any] + extrasaction = ... # type: str + writer = ... # type: _writer + def __init__(self, f: Any, fieldnames: Sequence[str], + restval: Optional[Any] = ..., extrasaction: str = ..., dialect: _Dialect = ..., + *args: Any, **kwds: Any) -> None: ... + def writeheader(self) -> None: ... + def writerow(self, rowdict: _DictRow) -> None: ... + def writerows(self, rowdicts: Iterable[_DictRow]) -> None: ... + +class Sniffer(object): + preferred = ... # type: List[str] + def __init__(self) -> None: ... + def sniff(self, sample: str, delimiters: Optional[str] = ...) -> Dialect: ... + def has_header(self, sample: str) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/2and3/ctypes/__init__.pyi b/client/typeshed-fallback/stdlib/2and3/ctypes/__init__.pyi new file mode 100644 index 000000000..e4cd6b48f --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/ctypes/__init__.pyi @@ -0,0 +1,285 @@ +# Stubs for ctypes + +from array import array +from typing import ( + Any, Callable, ClassVar, Iterator, Iterable, List, Mapping, Optional, Sequence, Sized, Text, + Tuple, Type, Generic, TypeVar, overload, +) +from typing import Union as _UnionT +import sys + +_T = TypeVar('_T') +_DLLT = TypeVar('_DLLT', bound=CDLL) +_CT = TypeVar('_CT', bound=_CData) + + +RTLD_GLOBAL: int = ... +RTLD_LOCAL: int = ... +DEFAULT_MODE: int = ... + + +class CDLL(object): + _func_flags_: ClassVar[int] = ... + _func_restype_: ClassVar[_CData] = ... + _name: str = ... + _handle: int = ... + _FuncPtr: Type[_FuncPointer] = ... + def __init__(self, name: str, mode: int = ..., handle: Optional[int] = ..., + use_errno: bool = ..., use_last_error: bool = ...) -> None: ... + def __getattr__(self, name: str) -> _FuncPointer: ... + def __getitem__(self, name: str) -> _FuncPointer: ... +if sys.platform == 'win32': + class OleDLL(CDLL): ... + class WinDLL(CDLL): ... +class PyDLL(CDLL): ... + +class LibraryLoader(Generic[_DLLT]): + def __init__(self, dlltype: Type[_DLLT]) -> None: ... + def __getattr__(self, name: str) -> _DLLT: ... + def __getitem__(self, name: str) -> _DLLT: ... + def LoadLibrary(self, name: str) -> _DLLT: ... + +cdll: LibraryLoader[CDLL] = ... +if sys.platform == 'win32': + windll: LibraryLoader[WinDLL] = ... + oledll: LibraryLoader[OleDLL] = ... +pydll: LibraryLoader[PyDLL] = ... +pythonapi: PyDLL = ... + +# Anything that implements the read-write buffer interface. +# The buffer interface is defined purely on the C level, so we cannot define a normal Protocol +# for it. Instead we have to list the most common stdlib buffer classes in a Union. +_WritableBuffer = _UnionT[bytearray, memoryview, array, _CData] +# Same as _WritableBuffer, but also includes read-only buffer types (like bytes). +_ReadOnlyBuffer = _UnionT[_WritableBuffer, bytes] + +class _CDataMeta(type): + # By default mypy complains about the following two methods, because strictly speaking cls + # might not be a Type[_CT]. However this can never actually happen, because the only class that + # uses _CDataMeta as its metaclass is _CData. So it's safe to ignore the errors here. + def __mul__(cls: Type[_CT], other: int) -> Type[Array[_CT]]: ... # type: ignore + def __rmul__(cls: Type[_CT], other: int) -> Type[Array[_CT]]: ... # type: ignore +class _CData(metaclass=_CDataMeta): + _b_base: int = ... + _b_needsfree_: bool = ... + _objects: Optional[Mapping[Any, int]] = ... + @classmethod + def from_buffer(cls: Type[_CT], source: _WritableBuffer, offset: int = ...) -> _CT: ... + @classmethod + def from_buffer_copy(cls: Type[_CT], source: _ReadOnlyBuffer, offset: int = ...) -> _CT: ... + @classmethod + def from_address(cls: Type[_CT], address: int) -> _CT: ... + @classmethod + def from_param(cls: Type[_CT], obj: Any) -> _UnionT[_CT, _CArgObject]: ... + @classmethod + def in_dll(cls: Type[_CT], library: CDLL, name: str) -> _CT: ... + +class _PointerLike(_CData): ... + +_ECT = Callable[[Optional[Type[_CData]], + _FuncPointer, + Tuple[_CData, ...]], + _CData] +_PF = _UnionT[ + Tuple[int], + Tuple[int, str], + Tuple[int, str, Any] +] +class _FuncPointer(_PointerLike, _CData): + restype: _UnionT[Type[_CData], Callable[[int], None], None] = ... + argtypes: Sequence[Type[_CData]] = ... + errcheck: _ECT = ... + @overload + def __init__(self, address: int) -> None: ... + @overload + def __init__(self, callable: Callable[..., Any]) -> None: ... + @overload + def __init__(self, func_spec: Tuple[_UnionT[str, int], CDLL], + paramflags: Tuple[_PF, ...] = ...) -> None: ... + @overload + def __init__(self, vtlb_index: int, name: str, + paramflags: Tuple[_PF, ...] = ..., + iid: pointer[c_int] = ...) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + +class ArgumentError(Exception): ... + + +def CFUNCTYPE(restype: Optional[Type[_CData]], + *argtypes: Type[_CData], + use_errno: bool = ..., + use_last_error: bool = ...) -> Type[_FuncPointer]: ... +if sys.platform == 'win32': + def WINFUNCTYPE(restype: Optional[Type[_CData]], + *argtypes: Type[_CData], + use_errno: bool = ..., + use_last_error: bool = ...) -> Type[_FuncPointer]: ... +def PYFUNCTYPE(restype: Optional[Type[_CData]], + *argtypes: Type[_CData]) -> Type[_FuncPointer]: ... + +class _CArgObject: ... + +# Any type that can be implicitly converted to c_void_p when passed as a C function argument. +# (bytes is not included here, see below.) +_CVoidPLike = _UnionT[_PointerLike, Array[Any], _CArgObject, int] +# Same as above, but including types known to be read-only (i. e. bytes). +# This distinction is not strictly necessary (ctypes doesn't differentiate between const +# and non-const pointers), but it catches errors like memmove(b'foo', buf, 4) +# when memmove(buf, b'foo', 4) was intended. +_CVoidConstPLike = _UnionT[_CVoidPLike, bytes] + +def addressof(obj: _CData) -> int: ... +def alignment(obj_or_type: _UnionT[_CData, Type[_CData]]) -> int: ... +def byref(obj: _CData, offset: int = ...) -> _CArgObject: ... +_PT = TypeVar('_PT', bound=_PointerLike) +def cast(obj: _UnionT[_CData, _CArgObject], type: Type[_PT]) -> _PT: ... +def create_string_buffer(init_or_size: _UnionT[int, bytes], + size: Optional[int] = ...) -> Array[c_char]: ... +c_buffer = create_string_buffer +def create_unicode_buffer(init_or_size: _UnionT[int, Text], + size: Optional[int] = ...) -> Array[c_wchar]: ... +if sys.platform == 'win32': + def DllCanUnloadNow() -> int: ... + def DllGetClassObject(rclsid: Any, riid: Any, ppv: Any) -> int: ... # TODO not documented + def FormatError(code: int) -> str: ... + def GetLastError() -> int: ... +def get_errno() -> int: ... +if sys.platform == 'win32': + def get_last_error() -> int: ... +def memmove(dst: _CVoidPLike, src: _CVoidConstPLike, count: int) -> None: ... +def memset(dst: _CVoidPLike, c: int, count: int) -> None: ... +def POINTER(type: Type[_CT]) -> Type[pointer[_CT]]: ... + +# The real ctypes.pointer is a function, not a class. The stub version of pointer behaves like +# ctypes._Pointer in that it is the base class for all pointer types. Unlike the real _Pointer, +# it can be instantiated directly (to mimic the behavior of the real pointer function). +class pointer(Generic[_CT], _PointerLike, _CData): + _type_: ClassVar[Type[_CT]] = ... + contents: _CT = ... + def __init__(self, arg: _CT = ...) -> None: ... + @overload + def __getitem__(self, i: int) -> _CT: ... + @overload + def __getitem__(self, s: slice) -> List[_CT]: ... + @overload + def __setitem__(self, i: int, o: _CT) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[_CT]) -> None: ... + +def resize(obj: _CData, size: int) -> None: ... +if sys.version_info < (3,): + def set_conversion_mode(encoding: str, errors: str) -> Tuple[str, str]: ... +def set_errno(value: int) -> int: ... +if sys.platform == 'win32': + def set_last_error(value: int) -> int: ... +def sizeof(obj_or_type: _UnionT[_CData, Type[_CData]]) -> int: ... +def string_at(address: _CVoidConstPLike, size: int = ...) -> bytes: ... +if sys.platform == 'win32': + def WinError(code: Optional[int] = ..., + desc: Optional[str] = ...) -> WindowsError: ... +def wstring_at(address: _CVoidConstPLike, size: int = ...) -> str: ... + +class _SimpleCData(Generic[_T], _CData): + value: _T = ... + def __init__(self, value: _T = ...) -> None: ... + +class c_byte(_SimpleCData[int]): ... + +class c_char(_SimpleCData[bytes]): + def __init__(self, value: _UnionT[int, bytes] = ...) -> None: ... +class c_char_p(_PointerLike, _SimpleCData[Optional[bytes]]): + def __init__(self, value: Optional[_UnionT[int, bytes]] = ...) -> None: ... + +class c_double(_SimpleCData[float]): ... +class c_longdouble(_SimpleCData[float]): ... +class c_float(_SimpleCData[float]): ... + +class c_int(_SimpleCData[int]): ... +class c_int8(_SimpleCData[int]): ... +class c_int16(_SimpleCData[int]): ... +class c_int32(_SimpleCData[int]): ... +class c_int64(_SimpleCData[int]): ... + +class c_long(_SimpleCData[int]): ... +class c_longlong(_SimpleCData[int]): ... + +class c_short(_SimpleCData[int]): ... + +class c_size_t(_SimpleCData[int]): ... +class c_ssize_t(_SimpleCData[int]): ... + +class c_ubyte(_SimpleCData[int]): ... + +class c_uint(_SimpleCData[int]): ... +class c_uint8(_SimpleCData[int]): ... +class c_uint16(_SimpleCData[int]): ... +class c_uint32(_SimpleCData[int]): ... +class c_uint64(_SimpleCData[int]): ... + +class c_ulong(_SimpleCData[int]): ... +class c_ulonglong(_SimpleCData[int]): ... + +class c_ushort(_SimpleCData[int]): ... + +class c_void_p(_PointerLike, _SimpleCData[Optional[int]]): ... + +class c_wchar(_SimpleCData[Text]): ... +class c_wchar_p(_PointerLike, _SimpleCData[Optional[Text]]): + def __init__(self, value: Optional[_UnionT[int, Text]] = ...) -> None: ... + +class c_bool(_SimpleCData[bool]): + def __init__(self, value: bool) -> None: ... + +if sys.platform == 'win32': + class HRESULT(_SimpleCData[int]): ... # TODO undocumented + +class py_object(_SimpleCData[_T]): ... + +class _CField: + offset: int = ... + size: int = ... +class _StructUnionMeta(_CDataMeta): + _fields_: Sequence[_UnionT[Tuple[str, Type[_CData]], Tuple[str, Type[_CData], int]]] = ... + _pack_: int = ... + _anonymous_: Sequence[str] = ... + def __getattr__(self, name: str) -> _CField: ... +class _StructUnionBase(_CData, metaclass=_StructUnionMeta): + def __init__(self, *args: Any, **kw: Any) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + +class Union(_StructUnionBase): ... +class Structure(_StructUnionBase): ... +class BigEndianStructure(Structure): ... +class LittleEndianStructure(Structure): ... + +class Array(Generic[_CT], _CData): + _length_: ClassVar[int] = ... + _type_: ClassVar[Type[_CT]] = ... + raw: bytes = ... # Note: only available if _CT == c_char + value: Any = ... # Note: bytes if _CT == c_char, Text if _CT == c_wchar, unavailable otherwise + # TODO These methods cannot be annotated correctly at the moment. + # All of these "Any"s stand for the array's element type, but it's not possible to use _CT + # here, because of a special feature of ctypes. + # By default, when accessing an element of an Array[_CT], the returned object has type _CT. + # However, when _CT is a "simple type" like c_int, ctypes automatically "unboxes" the object + # and converts it to the corresponding Python primitive. For example, when accessing an element + # of an Array[c_int], a Python int object is returned, not a c_int. + # This behavior does *not* apply to subclasses of "simple types". + # If MyInt is a subclass of c_int, then accessing an element of an Array[MyInt] returns + # a MyInt, not an int. + # This special behavior is not easy to model in a stub, so for now all places where + # the array element type would belong are annotated with Any instead. + def __init__(self, *args: Any) -> None: ... + @overload + def __getitem__(self, i: int) -> Any: ... + @overload + def __getitem__(self, s: slice) -> List[Any]: ... + @overload + def __setitem__(self, i: int, o: Any) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[Any]) -> None: ... + def __iter__(self) -> Iterator[Any]: ... + # Can't inherit from Sized because the metaclass conflict between + # Sized and _CData prevents using _CDataMeta. + def __len__(self) -> int: ... diff --git a/client/typeshed-fallback/stdlib/2and3/ctypes/util.pyi b/client/typeshed-fallback/stdlib/2and3/ctypes/util.pyi new file mode 100644 index 000000000..7077d9d2f --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/ctypes/util.pyi @@ -0,0 +1,8 @@ +# Stubs for ctypes.util + +from typing import Optional +import sys + +def find_library(name: str) -> Optional[str]: ... +if sys.platform == 'win32': + def find_msvcrt() -> Optional[str]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/ctypes/wintypes.pyi b/client/typeshed-fallback/stdlib/2and3/ctypes/wintypes.pyi new file mode 100644 index 000000000..c5a6226b2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/ctypes/wintypes.pyi @@ -0,0 +1,209 @@ +from ctypes import ( + _SimpleCData, Array, Structure, c_byte, c_char, c_char_p, c_double, c_float, c_int, c_long, + c_longlong, c_short, c_uint, c_ulong, c_ulonglong, c_ushort, c_void_p, c_wchar, c_wchar_p, + pointer, +) + +BYTE = c_byte +WORD = c_ushort +DWORD = c_ulong +CHAR = c_char +WCHAR = c_wchar +UINT = c_uint +INT = c_int +DOUBLE = c_double +FLOAT = c_float +BOOLEAN = BYTE +BOOL = c_long +class VARIANT_BOOL(_SimpleCData[bool]): ... +ULONG = c_ulong +LONG = c_long +USHORT = c_ushort +SHORT = c_short +LARGE_INTEGER = c_longlong +_LARGE_INTEGER = c_longlong +ULARGE_INTEGER = c_ulonglong +_ULARGE_INTEGER = c_ulonglong + +OLESTR = c_wchar_p +LPOLESTR = c_wchar_p +LPCOLESTR = c_wchar_p +LPWSTR = c_wchar_p +LPCWSTR = c_wchar_p +LPSTR = c_char_p +LPCSTR = c_char_p +LPVOID = c_void_p +LPCVOID = c_void_p + +# These two types are pointer-sized unsigned and signed ints, respectively. +# At runtime, they are either c_[u]long or c_[u]longlong, depending on the host's pointer size +# (they are not really separate classes). +class WPARAM(_SimpleCData[int]): ... +class LPARAM(_SimpleCData[int]): ... + +ATOM = WORD +LANGID = WORD +COLORREF = DWORD +LGRPID = DWORD +LCTYPE = DWORD +LCID = DWORD + +HANDLE = c_void_p +HACCEL = HANDLE +HBITMAP = HANDLE +HBRUSH = HANDLE +HCOLORSPACE = HANDLE +HDC = HANDLE +HDESK = HANDLE +HDWP = HANDLE +HENHMETAFILE = HANDLE +HFONT = HANDLE +HGDIOBJ = HANDLE +HGLOBAL = HANDLE +HHOOK = HANDLE +HICON = HANDLE +HINSTANCE = HANDLE +HKEY = HANDLE +HKL = HANDLE +HLOCAL = HANDLE +HMENU = HANDLE +HMETAFILE = HANDLE +HMODULE = HANDLE +HMONITOR = HANDLE +HPALETTE = HANDLE +HPEN = HANDLE +HRGN = HANDLE +HRSRC = HANDLE +HSTR = HANDLE +HTASK = HANDLE +HWINSTA = HANDLE +HWND = HANDLE +SC_HANDLE = HANDLE +SERVICE_STATUS_HANDLE = HANDLE + +class RECT(Structure): + left: LONG + top: LONG + right: LONG + bottom: LONG +RECTL = RECT +_RECTL = RECT +tagRECT = RECT + +class _SMALL_RECT(Structure): + Left: SHORT + Top: SHORT + Right: SHORT + Bottom: SHORT +SMALL_RECT = _SMALL_RECT + +class _COORD(Structure): + X: SHORT + Y: SHORT + +class POINT(Structure): + x: LONG + y: LONG +POINTL = POINT +_POINTL = POINT +tagPOINT = POINT + +class SIZE(Structure): + cx: LONG + cy: LONG +SIZEL = SIZE +tagSIZE = SIZE + +def RGB(red: int, green: int, blue: int) -> int: ... + +class FILETIME(Structure): + dwLowDateTime: DWORD + dwHighDateTime: DWORD +_FILETIME = FILETIME + +class MSG(Structure): + hWnd: HWND + message: UINT + wParam: WPARAM + lParam: LPARAM + time: DWORD + pt: POINT +tagMSG = MSG +MAX_PATH: int + +class WIN32_FIND_DATAA(Structure): + dwFileAttributes: DWORD + ftCreationTime: FILETIME + ftLastAccessTime: FILETIME + ftLastWriteTime: FILETIME + nFileSizeHigh: DWORD + nFileSizeLow: DWORD + dwReserved0: DWORD + dwReserved1: DWORD + cFileName: Array[CHAR] + cAlternateFileName: Array[CHAR] + +class WIN32_FIND_DATAW(Structure): + dwFileAttributes: DWORD + ftCreationTime: FILETIME + ftLastAccessTime: FILETIME + ftLastWriteTime: FILETIME + nFileSizeHigh: DWORD + nFileSizeLow: DWORD + dwReserved0: DWORD + dwReserved1: DWORD + cFileName: Array[WCHAR] + cAlternateFileName: Array[WCHAR] + +# These pointer type definitions use pointer[...] instead of POINTER(...), to allow them +# to be used in type annotations. +PBOOL = pointer[BOOL] +LPBOOL = pointer[BOOL] +PBOOLEAN = pointer[BOOLEAN] +PBYTE = pointer[BYTE] +LPBYTE = pointer[BYTE] +PCHAR = pointer[CHAR] +LPCOLORREF = pointer[COLORREF] +PDWORD = pointer[DWORD] +LPDWORD = pointer[DWORD] +PFILETIME = pointer[FILETIME] +LPFILETIME = pointer[FILETIME] +PFLOAT = pointer[FLOAT] +PHANDLE = pointer[HANDLE] +LPHANDLE = pointer[HANDLE] +PHKEY = pointer[HKEY] +LPHKL = pointer[HKL] +PINT = pointer[INT] +LPINT = pointer[INT] +PLARGE_INTEGER = pointer[LARGE_INTEGER] +PLCID = pointer[LCID] +PLONG = pointer[LONG] +LPLONG = pointer[LONG] +PMSG = pointer[MSG] +LPMSG = pointer[MSG] +PPOINT = pointer[POINT] +LPPOINT = pointer[POINT] +PPOINTL = pointer[POINTL] +PRECT = pointer[RECT] +LPRECT = pointer[RECT] +PRECTL = pointer[RECTL] +LPRECTL = pointer[RECTL] +LPSC_HANDLE = pointer[SC_HANDLE] +PSHORT = pointer[SHORT] +PSIZE = pointer[SIZE] +LPSIZE = pointer[SIZE] +PSIZEL = pointer[SIZEL] +LPSIZEL = pointer[SIZEL] +PSMALL_RECT = pointer[SMALL_RECT] +PUINT = pointer[UINT] +LPUINT = pointer[UINT] +PULARGE_INTEGER = pointer[ULARGE_INTEGER] +PULONG = pointer[ULONG] +PUSHORT = pointer[USHORT] +PWCHAR = pointer[WCHAR] +PWIN32_FIND_DATAA = pointer[WIN32_FIND_DATAA] +LPWIN32_FIND_DATAA = pointer[WIN32_FIND_DATAA] +PWIN32_FIND_DATAW = pointer[WIN32_FIND_DATAW] +LPWIN32_FIND_DATAW = pointer[WIN32_FIND_DATAW] +PWORD = pointer[WORD] +LPWORD = pointer[WORD] diff --git a/client/typeshed-fallback/stdlib/2and3/datetime.pyi b/client/typeshed-fallback/stdlib/2and3/datetime.pyi new file mode 100644 index 000000000..ccc92ba35 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/datetime.pyi @@ -0,0 +1,290 @@ +import sys +from time import struct_time +from typing import ( + AnyStr, Optional, SupportsAbs, Tuple, Union, overload, + ClassVar, +) + +if sys.version_info >= (3,): + _Text = str +else: + _Text = Union[str, unicode] + +MINYEAR: int +MAXYEAR: int + +class tzinfo: + def tzname(self, dt: Optional[datetime]) -> Optional[str]: ... + def utcoffset(self, dt: Optional[datetime]) -> Optional[timedelta]: ... + def dst(self, dt: Optional[datetime]) -> Optional[timedelta]: ... + def fromutc(self, dt: datetime) -> datetime: ... + +if sys.version_info >= (3, 2): + class timezone(tzinfo): + utc: ClassVar[timezone] + min: ClassVar[timezone] + max: ClassVar[timezone] + + def __init__(self, offset: timedelta, name: str = ...) -> None: ... + def __hash__(self) -> int: ... + +_tzinfo = tzinfo + +class date: + min: ClassVar[date] + max: ClassVar[date] + resolution: ClassVar[timedelta] + + def __init__(self, year: int, month: int, day: int) -> None: ... + + @classmethod + def fromtimestamp(cls, t: float) -> date: ... + @classmethod + def today(cls) -> date: ... + @classmethod + def fromordinal(cls, n: int) -> date: ... + if sys.version_info >= (3, 7): + @classmethod + def fromisoformat(cls, date_string: str) -> date: ... + + @property + def year(self) -> int: ... + @property + def month(self) -> int: ... + @property + def day(self) -> int: ... + + def ctime(self) -> str: ... + def strftime(self, fmt: _Text) -> str: ... + if sys.version_info >= (3,): + def __format__(self, fmt: str) -> str: ... + else: + def __format__(self, fmt: AnyStr) -> AnyStr: ... + def isoformat(self) -> str: ... + def timetuple(self) -> struct_time: ... + def toordinal(self) -> int: ... + def replace(self, year: int = ..., month: int = ..., day: int = ...) -> date: ... + def __le__(self, other: date) -> bool: ... + def __lt__(self, other: date) -> bool: ... + def __ge__(self, other: date) -> bool: ... + def __gt__(self, other: date) -> bool: ... + def __add__(self, other: timedelta) -> date: ... + @overload + def __sub__(self, other: timedelta) -> date: ... + @overload + def __sub__(self, other: date) -> timedelta: ... + def __hash__(self) -> int: ... + def weekday(self) -> int: ... + def isoweekday(self) -> int: ... + def isocalendar(self) -> Tuple[int, int, int]: ... + +class time: + min: ClassVar[time] + max: ClassVar[time] + resolution: ClassVar[timedelta] + + if sys.version_info >= (3, 6): + def __init__(self, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., + tzinfo: Optional[_tzinfo] = ..., *, fold: int = ...) -> None: ... + else: + def __init__(self, hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., + tzinfo: Optional[_tzinfo] = ...) -> None: ... + + @property + def hour(self) -> int: ... + @property + def minute(self) -> int: ... + @property + def second(self) -> int: ... + @property + def microsecond(self) -> int: ... + @property + def tzinfo(self) -> Optional[_tzinfo]: ... + if sys.version_info >= (3, 6): + @property + def fold(self) -> int: ... + + def __le__(self, other: time) -> bool: ... + def __lt__(self, other: time) -> bool: ... + def __ge__(self, other: time) -> bool: ... + def __gt__(self, other: time) -> bool: ... + def __hash__(self) -> int: ... + def isoformat(self) -> str: ... + if sys.version_info >= (3, 7): + @classmethod + def fromisoformat(cls, time_string: str) -> time: ... + def strftime(self, fmt: _Text) -> str: ... + if sys.version_info >= (3,): + def __format__(self, fmt: str) -> str: ... + else: + def __format__(self, fmt: AnyStr) -> AnyStr: ... + def utcoffset(self) -> Optional[timedelta]: ... + def tzname(self) -> Optional[str]: ... + def dst(self) -> Optional[int]: ... + if sys.version_info >= (3, 6): + def replace(self, hour: int = ..., minute: int = ..., second: int = ..., + microsecond: int = ..., tzinfo: Optional[_tzinfo] = ..., + *, fold: int = ...) -> time: ... + else: + def replace(self, hour: int = ..., minute: int = ..., second: int = ..., + microsecond: int = ..., tzinfo: Optional[_tzinfo] = ...) -> time: ... + +_date = date +_time = time + +class timedelta(SupportsAbs[timedelta]): + min: ClassVar[timedelta] + max: ClassVar[timedelta] + resolution: ClassVar[timedelta] + + if sys.version_info >= (3, 6): + def __init__(self, days: float = ..., seconds: float = ..., microseconds: float = ..., + milliseconds: float = ..., minutes: float = ..., hours: float = ..., + weeks: float = ..., *, fold: int = ...) -> None: ... + else: + def __init__(self, days: float = ..., seconds: float = ..., microseconds: float = ..., + milliseconds: float = ..., minutes: float = ..., hours: float = ..., + weeks: float = ...) -> None: ... + + @property + def days(self) -> int: ... + @property + def seconds(self) -> int: ... + @property + def microseconds(self) -> int: ... + + def total_seconds(self) -> float: ... + def __add__(self, other: timedelta) -> timedelta: ... + def __radd__(self, other: timedelta) -> timedelta: ... + def __sub__(self, other: timedelta) -> timedelta: ... + def __rsub__(self, other: timedelta) -> timedelta: ... + def __neg__(self) -> timedelta: ... + def __pos__(self) -> timedelta: ... + def __abs__(self) -> timedelta: ... + def __mul__(self, other: float) -> timedelta: ... + def __rmul__(self, other: float) -> timedelta: ... + @overload + def __floordiv__(self, other: timedelta) -> int: ... + @overload + def __floordiv__(self, other: int) -> timedelta: ... + if sys.version_info >= (3,): + @overload + def __truediv__(self, other: timedelta) -> float: ... + @overload + def __truediv__(self, other: float) -> timedelta: ... + def __mod__(self, other: timedelta) -> timedelta: ... + def __divmod__(self, other: timedelta) -> Tuple[int, timedelta]: ... + else: + @overload + def __div__(self, other: timedelta) -> float: ... + @overload + def __div__(self, other: float) -> timedelta: ... + def __le__(self, other: timedelta) -> bool: ... + def __lt__(self, other: timedelta) -> bool: ... + def __ge__(self, other: timedelta) -> bool: ... + def __gt__(self, other: timedelta) -> bool: ... + def __hash__(self) -> int: ... + +class datetime(date): + min: ClassVar[datetime] + max: ClassVar[datetime] + resolution: ClassVar[timedelta] + + if sys.version_info >= (3, 6): + def __init__(self, year: int, month: int, day: int, hour: int = ..., + minute: int = ..., second: int = ..., microsecond: int = ..., + tzinfo: Optional[_tzinfo] = ..., *, fold: int = ...) -> None: ... + else: + def __init__(self, year: int, month: int, day: int, hour: int = ..., + minute: int = ..., second: int = ..., microsecond: int = ..., + tzinfo: Optional[_tzinfo] = ...) -> None: ... + + @property + def year(self) -> int: ... + @property + def month(self) -> int: ... + @property + def day(self) -> int: ... + @property + def hour(self) -> int: ... + @property + def minute(self) -> int: ... + @property + def second(self) -> int: ... + @property + def microsecond(self) -> int: ... + @property + def tzinfo(self) -> Optional[_tzinfo]: ... + if sys.version_info >= (3, 6): + @property + def fold(self) -> int: ... + + @classmethod + def fromtimestamp(cls, t: float, tz: Optional[_tzinfo] = ...) -> datetime: ... + @classmethod + def utcfromtimestamp(cls, t: float) -> datetime: ... + @classmethod + def today(cls) -> datetime: ... + @classmethod + def fromordinal(cls, n: int) -> datetime: ... + @classmethod + def now(cls, tz: Optional[_tzinfo] = ...) -> datetime: ... + @classmethod + def utcnow(cls) -> datetime: ... + if sys.version_info >= (3, 6): + @classmethod + def combine(cls, date: date, time: time, tzinfo: Optional[_tzinfo] = ...) -> datetime: ... + else: + @classmethod + def combine(cls, date: date, time: time) -> datetime: ... + if sys.version_info >= (3, 7): + @classmethod + def fromisoformat(cls, date_string: str) -> datetime: ... + def strftime(self, fmt: _Text) -> str: ... + if sys.version_info >= (3,): + def __format__(self, fmt: str) -> str: ... + else: + def __format__(self, fmt: AnyStr) -> AnyStr: ... + def toordinal(self) -> int: ... + def timetuple(self) -> struct_time: ... + if sys.version_info >= (3, 3): + def timestamp(self) -> float: ... + def utctimetuple(self) -> struct_time: ... + def date(self) -> _date: ... + def time(self) -> _time: ... + def timetz(self) -> _time: ... + if sys.version_info >= (3, 6): + def replace(self, year: int = ..., month: int = ..., day: int = ..., hour: int = ..., + minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: + Optional[_tzinfo] = ..., *, fold: int = ...) -> datetime: ... + else: + def replace(self, year: int = ..., month: int = ..., day: int = ..., hour: int = ..., + minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: + Optional[_tzinfo] = ...) -> datetime: ... + if sys.version_info >= (3, 3): + def astimezone(self, tz: Optional[_tzinfo] = ...) -> datetime: ... + else: + def astimezone(self, tz: _tzinfo) -> datetime: ... + def ctime(self) -> str: ... + if sys.version_info >= (3, 6): + def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... + else: + def isoformat(self, sep: str = ...) -> str: ... + @classmethod + def strptime(cls, date_string: _Text, format: _Text) -> datetime: ... + def utcoffset(self) -> Optional[timedelta]: ... + def tzname(self) -> Optional[str]: ... + def dst(self) -> Optional[timedelta]: ... + def __le__(self, other: datetime) -> bool: ... # type: ignore + def __lt__(self, other: datetime) -> bool: ... # type: ignore + def __ge__(self, other: datetime) -> bool: ... # type: ignore + def __gt__(self, other: datetime) -> bool: ... # type: ignore + def __add__(self, other: timedelta) -> datetime: ... + @overload # type: ignore + def __sub__(self, other: datetime) -> timedelta: ... + @overload + def __sub__(self, other: timedelta) -> datetime: ... + def __hash__(self) -> int: ... + def weekday(self) -> int: ... + def isoweekday(self) -> int: ... + def isocalendar(self) -> Tuple[int, int, int]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/decimal.pyi b/client/typeshed-fallback/stdlib/2and3/decimal.pyi new file mode 100644 index 000000000..6adff15d0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/decimal.pyi @@ -0,0 +1,317 @@ +import numbers +import sys +from types import TracebackType +from typing import ( + Any, Container, Dict, List, NamedTuple, Optional, overload, Sequence, Text, Tuple, Type, TypeVar, Union, +) + +_Decimal = Union[Decimal, int] +_DecimalNew = Union[Decimal, float, Text, Tuple[int, Sequence[int], int]] +if sys.version_info >= (3,): + _ComparableNum = Union[Decimal, float, numbers.Rational] +else: + _ComparableNum = Union[Decimal, float] +_DecimalT = TypeVar('_DecimalT', bound=Decimal) + +DecimalTuple = NamedTuple('DecimalTuple', + [('sign', int), + ('digits', Tuple[int, ...]), + ('exponent', int)]) + +ROUND_DOWN: str +ROUND_HALF_UP: str +ROUND_HALF_EVEN: str +ROUND_CEILING: str +ROUND_FLOOR: str +ROUND_UP: str +ROUND_HALF_DOWN: str +ROUND_05UP: str + +if sys.version_info >= (3,): + HAVE_THREADS: bool + MAX_EMAX: int + MAX_PREC: int + MIN_EMIN: int + MIN_ETINY: int + +class DecimalException(ArithmeticError): + def handle(self, context: Context, *args: Any) -> Optional[Decimal]: ... + +class Clamped(DecimalException): ... + +class InvalidOperation(DecimalException): ... + +class ConversionSyntax(InvalidOperation): ... + +class DivisionByZero(DecimalException, ZeroDivisionError): ... + +class DivisionImpossible(InvalidOperation): ... + +class DivisionUndefined(InvalidOperation, ZeroDivisionError): ... + +class Inexact(DecimalException): ... + +class InvalidContext(InvalidOperation): ... + +class Rounded(DecimalException): ... + +class Subnormal(DecimalException): ... + +class Overflow(Inexact, Rounded): ... + +class Underflow(Inexact, Rounded, Subnormal): ... + +if sys.version_info >= (3,): + class FloatOperation(DecimalException, TypeError): ... + +def setcontext(context: Context) -> None: ... +def getcontext() -> Context: ... +def localcontext(ctx: Optional[Context] = ...) -> _ContextManager: ... + +class Decimal(object): + def __new__(cls: Type[_DecimalT], value: _DecimalNew = ..., context: Optional[Context] = ...) -> _DecimalT: ... + @classmethod + def from_float(cls, f: float) -> Decimal: ... + if sys.version_info >= (3,): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + def __eq__(self, other: object, context: Optional[Context] = ...) -> bool: ... + if sys.version_info < (3,): + def __ne__(self, other: object, context: Optional[Context] = ...) -> bool: ... + def __lt__(self, other: _ComparableNum, context: Optional[Context] = ...) -> bool: ... + def __le__(self, other: _ComparableNum, context: Optional[Context] = ...) -> bool: ... + def __gt__(self, other: _ComparableNum, context: Optional[Context] = ...) -> bool: ... + def __ge__(self, other: _ComparableNum, context: Optional[Context] = ...) -> bool: ... + def compare(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __hash__(self) -> int: ... + def as_tuple(self) -> DecimalTuple: ... + if sys.version_info >= (3,): + def as_integer_ratio(self) -> Tuple[int, int]: ... + def __str__(self, eng: bool = ..., context: Optional[Context] = ...) -> str: ... + def to_eng_string(self, context: Optional[Context] = ...) -> str: ... + def __neg__(self, context: Optional[Context] = ...) -> Decimal: ... + def __pos__(self, context: Optional[Context] = ...) -> Decimal: ... + def __abs__(self, round: bool = ..., context: Optional[Context] = ...) -> Decimal: ... + def __add__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __radd__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __sub__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __rsub__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __mul__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __rmul__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __truediv__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __rtruediv__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + if sys.version_info < (3,): + def __div__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __rdiv__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __divmod__(self, other: _Decimal, context: Optional[Context] = ...) -> Tuple[Decimal, Decimal]: ... + def __rdivmod__(self, other: _Decimal, context: Optional[Context] = ...) -> Tuple[Decimal, Decimal]: ... + def __mod__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __rmod__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def remainder_near(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __floordiv__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __rfloordiv__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + def __trunc__(self) -> int: ... + @property + def real(self) -> Decimal: ... + @property + def imag(self) -> Decimal: ... + def conjugate(self) -> Decimal: ... + def __complex__(self) -> complex: ... + if sys.version_info >= (3,): + @overload + def __round__(self) -> int: ... + @overload + def __round__(self, ndigits: None) -> int: ... + @overload + def __round__(self, ndigits: int) -> Decimal: ... + def __floor__(self) -> int: ... + def __ceil__(self) -> int: ... + else: + def __long__(self) -> long: ... + def fma(self, other: _Decimal, third: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __pow__(self, other: _Decimal, modulo: Optional[_Decimal] = ..., context: Optional[Context] = ...) -> Decimal: ... + def __rpow__(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def normalize(self, context: Optional[Context] = ...) -> Decimal: ... + if sys.version_info >= (3,): + def quantize(self, exp: _Decimal, rounding: Optional[str] = ..., + context: Optional[Context] = ...) -> Decimal: ... + def same_quantum(self, other: _Decimal, context: Optional[Context] = ...) -> bool: ... + else: + def quantize(self, exp: _Decimal, rounding: Optional[str] = ..., + context: Optional[Context] = ..., watchexp: bool = ...) -> Decimal: ... + def same_quantum(self, other: _Decimal) -> bool: ... + def to_integral_exact(self, rounding: Optional[str] = ..., context: Optional[Context] = ...) -> Decimal: ... + def to_integral_value(self, rounding: Optional[str] = ..., context: Optional[Context] = ...) -> Decimal: ... + def to_integral(self, rounding: Optional[str] = ..., context: Optional[Context] = ...) -> Decimal: ... + def sqrt(self, context: Optional[Context] = ...) -> Decimal: ... + def max(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def min(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def adjusted(self) -> int: ... + if sys.version_info >= (3,): + def canonical(self) -> Decimal: ... + else: + def canonical(self, context: Optional[Context] = ...) -> Decimal: ... + def compare_signal(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + if sys.version_info >= (3,): + def compare_total(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def compare_total_mag(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + else: + def compare_total(self, other: _Decimal) -> Decimal: ... + def compare_total_mag(self, other: _Decimal) -> Decimal: ... + def copy_abs(self) -> Decimal: ... + def copy_negate(self) -> Decimal: ... + if sys.version_info >= (3,): + def copy_sign(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + else: + def copy_sign(self, other: _Decimal) -> Decimal: ... + def exp(self, context: Optional[Context] = ...) -> Decimal: ... + def is_canonical(self) -> bool: ... + def is_finite(self) -> bool: ... + def is_infinite(self) -> bool: ... + def is_nan(self) -> bool: ... + def is_normal(self, context: Optional[Context] = ...) -> bool: ... + def is_qnan(self) -> bool: ... + def is_signed(self) -> bool: ... + def is_snan(self) -> bool: ... + def is_subnormal(self, context: Optional[Context] = ...) -> bool: ... + def is_zero(self) -> bool: ... + def ln(self, context: Optional[Context] = ...) -> Decimal: ... + def log10(self, context: Optional[Context] = ...) -> Decimal: ... + def logb(self, context: Optional[Context] = ...) -> Decimal: ... + def logical_and(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def logical_invert(self, context: Optional[Context] = ...) -> Decimal: ... + def logical_or(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def logical_xor(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def max_mag(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def min_mag(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def next_minus(self, context: Optional[Context] = ...) -> Decimal: ... + def next_plus(self, context: Optional[Context] = ...) -> Decimal: ... + def next_toward(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def number_class(self, context: Optional[Context] = ...) -> str: ... + def radix(self) -> Decimal: ... + def rotate(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def scaleb(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def shift(self, other: _Decimal, context: Optional[Context] = ...) -> Decimal: ... + def __reduce__(self) -> Tuple[Type[Decimal], Tuple[str]]: ... + def __copy__(self) -> Decimal: ... + def __deepcopy__(self, memo: Any) -> Decimal: ... + def __format__(self, specifier: str, context: Optional[Context] = ...) -> str: ... + +class _ContextManager(object): + new_context: Context + saved_context: Context + def __init__(self, new_context: Context) -> None: ... + def __enter__(self) -> Context: ... + def __exit__(self, t: Optional[Type[BaseException]], v: Optional[BaseException], tb: Optional[TracebackType]) -> None: ... + +_TrapType = Type[DecimalException] + +class Context(object): + prec: int + rounding: str + Emin: int + Emax: int + capitals: int + if sys.version_info >= (3,): + clamp: int + else: + _clamp: int + traps: Dict[_TrapType, bool] + flags: Dict[_TrapType, bool] + if sys.version_info >= (3,): + def __init__(self, prec: Optional[int] = ..., rounding: Optional[str] = ..., + Emin: Optional[int] = ..., Emax: Optional[int] = ..., + capitals: Optional[int] = ..., clamp: Optional[int] = ..., + flags: Union[None, Dict[_TrapType, bool], Container[_TrapType]] = ..., + traps: Union[None, Dict[_TrapType, bool], Container[_TrapType]] = ..., + _ignored_flags: Optional[List[_TrapType]] = ...) -> None: ... + else: + def __init__(self, prec: Optional[int] = ..., rounding: Optional[str] = ..., + traps: Union[None, Dict[_TrapType, bool], Container[_TrapType]] = ..., + flags: Union[None, Dict[_TrapType, bool], Container[_TrapType]] = ..., + Emin: Optional[int] = ..., Emax: Optional[int] = ..., + capitals: Optional[int] = ..., _clamp: Optional[int] = ..., + _ignored_flags: Optional[List[_TrapType]] = ...) -> None: ... + if sys.version_info >= (3,): + # __setattr__() only allows to set a specific set of attributes, + # already defined above. + def __delattr__(self, name: str) -> None: ... + def __reduce__(self) -> Tuple[Type[Context], Tuple[Any, ...]]: ... + def clear_flags(self) -> None: ... + if sys.version_info >= (3,): + def clear_traps(self) -> None: ... + def copy(self) -> Context: ... + def __copy__(self) -> Context: ... + __hash__: Any = ... + def Etiny(self) -> int: ... + def Etop(self) -> int: ... + def create_decimal(self, num: _DecimalNew = ...) -> Decimal: ... + def create_decimal_from_float(self, f: float) -> Decimal: ... + def abs(self, a: _Decimal) -> Decimal: ... + def add(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def canonical(self, a: Decimal) -> Decimal: ... + def compare(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def compare_signal(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def compare_total(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def compare_total_mag(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def copy_abs(self, a: _Decimal) -> Decimal: ... + def copy_decimal(self, a: _Decimal) -> Decimal: ... + def copy_negate(self, a: _Decimal) -> Decimal: ... + def copy_sign(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def divide(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def divide_int(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def divmod(self, a: _Decimal, b: _Decimal) -> Tuple[Decimal, Decimal]: ... + def exp(self, a: _Decimal) -> Decimal: ... + def fma(self, a: _Decimal, b: _Decimal, c: _Decimal) -> Decimal: ... + def is_canonical(self, a: _Decimal) -> bool: ... + def is_finite(self, a: _Decimal) -> bool: ... + def is_infinite(self, a: _Decimal) -> bool: ... + def is_nan(self, a: _Decimal) -> bool: ... + def is_normal(self, a: _Decimal) -> bool: ... + def is_qnan(self, a: _Decimal) -> bool: ... + def is_signed(self, a: _Decimal) -> bool: ... + def is_snan(self, a: _Decimal) -> bool: ... + def is_subnormal(self, a: _Decimal) -> bool: ... + def is_zero(self, a: _Decimal) -> bool: ... + def ln(self, a: _Decimal) -> Decimal: ... + def log10(self, a: _Decimal) -> Decimal: ... + def logb(self, a: _Decimal) -> Decimal: ... + def logical_and(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def logical_invert(self, a: _Decimal) -> Decimal: ... + def logical_or(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def logical_xor(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def max(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def max_mag(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def min(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def min_mag(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def minus(self, a: _Decimal) -> Decimal: ... + def multiply(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def next_minus(self, a: _Decimal) -> Decimal: ... + def next_plus(self, a: _Decimal) -> Decimal: ... + def next_toward(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def normalize(self, a: _Decimal) -> Decimal: ... + def number_class(self, a: _Decimal) -> str: ... + def plus(self, a: _Decimal) -> Decimal: ... + def power(self, a: _Decimal, b: _Decimal, modulo: Optional[_Decimal] = ...) -> Decimal: ... + def quantize(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def radix(self) -> Decimal: ... + def remainder(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def remainder_near(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def rotate(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def same_quantum(self, a: _Decimal, b: _Decimal) -> bool: ... + def scaleb(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def shift(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def sqrt(self, a: _Decimal) -> Decimal: ... + def subtract(self, a: _Decimal, b: _Decimal) -> Decimal: ... + def to_eng_string(self, a: _Decimal) -> str: ... + def to_sci_string(self, a: _Decimal) -> str: ... + def to_integral_exact(self, a: _Decimal) -> Decimal: ... + def to_integral_value(self, a: _Decimal) -> Decimal: ... + def to_integral(self, a: _Decimal) -> Decimal: ... + +DefaultContext: Context +BasicContext: Context +ExtendedContext: Context diff --git a/client/typeshed-fallback/stdlib/2and3/difflib.pyi b/client/typeshed-fallback/stdlib/2and3/difflib.pyi new file mode 100644 index 000000000..ddcec11dd --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/difflib.pyi @@ -0,0 +1,87 @@ +# Based on https://docs.python.org/2.7/library/difflib.html and https://docs.python.org/3.2/library/difflib.html + +import sys +from typing import ( + TypeVar, Callable, Iterable, Iterator, List, NamedTuple, Sequence, Tuple, + Generic, Optional, Text, Union, AnyStr +) + +_T = TypeVar('_T') + +if sys.version_info >= (3,): + _StrType = Text +else: + # Aliases can't point to type vars, so we need to redeclare AnyStr + _StrType = TypeVar('_StrType', Text, bytes) + +_JunkCallback = Union[Callable[[Text], bool], Callable[[str], bool]] + +Match = NamedTuple('Match', [ + ('a', int), + ('b', int), + ('size', int), +]) + +class SequenceMatcher(Generic[_T]): + def __init__(self, isjunk: Optional[Callable[[_T], bool]] = ..., + a: Sequence[_T] = ..., b: Sequence[_T] = ..., + autojunk: bool = ...) -> None: ... + def set_seqs(self, a: Sequence[_T], b: Sequence[_T]) -> None: ... + def set_seq1(self, a: Sequence[_T]) -> None: ... + def set_seq2(self, b: Sequence[_T]) -> None: ... + def find_longest_match(self, alo: int, ahi: int, blo: int, + bhi: int) -> Match: ... + def get_matching_blocks(self) -> List[Match]: ... + def get_opcodes(self) -> List[Tuple[str, int, int, int, int]]: ... + def get_grouped_opcodes(self, n: int = ... + ) -> Iterable[List[Tuple[str, int, int, int, int]]]: ... + def ratio(self) -> float: ... + def quick_ratio(self) -> float: ... + def real_quick_ratio(self) -> float: ... + +def get_close_matches(word: Sequence[_T], possibilities: Iterable[Sequence[_T]], + n: int = ..., cutoff: float = ...) -> List[Sequence[_T]]: ... + +class Differ: + def __init__(self, linejunk: _JunkCallback = ..., charjunk: _JunkCallback = ...) -> None: ... + def compare(self, a: Sequence[_StrType], b: Sequence[_StrType]) -> Iterator[_StrType]: ... + +def IS_LINE_JUNK(line: _StrType) -> bool: ... +def IS_CHARACTER_JUNK(line: _StrType) -> bool: ... +def unified_diff(a: Sequence[_StrType], b: Sequence[_StrType], fromfile: _StrType = ..., + tofile: _StrType = ..., fromfiledate: _StrType = ..., tofiledate: _StrType = ..., + n: int = ..., lineterm: _StrType = ...) -> Iterator[_StrType]: ... +def context_diff(a: Sequence[_StrType], b: Sequence[_StrType], fromfile: _StrType = ..., + tofile: _StrType = ..., fromfiledate: _StrType = ..., tofiledate: _StrType = ..., + n: int = ..., lineterm: _StrType = ...) -> Iterator[_StrType]: ... +def ndiff(a: Sequence[_StrType], b: Sequence[_StrType], + linejunk: _JunkCallback = ..., + charjunk: _JunkCallback = ... + ) -> Iterator[_StrType]: ... + +class HtmlDiff(object): + def __init__(self, tabsize: int = ..., wrapcolumn: int = ..., + linejunk: _JunkCallback = ..., + charjunk: _JunkCallback = ... + ) -> None: ... + def make_file(self, fromlines: Sequence[_StrType], tolines: Sequence[_StrType], + fromdesc: _StrType = ..., todesc: _StrType = ..., context: bool = ..., + numlines: int = ...) -> _StrType: ... + def make_table(self, fromlines: Sequence[_StrType], tolines: Sequence[_StrType], + fromdesc: _StrType = ..., todesc: _StrType = ..., context: bool = ..., + numlines: int = ...) -> _StrType: ... + +def restore(delta: Iterable[_StrType], which: int) -> Iterator[_StrType]: ... + +if sys.version_info >= (3, 5): + def diff_bytes( + dfunc: Callable[[Sequence[str], Sequence[str], str, str, str, str, int, str], Iterator[str]], + a: Sequence[bytes], + b: Sequence[bytes], + fromfile: bytes = ..., + tofile: bytes = ..., + fromfiledate: bytes = ..., + tofiledate: bytes = ..., + n: int = ..., + lineterm: bytes = ... + ) -> Iterator[bytes]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/dis.pyi b/client/typeshed-fallback/stdlib/2and3/dis.pyi new file mode 100644 index 000000000..9aeb7dd8a --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/dis.pyi @@ -0,0 +1,75 @@ +from typing import List, Union, Iterator, Tuple, Optional, Any, IO, NamedTuple, Dict + +import sys +import types + +from opcode import (hasconst as hasconst, hasname as hasname, hasjrel as hasjrel, + hasjabs as hasjabs, haslocal as haslocal, hascompare as hascompare, + hasfree as hasfree, cmp_op as cmp_op, opname as opname, opmap as opmap, + HAVE_ARGUMENT as HAVE_ARGUMENT, EXTENDED_ARG as EXTENDED_ARG) + +if sys.version_info >= (3, 4): + from opcode import stack_effect as stack_effect + +if sys.version_info >= (3, 6): + from opcode import hasnargs as hasnargs + +_have_code = Union[types.MethodType, types.FunctionType, types.CodeType, type] +_have_code_or_string = Union[_have_code, str, bytes] + + +if sys.version_info >= (3, 4): + Instruction = NamedTuple( + "Instruction", + [ + ('opname', str), + ('opcode', int), + ('arg', Optional[int]), + ('argval', Any), + ('argrepr', str), + ('offset', int), + ('starts_line', Optional[int]), + ('is_jump_target', bool) + ] + ) + + class Bytecode: + codeobj = ... # type: types.CodeType + first_line = ... # type: int + def __init__(self, x: _have_code_or_string, *, first_line: Optional[int] = ..., + current_offset: Optional[int] = ...) -> None: ... + def __iter__(self) -> Iterator[Instruction]: ... + def __repr__(self) -> str: ... + def info(self) -> str: ... + def dis(self) -> str: ... + + @classmethod + def from_traceback(cls, tb: types.TracebackType) -> Bytecode: ... + + +COMPILER_FLAG_NAMES = ... # type: Dict[int, str] + + +def findlabels(code: _have_code) -> List[int]: ... +def findlinestarts(code: _have_code) -> Iterator[Tuple[int, int]]: ... + +if sys.version_info >= (3, 0): + def pretty_flags(flags: int) -> str: ... + def code_info(x: _have_code_or_string) -> str: ... + +if sys.version_info >= (3, 4): + def dis(x: _have_code_or_string = ..., *, file: Optional[IO[str]] = ...) -> None: ... + def distb(tb: Optional[types.TracebackType] = ..., *, file: Optional[IO[str]] = ...) -> None: ... + def disassemble(co: _have_code, lasti: int = ..., *, file: Optional[IO[str]] = ...) -> None: ... + def disco(co: _have_code, lasti: int = ..., *, file: Optional[IO[str]] = ...) -> None: ... + def show_code(co: _have_code, *, file: Optional[IO[str]] = ...) -> None: ... + + def get_instructions(x: _have_code, *, first_line: Optional[int] = ...) -> Iterator[Instruction]: ... +else: + def dis(x: _have_code_or_string = ...) -> None: ... + def distb(tb: types.TracebackType = ...) -> None: ... + def disassemble(co: _have_code, lasti: int = ...) -> None: ... + def disco(co: _have_code, lasti: int = ...) -> None: ... + + if sys.version_info >= (3, 0): + def show_code(co: _have_code) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/__init__.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/__init__.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/archive_util.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/archive_util.pyi new file mode 100644 index 000000000..12172f3f2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/archive_util.pyi @@ -0,0 +1,12 @@ +# Stubs for distutils.archive_util + +from typing import Optional + + +def make_archive(base_name: str, format: str, root_dir: Optional[str] = ..., + base_dir: Optional[str] = ..., verbose: int = ..., + dry_run: int = ...) -> str: ... +def make_tarball(base_name: str, base_dir: str, compress: Optional[str] = ..., + verbose: int = ..., dry_run: int = ...) -> str: ... +def make_zipfile(base_name: str, base_dir: str, verbose: int = ..., + dry_run: int = ...) -> str: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/bcppcompiler.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/bcppcompiler.pyi new file mode 100644 index 000000000..9f27a0ae0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/bcppcompiler.pyi @@ -0,0 +1,6 @@ +# Stubs for distutils.bcppcompiler + +from distutils.ccompiler import CCompiler + + +class BCPPCompiler(CCompiler): ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/ccompiler.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/ccompiler.pyi new file mode 100644 index 000000000..94fad8bac --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/ccompiler.pyi @@ -0,0 +1,119 @@ +# Stubs for distutils.ccompiler + +from typing import Any, Callable, List, Optional, Tuple, Union + + +_Macro = Union[Tuple[str], Tuple[str, str]] + + +def gen_lib_options(compiler: CCompiler, library_dirs: List[str], + runtime_library_dirs: List[str], + libraries: List[str]) -> List[str]: ... +def gen_preprocess_options(macros: List[_Macro], + include_dirs: List[str]) -> List[str]: ... +def get_default_compiler(osname: Optional[str] = ..., + platform: Optional[str] = ...) -> str: ... +def new_compiler(plat: Optional[str] = ..., compiler: Optional[str] = ..., + verbose: int = ..., dry_run: int = ..., + force: int = ...) -> CCompiler: ... +def show_compilers() -> None: ... + +class CCompiler: + def __init__(self, verbose: int = ..., dry_run: int = ..., + force: int = ...) -> None: ... + def add_include_dir(self, dir: str) -> None: ... + def set_include_dirs(self, dirs: List[str]) -> None: ... + def add_library(self, libname: str) -> None: ... + def set_libraries(self, libnames: List[str]) -> None: ... + def add_library_dir(self, dir: str) -> None: ... + def set_library_dirs(self, dirs: List[str]) -> None: ... + def add_runtime_library_dir(self, dir: str) -> None: ... + def set_runtime_library_dirs(self, dirs: List[str]) -> None: ... + def define_macro(self, name: str, value: Optional[str] = ...) -> None: ... + def undefine_macro(self, name: str) -> None: ... + def add_link_object(self, object: str) -> None: ... + def set_link_objects(self, objects: List[str]) -> None: ... + def detect_language(self, sources: Union[str, List[str]]) -> Optional[str]: ... + def find_library_file(self, dirs: List[str], lib: str, + debug: bool = ...) -> Optional[str]: ... + def has_function(self, funcname: str, includes: Optional[List[str]] = ..., + include_dirs: Optional[List[str]] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ...) -> bool: ... + def library_dir_option(self, dir: str) -> str: ... + def library_option(self, lib: str) -> str: ... + def runtime_library_dir_option(self, dir: str) -> str: ... + def set_executables(self, **args: str) -> None: ... + def compile(self, sources: List[str], output_dir: Optional[str] = ..., + macros: Optional[_Macro] = ..., + include_dirs: Optional[List[str]] = ..., debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + depends: Optional[List[str]] = ...) -> List[str]: ... + def create_static_lib(self, objects: List[str], output_libname: str, + output_dir: Optional[str] = ..., debug: bool = ..., + target_lang: Optional[str] = ...) -> None: ... + def link(self, target_desc: str, objects: List[str], output_filename: str, + output_dir: Optional[str] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + runtime_library_dirs: Optional[List[str]] = ..., + export_symbols: Optional[List[str]] = ..., debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + build_temp: Optional[str] = ..., + target_lang: Optional[str] = ...) -> None: ... + def link_executable(self, objects: List[str], output_progname: str, + output_dir: Optional[str] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + runtime_library_dirs: Optional[List[str]] = ..., + debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + target_lang: Optional[str] = ...) -> None: ... + def link_shared_lib(self, objects: List[str], output_libname: str, + output_dir: Optional[str] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + runtime_library_dirs: Optional[List[str]] = ..., + export_symbols: Optional[List[str]] = ..., + debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + build_temp: Optional[str] = ..., + target_lang: Optional[str] = ...) -> None: ... + def link_shared_object(self, objects: List[str], output_filename: str, + output_dir: Optional[str] = ..., + libraries: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + runtime_library_dirs: Optional[List[str]] = ..., + export_symbols: Optional[List[str]] = ..., + debug: bool = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ..., + build_temp: Optional[str] = ..., + target_lang: Optional[str] = ...) -> None: ... + def preprocess(self, source: str, output_file: Optional[str] = ..., + macros: Optional[List[_Macro]] = ..., + include_dirs: Optional[List[str]] = ..., + extra_preargs: Optional[List[str]] = ..., + extra_postargs: Optional[List[str]] = ...) -> None: ... + def executable_filename(self, basename: str, strip_dir: int = ..., + output_dir: str = ...) -> str: ... + def library_filename(self, libname: str, lib_type: str = ..., + strip_dir: int = ..., + output_dir: str = ...) -> str: ... + def object_filenames(self, source_filenames: List[str], + strip_dir: int = ..., + output_dir: str = ...) -> List[str]: ... + def shared_object_filename(self, basename: str, strip_dir: int = ..., + output_dir: str = ...) -> str: ... + def execute(self, func: Callable[..., None], args: Tuple[Any, ...], + msg: Optional[str] = ..., level: int = ...) -> None: ... + def spawn(self, cmd: List[str]) -> None: ... + def mkpath(self, name: str, mode: int = ...) -> None: ... + def move_file(self, src: str, dst: str) -> str: ... + def announce(self, msg: str, level: int = ...) -> None: ... + def warn(self, msg: str) -> None: ... + def debug_print(self, msg: str) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/cmd.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/cmd.pyi new file mode 100644 index 000000000..07e4989e6 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/cmd.pyi @@ -0,0 +1,40 @@ +# Stubs for distutils.cmd + +from typing import Callable, List, Tuple, Union, Optional, Iterable, Any, Text +from abc import abstractmethod +from distutils.dist import Distribution + +class Command: + sub_commands = ... # type: List[Tuple[str, Union[Callable[[], bool], str, None]]] + def __init__(self, dist: Distribution) -> None: ... + @abstractmethod + def initialize_options(self) -> None: ... + @abstractmethod + def finalize_options(self) -> None: ... + @abstractmethod + def run(self) -> None: ... + + def announce(self, msg: Text, level: int = ...) -> None: ... + def debug_print(self, msg: Text) -> None: ... + + def ensure_string(self, option: str, default: Optional[str] = ...) -> None: ... + def ensure_string_list(self, option: Union[str, List[str]]) -> None: ... + def ensure_filename(self, option: str) -> None: ... + def ensure_dirname(self, option: str) -> None: ... + + def get_command_name(self) -> str: ... + def set_undefined_options(self, src_cmd: Text, *option_pairs: Tuple[str, str]) -> None: ... + def get_finalized_command(self, command: Text, create: int = ...) -> Command: ... + def reinitialize_command(self, command: Union[Command, Text], reinit_subcommands: int = ...) -> Command: ... + def run_command(self, command: Text) -> None: ... + def get_sub_commands(self) -> List[str]: ... + + def warn(self, msg: Text) -> None: ... + def execute(self, func: Callable[..., Any], args: Iterable[Any], msg: Optional[Text] = ..., level: int = ...) -> None: ... + def mkpath(self, name: str, mode: int = ...) -> None: ... + def copy_file(self, infile: str, outfile: str, preserve_mode: int = ..., preserve_times: int = ..., link: Optional[str] = ..., level: Any = ...) -> Tuple[str, bool]: ... # level is not used + def copy_tree(self, infile: str, outfile: str, preserve_mode: int = ..., preserve_times: int = ..., preserve_symlinks: int = ..., level: Any = ...) -> List[str]: ... # level is not used + def move_file(self, src: str, dest: str, level: Any = ...) -> str: ... # level is not used + def spawn(self, cmd: Iterable[str], search_path: int = ..., level: Any = ...) -> None: ... # level is not used + def make_archive(self, base_name: str, format: str, root_dir: Optional[str] = ..., base_dir: Optional[str] = ..., owner: Optional[str] = ..., group: Optional[str] = ...) -> str: ... + def make_file(self, infiles: Union[str, List[str], Tuple[str]], outfile: str, func: Callable[..., Any], args: List[Any], exec_msg: Optional[str] = ..., skip_msg: Optional[str] = ..., level: Any = ...) -> None: ... # level is not used diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/__init__.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/__init__.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/bdist.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/bdist.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/bdist_dumb.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/bdist_dumb.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/bdist_msi.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/bdist_msi.pyi new file mode 100644 index 000000000..a76179201 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/command/bdist_msi.pyi @@ -0,0 +1,6 @@ +from distutils.cmd import Command + +class bdist_msi(Command): + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/bdist_packager.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/bdist_packager.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/bdist_rpm.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/bdist_rpm.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/bdist_wininst.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/bdist_wininst.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/build.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/build.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/build_clib.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/build_clib.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/build_ext.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/build_ext.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/build_py.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/build_py.pyi new file mode 100644 index 000000000..34753e4a7 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/command/build_py.pyi @@ -0,0 +1,10 @@ +from distutils.cmd import Command +import sys + +if sys.version_info >= (3,): + class build_py(Command): + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + + class build_py_2to3(build_py): ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/build_scripts.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/build_scripts.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/check.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/check.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/clean.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/clean.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/config.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/config.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/install.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/install.pyi new file mode 100644 index 000000000..94a900824 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/command/install.pyi @@ -0,0 +1,14 @@ +from distutils.cmd import Command +from typing import Optional, Text + + +class install(Command): + user: bool + prefix: Optional[Text] + home: Optional[Text] + root: Optional[Text] + install_lib: Optional[Text] + + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/install_data.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/install_data.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/install_headers.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/install_headers.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/install_lib.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/install_lib.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/install_scripts.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/install_scripts.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/register.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/register.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/command/sdist.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/command/sdist.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/core.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/core.pyi new file mode 100644 index 000000000..125b79992 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/core.pyi @@ -0,0 +1,50 @@ +# Stubs for distutils.core + +from typing import Any, List, Mapping, Optional, Tuple, Type, Union +from distutils.cmd import Command as Command +from distutils.dist import Distribution as Distribution +from distutils.extension import Extension as Extension + +def setup(name: str = ..., + version: str = ..., + description: str = ..., + long_description: str = ..., + author: str = ..., + author_email: str = ..., + maintainer: str = ..., + maintainer_email: str = ..., + url: str = ..., + download_url: str = ..., + packages: List[str] = ..., + py_modules: List[str] = ..., + scripts: List[str] = ..., + ext_modules: List[Extension] = ..., + classifiers: List[str] = ..., + distclass: Type[Distribution] = ..., + script_name: str = ..., + script_args: List[str] = ..., + options: Mapping[str, Any] = ..., + license: str = ..., + keywords: Union[List[str], str] = ..., + platforms: Union[List[str], str] = ..., + cmdclass: Mapping[str, Type[Command]] = ..., + data_files: List[Tuple[str, List[str]]] = ..., + package_dir: Mapping[str, str] = ..., + obsoletes: List[str] = ..., + provides: List[str] = ..., + requires: List[str] = ..., + command_packages: List[str] = ..., + command_options: Mapping[str, Mapping[str, Tuple[Any, Any]]] = ..., + package_data: Mapping[str, List[str]] = ..., + include_package_data: bool = ..., + libraries: List[str] = ..., + headers: List[str] = ..., + ext_package: str = ..., + include_dirs: List[str] = ..., + password: str = ..., + fullname: str = ..., + **attrs: Any) -> None: ... + +def run_setup(script_name: str, + script_args: Optional[List[str]] = ..., + stop_after: str = ...) -> Distribution: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/cygwinccompiler.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/cygwinccompiler.pyi new file mode 100644 index 000000000..1bfab90ea --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/cygwinccompiler.pyi @@ -0,0 +1,7 @@ +# Stubs for distutils.cygwinccompiler + +from distutils.unixccompiler import UnixCCompiler + + +class CygwinCCompiler(UnixCCompiler): ... +class Mingw32CCompiler(CygwinCCompiler): ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/debug.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/debug.pyi new file mode 100644 index 000000000..c3a184999 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/debug.pyi @@ -0,0 +1,3 @@ +# Stubs for distutils.debug + +DEBUG = ... # type: bool diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/dep_util.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/dep_util.pyi new file mode 100644 index 000000000..7df584781 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/dep_util.pyi @@ -0,0 +1,8 @@ +# Stubs for distutils.dep_util + +from typing import List, Tuple + +def newer(source: str, target: str) -> bool: ... +def newer_pairwise(sources: List[str], + targets: List[str]) -> List[Tuple[str, str]]: ... +def newer_group(sources: List[str], target: str, missing: str = ...) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/dir_util.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/dir_util.pyi new file mode 100644 index 000000000..667ac2fe7 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/dir_util.pyi @@ -0,0 +1,15 @@ +# Stubs for distutils.dir_util + +from typing import List + + +def mkpath(name: str, mode: int = ..., verbose: int = ..., + dry_run: int = ...) -> List[str]: ... +def create_tree(base_dir: str, files: List[str], mode: int = ..., + verbose: int = ..., dry_run: int = ...) -> None: ... +def copy_tree(src: str, dst: str, preserve_mode: int = ..., + preserve_times: int = ..., preserve_symlinks: int = ..., + update: int = ..., verbose: int = ..., + dry_run: int = ...) -> List[str]: ... +def remove_tree(directory: str, verbose: int = ..., + dry_run: int = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/dist.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/dist.pyi new file mode 100644 index 000000000..65e766d18 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/dist.pyi @@ -0,0 +1,11 @@ +# Stubs for distutils.dist +from distutils.cmd import Command + +from typing import Any, Mapping, Optional, Dict, Tuple, Iterable, Text + + +class Distribution: + def __init__(self, attrs: Optional[Mapping[str, Any]] = ...) -> None: ... + def get_option_dict(self, command: str) -> Dict[str, Tuple[str, Text]]: ... + def parse_config_files(self, filenames: Optional[Iterable[Text]] = ...) -> None: ... + def get_command_obj(self, command: str, create: bool = ...) -> Optional[Command]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/errors.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/errors.pyi new file mode 100644 index 000000000..e483362bf --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/errors.pyi @@ -0,0 +1,19 @@ +class DistutilsError(Exception): ... +class DistutilsModuleError(DistutilsError): ... +class DistutilsClassError(DistutilsError): ... +class DistutilsGetoptError(DistutilsError): ... +class DistutilsArgError(DistutilsError): ... +class DistutilsFileError(DistutilsError): ... +class DistutilsOptionError(DistutilsError): ... +class DistutilsSetupError(DistutilsError): ... +class DistutilsPlatformError(DistutilsError): ... +class DistutilsExecError(DistutilsError): ... +class DistutilsInternalError(DistutilsError): ... +class DistutilsTemplateError(DistutilsError): ... +class DistutilsByteCompileError(DistutilsError): ... +class CCompilerError(Exception): ... +class PreprocessError(CCompilerError): ... +class CompileError(CCompilerError): ... +class LibError(CCompilerError): ... +class LinkError(CCompilerError): ... +class UnknownFileError(CCompilerError): ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/extension.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/extension.pyi new file mode 100644 index 000000000..5aa070e43 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/extension.pyi @@ -0,0 +1,39 @@ +# Stubs for distutils.extension + +from typing import List, Optional, Tuple +import sys + +class Extension: + if sys.version_info >= (3,): + def __init__(self, + name: str, + sources: List[str], + include_dirs: List[str] = ..., + define_macros: List[Tuple[str, Optional[str]]] = ..., + undef_macros: List[str] = ..., + library_dirs: List[str] = ..., + libraries: List[str] = ..., + runtime_library_dirs: List[str] = ..., + extra_objects: List[str] = ..., + extra_compile_args: List[str] = ..., + extra_link_args: List[str] = ..., + export_symbols: List[str] = ..., + depends: List[str] = ..., + language: str = ..., + optional: bool = ...) -> None: ... + else: + def __init__(self, + name: str, + sources: List[str], + include_dirs: List[str] = ..., + define_macros: List[Tuple[str, Optional[str]]] = ..., + undef_macros: List[str] = ..., + library_dirs: List[str] = ..., + libraries: List[str] = ..., + runtime_library_dirs: List[str] = ..., + extra_objects: List[str] = ..., + extra_compile_args: List[str] = ..., + extra_link_args: List[str] = ..., + export_symbols: List[str] = ..., + depends: List[str] = ..., + language: str = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/fancy_getopt.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/fancy_getopt.pyi new file mode 100644 index 000000000..aa7e964b2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/fancy_getopt.pyi @@ -0,0 +1,27 @@ +# Stubs for distutils.fancy_getopt + +from typing import ( + Any, List, Mapping, Optional, Tuple, Union, + TypeVar, overload, +) + +_Option = Tuple[str, str, str] +_GR = Tuple[List[str], OptionDummy] + +def fancy_getopt(options: List[_Option], + negative_opt: Mapping[_Option, _Option], + object: Any, + args: Optional[List[str]]) -> Union[List[str], _GR]: ... +def wrap_text(text: str, width: int) -> List[str]: ... + +class FancyGetopt: + def __init__(self, option_table: Optional[List[_Option]] = ...) -> None: ... + # TODO kinda wrong, `getopt(object=object())` is invalid + @overload + def getopt(self, args: Optional[List[str]] = ...) -> _GR: ... + @overload + def getopt(self, args: Optional[List[str]], object: Any) -> List[str]: ... + def get_option_order(self) -> List[Tuple[str, str]]: ... + def generate_help(self, header: Optional[str] = ...) -> List[str]: ... + +class OptionDummy: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/file_util.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/file_util.pyi new file mode 100644 index 000000000..6324d63d4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/file_util.pyi @@ -0,0 +1,12 @@ +# Stubs for distutils.file_util + +from typing import Optional, Sequence, Tuple + + +def copy_file(src: str, dst: str, preserve_mode: bool = ..., + preserve_times: bool = ..., update: bool = ..., + link: Optional[str] = ..., verbose: bool = ..., + dry_run: bool = ...) -> Tuple[str, str]: ... +def move_file(src: str, dst: str, verbose: bool = ..., + dry_run: bool = ...) -> str: ... +def write_file(filename: str, contents: Sequence[str]) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/filelist.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/filelist.pyi new file mode 100644 index 000000000..4ecaebaf7 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/filelist.pyi @@ -0,0 +1,3 @@ +# Stubs for distutils.filelist + +class FileList: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/log.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/log.pyi new file mode 100644 index 000000000..6c37cc503 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/log.pyi @@ -0,0 +1,28 @@ +from typing import Any, Callable, Iterable, Text + +DEBUG: int +INFO: int +WARN: int +ERROR: int +FATAL: int + +class Log: + def __init__(self, threshold: int = ...) -> None: ... + def log(self, level: int, msg: Text, *args: Any) -> None: ... + def debug(self, msg: Text, *args: Any) -> None: ... + def info(self, msg: Text, *args: Any) -> None: ... + def warn(self, msg: Text, *args: Any) -> None: ... + def error(self, msg: Text, *args: Any) -> None: ... + def fatal(self, msg: Text, *args: Any) -> None: ... + +_LogFunc = Callable[[Text, Iterable[Any]], None] + +log: Callable[[int, Text, Iterable[Any]], None] +debug: _LogFunc +info: _LogFunc +warn: _LogFunc +error: _LogFunc +fatal: _LogFunc + +def set_threshold(level: int) -> int: ... +def set_verbosity(v: int) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/msvccompiler.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/msvccompiler.pyi new file mode 100644 index 000000000..ffc9e4490 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/msvccompiler.pyi @@ -0,0 +1,6 @@ +# Stubs for distutils.msvccompiler + +from distutils.ccompiler import CCompiler + + +class MSVCCompiler(CCompiler): ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/spawn.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/spawn.pyi new file mode 100644 index 000000000..8df9ebab7 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/spawn.pyi @@ -0,0 +1,8 @@ +# Stubs for distutils.spawn + +from typing import List, Optional + +def spawn(cmd: List[str], search_path: bool = ..., + verbose: bool = ..., dry_run: bool = ...) -> None: ... +def find_executable(executable: str, + path: Optional[str] = ...) -> Optional[str]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/sysconfig.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/sysconfig.pyi new file mode 100644 index 000000000..f87cd462b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/sysconfig.pyi @@ -0,0 +1,19 @@ +# Stubs for distutils.sysconfig + +from typing import Mapping, Optional, Union +from distutils.ccompiler import CCompiler + +PREFIX = ... # type: str +EXEC_PREFIX = ... # type: str + +def get_config_var(name: str) -> Union[int, str, None]: ... +def get_config_vars(*args: str) -> Mapping[str, Union[int, str]]: ... +def get_config_h_filename() -> str: ... +def get_makefile_filename() -> str: ... +def get_python_inc(plat_specific: bool = ..., + prefix: Optional[str] = ...) -> str: ... +def get_python_lib(plat_specific: bool = ..., standard_lib: bool = ..., + prefix: Optional[str] = ...) -> str: ... + +def customize_compiler(compiler: CCompiler) -> None: ... +def set_python_build() -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/text_file.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/text_file.pyi new file mode 100644 index 000000000..8f90d41d1 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/text_file.pyi @@ -0,0 +1,18 @@ +# Stubs for distutils.text_file + +from typing import IO, List, Optional, Tuple, Union + +class TextFile: + def __init__(self, filename: Optional[str] = ..., + file: Optional[IO[str]] = ..., + *, strip_comments: bool = ..., + lstrip_ws: bool = ..., rstrip_ws: bool = ..., + skip_blanks: bool = ..., join_lines: bool = ..., + collapse_join: bool = ...) -> None: ... + def open(self, filename: str) -> None: ... + def close(self) -> None: ... + def warn(self, msg: str, + line: Union[List[int], Tuple[int, int], int] = ...) -> None: ... + def readline(self) -> Optional[str]: ... + def readlines(self) -> List[str]: ... + def unreadline(self, line: str) -> str: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/unixccompiler.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/unixccompiler.pyi new file mode 100644 index 000000000..7ab7298bf --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/unixccompiler.pyi @@ -0,0 +1,6 @@ +# Stubs for distutils.unixccompiler + +from distutils.ccompiler import CCompiler + + +class UnixCCompiler(CCompiler): ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/util.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/util.pyi new file mode 100644 index 000000000..942886d77 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/util.pyi @@ -0,0 +1,20 @@ +# Stubs for distutils.util + +from typing import Any, Callable, List, Mapping, Optional, Tuple + + +def get_platform() -> str: ... +def convert_path(pathname: str) -> str: ... +def change_root(new_root: str, pathname: str) -> str: ... +def check_environ() -> None: ... +def subst_vars(s: str, local_vars: Mapping[str, str]) -> None: ... +def split_quoted(s: str) -> List[str]: ... +def execute(func: Callable[..., None], args: Tuple[Any, ...], + msg: Optional[str] = ..., verbose: bool = ..., + dry_run: bool = ...) -> None: ... +def strtobool(val: str) -> bool: ... +def byte_compile(py_files: List[str], optimize: int = ..., force: bool = ..., + prefix: Optional[str] = ..., base_dir: Optional[str] = ..., + verbose: bool = ..., dry_run: bool = ..., + direct: Optional[bool] = ...) -> None: ... +def rfc822_escape(header: str) -> str: ... diff --git a/client/typeshed-fallback/stdlib/2and3/distutils/version.pyi b/client/typeshed-fallback/stdlib/2and3/distutils/version.pyi new file mode 100644 index 000000000..cb636b4d9 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/distutils/version.pyi @@ -0,0 +1,54 @@ +import sys +from abc import abstractmethod +from typing import Any, Optional, TypeVar, Union, Pattern, Text, Tuple + +_T = TypeVar('_T', bound='Version') + +class Version: + def __repr__(self) -> str: ... + + if sys.version_info >= (3,): + def __eq__(self, other: object) -> bool: ... + def __lt__(self: _T, other: Union[_T, str]) -> bool: ... + def __le__(self: _T, other: Union[_T, str]) -> bool: ... + def __gt__(self: _T, other: Union[_T, str]) -> bool: ... + def __ge__(self: _T, other: Union[_T, str]) -> bool: ... + + @abstractmethod + def __init__(self, vstring: Optional[Text] = ...) -> None: ... + @abstractmethod + def parse(self: _T, vstring: Text) -> _T: ... + @abstractmethod + def __str__(self) -> str: ... + if sys.version_info >= (3,): + @abstractmethod + def _cmp(self: _T, other: Union[_T, str]) -> bool: ... + else: + @abstractmethod + def __cmp__(self: _T, other: Union[_T, str]) -> bool: ... + +class StrictVersion(Version): + version_re: Pattern[str] + version: Tuple[int, int, int] + prerelease: Optional[Tuple[Text, int]] + + def __init__(self, vstring: Optional[Text] = ...) -> None: ... + def parse(self: _T, vstring: Text) -> _T: ... + def __str__(self) -> str: ... + if sys.version_info >= (3,): + def _cmp(self: _T, other: Union[_T, str]) -> bool: ... + else: + def __cmp__(self: _T, other: Union[_T, str]) -> bool: ... + +class LooseVersion(Version): + component_re: Pattern[str] + vstring: Text + version: Tuple[Union[Text, int], ...] + + def __init__(self, vstring: Optional[Text] = ...) -> None: ... + def parse(self: _T, vstring: Text) -> _T: ... + def __str__(self) -> str: ... + if sys.version_info >= (3,): + def _cmp(self: _T, other: Union[_T, str]) -> bool: ... + else: + def __cmp__(self: _T, other: Union[_T, str]) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/2and3/doctest.pyi b/client/typeshed-fallback/stdlib/2and3/doctest.pyi new file mode 100644 index 000000000..8151fb572 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/doctest.pyi @@ -0,0 +1,161 @@ +from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Type, Union + +import sys +import types +import unittest + +TestResults = NamedTuple('TestResults', [ + ('failed', int), + ('attempted', int), +]) + +OPTIONFLAGS_BY_NAME: Dict[str, int] +def register_optionflag(name: str) -> int: ... +DONT_ACCEPT_TRUE_FOR_1: int +DONT_ACCEPT_BLANKLINE: int +NORMALIZE_WHITESPACE: int +ELLIPSIS: int +SKIP: int +IGNORE_EXCEPTION_DETAIL: int + +COMPARISON_FLAGS: int + +REPORT_UDIFF: int +REPORT_CDIFF: int +REPORT_NDIFF: int +REPORT_ONLY_FIRST_FAILURE: int +if sys.version_info >= (3, 4): + FAIL_FAST: int + +REPORTING_FLAGS: int + +BLANKLINE_MARKER: str +ELLIPSIS_MARKER: str + +class Example: + source: str + want: str + exc_msg: Optional[str] + lineno: int + indent: int + options: Dict[int, bool] + def __init__(self, source: str, want: str, exc_msg: Optional[str] = ..., lineno: int = ..., indent: int = ..., + options: Optional[Dict[int, bool]] = ...) -> None: ... + def __hash__(self) -> int: ... + +class DocTest: + examples: List[Example] + globs: Dict[str, Any] + name: str + filename: Optional[str] + lineno: Optional[int] + docstring: Optional[str] + def __init__(self, examples: List[Example], globs: Dict[str, Any], name: str, filename: Optional[str], lineno: Optional[int], docstring: Optional[str]) -> None: ... + def __hash__(self) -> int: ... + def __lt__(self, other: DocTest) -> bool: ... + +class DocTestParser: + def parse(self, string: str, name: str = ...) -> List[Union[str, Example]]: ... + def get_doctest(self, string: str, globs: Dict[str, Any], name: str, filename: Optional[str], lineno: Optional[str]) -> DocTest: ... + def get_examples(self, strin: str, name: str = ...) -> List[Example]: ... + +class DocTestFinder: + def __init__(self, verbose: bool = ..., parser: DocTestParser = ..., + recurse: bool = ..., exclude_empty: bool = ...) -> None: ... + def find(self, obj: object, name: Optional[str] = ..., module: Union[None, bool, types.ModuleType] = ..., + globs: Optional[Dict[str, Any]] = ..., extraglobs: Optional[Dict[str, Any]] = ...) -> List[DocTest]: ... + +_Out = Callable[[str], Any] +_ExcInfo = Tuple[Type[BaseException], BaseException, types.TracebackType] + +class DocTestRunner: + DIVIDER: str + optionflags: int + original_optionflags: int + tries: int + failures: int + test: DocTest + + def __init__(self, checker: Optional[OutputChecker] = ..., verbose: Optional[bool] = ..., optionflags: int = ...) -> None: ... + def report_start(self, out: _Out, test: DocTest, example: Example) -> None: ... + def report_success(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ... + def report_failure(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ... + def report_unexpected_exception(self, out: _Out, test: DocTest, example: Example, exc_info: _ExcInfo) -> None: ... + def run(self, test: DocTest, compileflags: Optional[int] = ..., out: Optional[_Out] = ..., clear_globs: bool = ...) -> TestResults: ... + def summarize(self, verbose: Optional[bool] = ...) -> TestResults: ... + def merge(self, other: DocTestRunner) -> None: ... + +class OutputChecker: + def check_output(self, want: str, got: str, optionflags: int) -> bool: ... + def output_difference(self, example: Example, got: str, optionflags: int) -> str: ... + +class DocTestFailure(Exception): + test: DocTest + example: Example + got: str + + def __init__(self, test: DocTest, example: Example, got: str) -> None: ... + +class UnexpectedException(Exception): + test: DocTest + example: Example + exc_info: _ExcInfo + + def __init__(self, test: DocTest, example: Example, exc_info: _ExcInfo) -> None: ... + +class DebugRunner(DocTestRunner): ... + +master: Optional[DocTestRunner] + +def testmod(m: Optional[types.ModuleType] = ..., name: Optional[str] = ..., globs: Dict[str, Any] = ..., verbose: Optional[bool] = ..., + report: bool = ..., optionflags: int = ..., extraglobs: Dict[str, Any] = ..., + raise_on_error: bool = ..., exclude_empty: bool = ...) -> TestResults: ... +def testfile(filename: str, module_relative: bool = ..., name: Optional[str] = ..., package: Union[None, str, types.ModuleType] = ..., + globs: Optional[Dict[str, Any]] = ..., verbose: Optional[bool] = ..., report: bool = ..., optionflags: int = ..., + extraglobs: Optional[Dict[str, Any]] = ..., raise_on_error: bool = ..., parser: DocTestParser = ..., + encoding: Optional[str] = ...) -> TestResults: ... +def run_docstring_examples(f: object, globs: Dict[str, Any], verbose: bool = ..., name: str = ..., + compileflags: Optional[int] = ..., optionflags: int = ...) -> None: ... +def set_unittest_reportflags(flags: int) -> int: ... + +class DocTestCase(unittest.TestCase): + def __init__(self, test: DocTest, optionflags: int = ..., setUp: Optional[Callable[[DocTest], Any]] = ..., + tearDown: Optional[Callable[[DocTest], Any]] = ..., + checker: Optional[OutputChecker] = ...) -> None: ... + def setUp(self) -> None: ... + def tearDown(self) -> None: ... + def runTest(self) -> None: ... + def format_failure(self, err: str) -> str: ... + def debug(self) -> None: ... + def id(self) -> str: ... + def __hash__(self) -> int: ... + def shortDescription(self) -> str: ... + +class SkipDocTestCase(DocTestCase): + def __init__(self, module: types.ModuleType) -> None: ... + def setUp(self) -> None: ... + def test_skip(self) -> None: ... + def shortDescription(self) -> str: ... + +if sys.version_info >= (3, 4): + class _DocTestSuite(unittest.TestSuite): ... +else: + _DocTestSuite = unittest.TestSuite + +def DocTestSuite(module: Union[None, str, types.ModuleType] = ..., globs: Optional[Dict[str, Any]] = ..., + extraglobs: Optional[Dict[str, Any]] = ..., test_finder: Optional[DocTestFinder] = ..., + **options: Any) -> _DocTestSuite: ... + +class DocFileCase(DocTestCase): + def id(self) -> str: ... + def format_failure(self, err: str) -> str: ... + +def DocFileTest(path: str, module_relative: bool = ..., package: Union[None, str, types.ModuleType] = ..., + globs: Optional[Dict[str, Any]] = ..., parser: DocTestParser = ..., + encoding: Optional[str] = ..., **options: Any) -> DocFileCase: ... +def DocFileSuite(*paths: str, **kw: Any) -> _DocTestSuite: ... +def script_from_examples(s: str) -> str: ... +def testsource(module: Union[None, str, types.ModuleType], name: str) -> str: ... +def debug_src(src: str, pm: bool = ..., globs: Optional[Dict[str, Any]] = ...) -> None: ... +def debug_script(src: str, pm: bool = ..., globs: Optional[Dict[str, Any]] = ...) -> None: ... +def debug(module: Union[None, str, types.ModuleType], name: str, pm: bool = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/errno.pyi b/client/typeshed-fallback/stdlib/2and3/errno.pyi new file mode 100644 index 000000000..21a2f3437 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/errno.pyi @@ -0,0 +1,130 @@ +# Stubs for errno + +from typing import Mapping +import sys + +errorcode = ... # type: Mapping[int, str] + +EPERM = ... # type: int +ENOENT = ... # type: int +ESRCH = ... # type: int +EINTR = ... # type: int +EIO = ... # type: int +ENXIO = ... # type: int +E2BIG = ... # type: int +ENOEXEC = ... # type: int +EBADF = ... # type: int +ECHILD = ... # type: int +EAGAIN = ... # type: int +ENOMEM = ... # type: int +EACCES = ... # type: int +EFAULT = ... # type: int +ENOTBLK = ... # type: int +EBUSY = ... # type: int +EEXIST = ... # type: int +EXDEV = ... # type: int +ENODEV = ... # type: int +ENOTDIR = ... # type: int +EISDIR = ... # type: int +EINVAL = ... # type: int +ENFILE = ... # type: int +EMFILE = ... # type: int +ENOTTY = ... # type: int +ETXTBSY = ... # type: int +EFBIG = ... # type: int +ENOSPC = ... # type: int +ESPIPE = ... # type: int +EROFS = ... # type: int +EMLINK = ... # type: int +EPIPE = ... # type: int +EDOM = ... # type: int +ERANGE = ... # type: int +EDEADLCK = ... # type: int +ENAMETOOLONG = ... # type: int +ENOLCK = ... # type: int +ENOSYS = ... # type: int +ENOTEMPTY = ... # type: int +ELOOP = ... # type: int +EWOULDBLOCK = ... # type: int +ENOMSG = ... # type: int +EIDRM = ... # type: int +ECHRNG = ... # type: int +EL2NSYNC = ... # type: int +EL3HLT = ... # type: int +EL3RST = ... # type: int +ELNRNG = ... # type: int +EUNATCH = ... # type: int +ENOCSI = ... # type: int +EL2HLT = ... # type: int +EBADE = ... # type: int +EBADR = ... # type: int +EXFULL = ... # type: int +ENOANO = ... # type: int +EBADRQC = ... # type: int +EBADSLT = ... # type: int +EDEADLOCK = ... # type: int +EBFONT = ... # type: int +ENOSTR = ... # type: int +ENODATA = ... # type: int +ETIME = ... # type: int +ENOSR = ... # type: int +ENONET = ... # type: int +ENOPKG = ... # type: int +EREMOTE = ... # type: int +ENOLINK = ... # type: int +EADV = ... # type: int +ESRMNT = ... # type: int +ECOMM = ... # type: int +EPROTO = ... # type: int +EMULTIHOP = ... # type: int +EDOTDOT = ... # type: int +EBADMSG = ... # type: int +EOVERFLOW = ... # type: int +ENOTUNIQ = ... # type: int +EBADFD = ... # type: int +EREMCHG = ... # type: int +ELIBACC = ... # type: int +ELIBBAD = ... # type: int +ELIBSCN = ... # type: int +ELIBMAX = ... # type: int +ELIBEXEC = ... # type: int +EILSEQ = ... # type: int +ERESTART = ... # type: int +ESTRPIPE = ... # type: int +EUSERS = ... # type: int +ENOTSOCK = ... # type: int +EDESTADDRREQ = ... # type: int +EMSGSIZE = ... # type: int +EPROTOTYPE = ... # type: int +ENOPROTOOPT = ... # type: int +EPROTONOSUPPORT = ... # type: int +ESOCKTNOSUPPORT = ... # type: int +ENOTSUP = ... # type: int +EOPNOTSUPP = ... # type: int +EPFNOSUPPORT = ... # type: int +EAFNOSUPPORT = ... # type: int +EADDRINUSE = ... # type: int +EADDRNOTAVAIL = ... # type: int +ENETDOWN = ... # type: int +ENETUNREACH = ... # type: int +ENETRESET = ... # type: int +ECONNABORTED = ... # type: int +ECONNRESET = ... # type: int +ENOBUFS = ... # type: int +EISCONN = ... # type: int +ENOTCONN = ... # type: int +ESHUTDOWN = ... # type: int +ETOOMANYREFS = ... # type: int +ETIMEDOUT = ... # type: int +ECONNREFUSED = ... # type: int +EHOSTDOWN = ... # type: int +EHOSTUNREACH = ... # type: int +EALREADY = ... # type: int +EINPROGRESS = ... # type: int +ESTALE = ... # type: int +EUCLEAN = ... # type: int +ENOTNAM = ... # type: int +ENAVAIL = ... # type: int +EISNAM = ... # type: int +EREMOTEIO = ... # type: int +EDQUOT = ... # type: int diff --git a/client/typeshed-fallback/stdlib/2and3/filecmp.pyi b/client/typeshed-fallback/stdlib/2and3/filecmp.pyi new file mode 100644 index 000000000..cc0a621a0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/filecmp.pyi @@ -0,0 +1,48 @@ +# Stubs for filecmp (Python 2/3) +import sys +from typing import AnyStr, Callable, Dict, Generic, Iterable, List, Optional, Sequence, Tuple, Union, Text + +DEFAULT_IGNORES = ... # type: List[str] + +def cmp(f1: Union[bytes, Text], f2: Union[bytes, Text], shallow: Union[int, bool] = ...) -> bool: ... +def cmpfiles(a: AnyStr, b: AnyStr, common: Iterable[AnyStr], + shallow: Union[int, bool] = ...) -> Tuple[List[AnyStr], List[AnyStr], List[AnyStr]]: ... + +class dircmp(Generic[AnyStr]): + def __init__(self, a: AnyStr, b: AnyStr, + ignore: Optional[Sequence[AnyStr]] = ..., + hide: Optional[Sequence[AnyStr]] = ...) -> None: ... + + left = ... # type: AnyStr + right = ... # type: AnyStr + hide = ... # type: Sequence[AnyStr] + ignore = ... # type: Sequence[AnyStr] + + # These properties are created at runtime by __getattr__ + subdirs = ... # type: Dict[AnyStr, dircmp[AnyStr]] + same_files = ... # type: List[AnyStr] + diff_files = ... # type: List[AnyStr] + funny_files = ... # type: List[AnyStr] + common_dirs = ... # type: List[AnyStr] + common_files = ... # type: List[AnyStr] + common_funny = ... # type: List[AnyStr] + common = ... # type: List[AnyStr] + left_only = ... # type: List[AnyStr] + right_only = ... # type: List[AnyStr] + left_list = ... # type: List[AnyStr] + right_list = ... # type: List[AnyStr] + + def report(self) -> None: ... + def report_partial_closure(self) -> None: ... + def report_full_closure(self) -> None: ... + + methodmap = ... # type: Dict[str, Callable[[], None]] + def phase0(self) -> None: ... + def phase1(self) -> None: ... + def phase2(self) -> None: ... + def phase3(self) -> None: ... + def phase4(self) -> None: ... + def phase4_closure(self) -> None: ... + +if sys.version_info >= (3,): + def clear_cache() -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/fileinput.pyi b/client/typeshed-fallback/stdlib/2and3/fileinput.pyi new file mode 100644 index 000000000..0eb8ca9d8 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/fileinput.pyi @@ -0,0 +1,62 @@ +from typing import Iterable, Callable, IO, AnyStr, Generic, Any, Text, Union, Iterator, Optional + +import os +import sys + +if sys.version_info >= (3, 6): + _Path = Union[Text, bytes, os.PathLike[Any]] +else: + _Path = Union[Text, bytes] + + +def input( + files: Union[_Path, Iterable[_Path], None] = ..., + inplace: bool = ..., + backup: str = ..., + bufsize: int = ..., + mode: str = ..., + openhook: Callable[[_Path, str], IO[AnyStr]] = ...) -> FileInput[AnyStr]: ... + + +def close() -> None: ... +def nextfile() -> None: ... +def filename() -> str: ... +def lineno() -> int: ... +def filelineno() -> int: ... +def fileno() -> int: ... +def isfirstline() -> bool: ... +def isstdin() -> bool: ... + +class FileInput(Iterable[AnyStr], Generic[AnyStr]): + def __init__( + self, + files: Union[None, _Path, Iterable[_Path]] = ..., + inplace: bool = ..., + backup: str = ..., + bufsize: int = ..., + mode: str = ..., + openhook: Callable[[_Path, str], IO[AnyStr]] = ... + ) -> None: ... + + def __del__(self) -> None: ... + def close(self) -> None: ... + if sys.version_info >= (3, 2): + def __enter__(self) -> FileInput[AnyStr]: ... + def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... + def __iter__(self) -> Iterator[AnyStr]: ... + def __next__(self) -> AnyStr: ... + def __getitem__(self, i: int) -> AnyStr: ... + def nextfile(self) -> None: ... + def readline(self) -> AnyStr: ... + def filename(self) -> str: ... + def lineno(self) -> int: ... + def filelineno(self) -> int: ... + def fileno(self) -> int: ... + def isfirstline(self) -> bool: ... + def isstdin(self) -> bool: ... + +def hook_compressed(filename: _Path, mode: str) -> IO[Any]: ... +if sys.version_info >= (3, 6): + def hook_encoded(encoding: str, errors: Optional[str] = ...) -> Callable[[_Path, str], IO[Any]]: ... +else: + def hook_encoded(encoding: str) -> Callable[[_Path, str], IO[Any]]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/formatter.pyi b/client/typeshed-fallback/stdlib/2and3/formatter.pyi new file mode 100644 index 000000000..9ad2978b5 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/formatter.pyi @@ -0,0 +1,105 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/formatter.py +# and https://github.com/python/cpython/blob/master/Lib/formatter.py +from typing import Any, IO, List, Optional, Tuple + +AS_IS = None +_FontType = Tuple[str, bool, bool, bool] +_StylesType = Tuple[Any, ...] + +class NullFormatter: + writer = ... # type: Optional[NullWriter] + def __init__(self, writer: Optional[NullWriter] = ...) -> None: ... + def end_paragraph(self, blankline: int) -> None: ... + def add_line_break(self) -> None: ... + def add_hor_rule(self, *args, **kw) -> None: ... + def add_label_data(self, format, counter: int, blankline: Optional[int] = ...) -> None: ... + def add_flowing_data(self, data: str) -> None: ... + def add_literal_data(self, data: str) -> None: ... + def flush_softspace(self) -> None: ... + def push_alignment(self, align: Optional[str]) -> None: ... + def pop_alignment(self) -> None: ... + def push_font(self, x: _FontType) -> None: ... + def pop_font(self) -> None: ... + def push_margin(self, margin: int) -> None: ... + def pop_margin(self) -> None: ... + def set_spacing(self, spacing: Optional[str]) -> None: ... + def push_style(self, *styles: _StylesType) -> None: ... + def pop_style(self, n: int = ...) -> None: ... + def assert_line_data(self, flag: int = ...) -> None: ... + +class AbstractFormatter: + writer = ... # type: NullWriter + align = ... # type: Optional[str] + align_stack = ... # type: List[Optional[str]] + font_stack = ... # type: List[_FontType] + margin_stack = ... # type: List[int] + spacing = ... # type: Optional[str] + style_stack = ... # type: Any + nospace = ... # type: int + softspace = ... # type: int + para_end = ... # type: int + parskip = ... # type: int + hard_break = ... # type: int + have_label = ... # type: int + def __init__(self, writer: NullWriter) -> None: ... + def end_paragraph(self, blankline: int) -> None: ... + def add_line_break(self) -> None: ... + def add_hor_rule(self, *args, **kw) -> None: ... + def add_label_data(self, format, counter: int, blankline: Optional[int] = ...) -> None: ... + def format_counter(self, format, counter: int) -> str: ... + def format_letter(self, case: str, counter: int) -> str: ... + def format_roman(self, case: str, counter: int) -> str: ... + def add_flowing_data(self, data: str) -> None: ... + def add_literal_data(self, data: str) -> None: ... + def flush_softspace(self) -> None: ... + def push_alignment(self, align: Optional[str]) -> None: ... + def pop_alignment(self) -> None: ... + def push_font(self, font: _FontType) -> None: ... + def pop_font(self) -> None: ... + def push_margin(self, margin: int) -> None: ... + def pop_margin(self) -> None: ... + def set_spacing(self, spacing: Optional[str]) -> None: ... + def push_style(self, *styles: _StylesType) -> None: ... + def pop_style(self, n: int = ...) -> None: ... + def assert_line_data(self, flag: int = ...) -> None: ... + +class NullWriter: + def __init__(self) -> None: ... + def flush(self) -> None: ... + def new_alignment(self, align: Optional[str]) -> None: ... + def new_font(self, font: _FontType) -> None: ... + def new_margin(self, margin: int, level: int) -> None: ... + def new_spacing(self, spacing: Optional[str]) -> None: ... + def new_styles(self, styles) -> None: ... + def send_paragraph(self, blankline: int) -> None: ... + def send_line_break(self) -> None: ... + def send_hor_rule(self, *args, **kw) -> None: ... + def send_label_data(self, data: str) -> None: ... + def send_flowing_data(self, data: str) -> None: ... + def send_literal_data(self, data: str) -> None: ... + +class AbstractWriter(NullWriter): + def new_alignment(self, align: Optional[str]) -> None: ... + def new_font(self, font: _FontType) -> None: ... + def new_margin(self, margin: int, level: int) -> None: ... + def new_spacing(self, spacing: Optional[str]) -> None: ... + def new_styles(self, styles) -> None: ... + def send_paragraph(self, blankline: int) -> None: ... + def send_line_break(self) -> None: ... + def send_hor_rule(self, *args, **kw) -> None: ... + def send_label_data(self, data: str) -> None: ... + def send_flowing_data(self, data: str) -> None: ... + def send_literal_data(self, data: str) -> None: ... + +class DumbWriter(NullWriter): + file = ... # type: IO + maxcol = ... # type: int + def __init__(self, file: Optional[IO] = ..., maxcol: int = ...) -> None: ... + def reset(self) -> None: ... + def send_paragraph(self, blankline: int) -> None: ... + def send_line_break(self) -> None: ... + def send_hor_rule(self, *args, **kw) -> None: ... + def send_literal_data(self, data: str) -> None: ... + def send_flowing_data(self, data: str) -> None: ... + +def test(file: Optional[str] = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/fractions.pyi b/client/typeshed-fallback/stdlib/2and3/fractions.pyi new file mode 100644 index 000000000..8bebe5fc8 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/fractions.pyi @@ -0,0 +1,96 @@ +# Stubs for fractions +# See https://docs.python.org/3/library/fractions.html +# +# Note: these stubs are incomplete. The more complex type +# signatures are currently omitted. Also see numbers.pyi. + +from typing import Optional, TypeVar, Union, overload, Any +from numbers import Real, Integral, Rational +from decimal import Decimal +import sys + +_ComparableNum = Union[int, float, Decimal, Real] + + +@overload +def gcd(a: int, b: int) -> int: ... +@overload +def gcd(a: Integral, b: int) -> Integral: ... +@overload +def gcd(a: int, b: Integral) -> Integral: ... +@overload +def gcd(a: Integral, b: Integral) -> Integral: ... + + +class Fraction(Rational): + @overload + def __init__(self, + numerator: Union[int, Rational] = ..., + denominator: Optional[Union[int, Rational]] = ..., + *, + _normalize: bool = ...) -> None: ... + @overload + def __init__(self, value: float, *, _normalize: bool = ...) -> None: ... + @overload + def __init__(self, value: Decimal, *, _normalize: bool = ...) -> None: ... + @overload + def __init__(self, value: str, *, _normalize: bool = ...) -> None: ... + + @classmethod + def from_float(cls, f: float) -> Fraction: ... + @classmethod + def from_decimal(cls, dec: Decimal) -> Fraction: ... + def limit_denominator(self, max_denominator: int = ...) -> Fraction: ... + + @property + def numerator(self) -> int: ... + @property + def denominator(self) -> int: ... + + def __add__(self, other): ... + def __radd__(self, other): ... + def __sub__(self, other): ... + def __rsub__(self, other): ... + def __mul__(self, other): ... + def __rmul__(self, other): ... + def __truediv__(self, other): ... + def __rtruediv__(self, other): ... + if sys.version_info < (3, 0): + def __div__(self, other): ... + def __rdiv__(self, other): ... + def __floordiv__(self, other) -> int: ... + def __rfloordiv__(self, other) -> int: ... + def __mod__(self, other): ... + def __rmod__(self, other): ... + def __divmod__(self, other): ... + def __rdivmod__(self, other): ... + def __pow__(self, other): ... + def __rpow__(self, other): ... + + def __pos__(self) -> Fraction: ... + def __neg__(self) -> Fraction: ... + def __abs__(self) -> Fraction: ... + def __trunc__(self) -> int: ... + if sys.version_info >= (3, 0): + def __floor__(self) -> int: ... + def __ceil__(self) -> int: ... + def __round__(self, ndigits: Optional[Any] = ...): ... + + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: _ComparableNum) -> bool: ... + def __gt__(self, other: _ComparableNum) -> bool: ... + def __le__(self, other: _ComparableNum) -> bool: ... + def __ge__(self, other: _ComparableNum) -> bool: ... + if sys.version_info >= (3, 0): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + + # Not actually defined within fractions.py, but provides more useful + # overrides + @property + def real(self) -> Fraction: ... + @property + def imag(self) -> Fraction: ... + def conjugate(self) -> Fraction: ... diff --git a/client/typeshed-fallback/stdlib/2and3/ftplib.pyi b/client/typeshed-fallback/stdlib/2and3/ftplib.pyi new file mode 100644 index 000000000..010961313 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/ftplib.pyi @@ -0,0 +1,134 @@ +# Stubs for ftplib (Python 2.7/3) +import sys +from typing import Optional, BinaryIO, Tuple, TextIO, Iterable, Callable, List, Union, Iterator, Dict, Text, Type, TypeVar, Generic, Any +from types import TracebackType +from socket import socket +from ssl import SSLContext + +_T = TypeVar('_T') +_IntOrStr = Union[int, Text] + +MSG_OOB = ... # type: int +FTP_PORT = ... # type: int +MAXLINE = ... # type: int +CRLF = ... # type: str +if sys.version_info >= (3,): + B_CRLF = ... # type: bytes + +class Error(Exception): ... +class error_reply(Error): ... +class error_temp(Error): ... +class error_perm(Error): ... +class error_proto(Error): ... + +all_errors = Tuple[Exception, ...] + +class FTP: + debugging = ... # type: int + + # Note: This is technically the type that's passed in as the host argument. But to make it easier in Python 2 we + # accept Text but return str. + host = ... # type: str + + port = ... # type: int + maxline = ... # type: int + sock = ... # type: Optional[socket] + welcome = ... # type: Optional[str] + passiveserver = ... # type: int + timeout = ... # type: int + af = ... # type: int + lastresp = ... # type: str + + if sys.version_info >= (3,): + file = ... # type: Optional[TextIO] + encoding = ... # type: str + def __enter__(self: _T) -> _T: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType]) -> bool: ... + else: + file = ... # type: Optional[BinaryIO] + + if sys.version_info >= (3, 3): + source_address = ... # type: Optional[Tuple[str, int]] + def __init__(self, host: Text = ..., user: Text = ..., passwd: Text = ..., acct: Text = ..., + timeout: float = ..., source_address: Optional[Tuple[str, int]] = ...) -> None: ... + def connect(self, host: Text = ..., port: int = ..., timeout: float = ..., + source_address: Optional[Tuple[str, int]] = ...) -> str: ... + else: + def __init__(self, host: Text = ..., user: Text = ..., passwd: Text = ..., acct: Text = ..., + timeout: float = ...) -> None: ... + def connect(self, host: Text = ..., port: int = ..., timeout: float = ...) -> str: ... + + def getwelcome(self) -> str: ... + def set_debuglevel(self, level: int) -> None: ... + def debug(self, level: int) -> None: ... + def set_pasv(self, val: Union[bool, int]) -> None: ... + def sanitize(self, s: Text) -> str: ... + def putline(self, line: Text) -> None: ... + def putcmd(self, line: Text) -> None: ... + def getline(self) -> str: ... + def getmultiline(self) -> str: ... + def getresp(self) -> str: ... + def voidresp(self) -> str: ... + def abort(self) -> str: ... + def sendcmd(self, cmd: Text) -> str: ... + def voidcmd(self, cmd: Text) -> str: ... + def sendport(self, host: Text, port: int) -> str: ... + def sendeprt(self, host: Text, port: int) -> str: ... + def makeport(self) -> socket: ... + def makepasv(self) -> Tuple[str, int]: ... + def login(self, user: Text = ..., passwd: Text = ..., acct: Text = ...) -> str: ... + + # In practice, `rest` rest can actually be anything whose str() is an integer sequence, so to make it simple we allow integers. + def ntransfercmd(self, cmd: Text, rest: Optional[_IntOrStr] = ...) -> Tuple[socket, int]: ... + def transfercmd(self, cmd: Text, rest: Optional[_IntOrStr] = ...) -> socket: ... + def retrbinary(self, cmd: Text, callback: Callable[[bytes], Any], blocksize: int = ..., rest: Optional[_IntOrStr] = ...) -> str: ... + def storbinary(self, cmd: Text, fp: BinaryIO, blocksize: int = ..., callback: Optional[Callable[[bytes], Any]] = ..., rest: Optional[_IntOrStr] = ...) -> str: ... + + def retrlines(self, cmd: Text, callback: Optional[Callable[[str], Any]] = ...) -> str: ... + def storlines(self, cmd: Text, fp: BinaryIO, callback: Optional[Callable[[bytes], Any]] = ...) -> str: ... + + def acct(self, password: Text) -> str: ... + def nlst(self, *args: Text) -> List[str]: ... + + # Technically only the last arg can be a Callable but ... + def dir(self, *args: Union[str, Callable[[str], None]]) -> None: ... + + if sys.version_info >= (3, 3): + def mlsd(self, path: Text = ..., facts: Iterable[str] = ...) -> Iterator[Tuple[str, Dict[str, str]]]: ... + def rename(self, fromname: Text, toname: Text) -> str: ... + def delete(self, filename: Text) -> str: ... + def cwd(self, dirname: Text) -> str: ... + def size(self, filename: Text) -> str: ... + def mkd(self, dirname: Text) -> str: ... + def rmd(self, dirname: Text) -> str: ... + def pwd(self) -> str: ... + def quit(self) -> str: ... + def close(self) -> None: ... + +class FTP_TLS(FTP): + def __init__(self, host: Text = ..., user: Text = ..., passwd: Text = ..., acct: Text = ..., + keyfile: Optional[str] = ..., certfile: Optional[str] = ..., + context: Optional[SSLContext] = ..., timeout: float = ..., + source_address: Optional[Tuple[str, int]] = ...) -> None: ... + + ssl_version = ... # type: int + keyfile = ... # type: Optional[str] + certfile = ... # type: Optional[str] + context = ... # type: SSLContext + + def login(self, user: Text = ..., passwd: Text = ..., acct: Text = ..., secure: bool = ...) -> str: ... + def auth(self) -> str: ... + def prot_p(self) -> str: ... + def prot_c(self) -> str: ... + + if sys.version_info >= (3, 3): + def ccc(self) -> str: ... + +if sys.version_info < (3,): + class Netrc: + def __init__(self, filename: Optional[Text] = ...) -> None: ... + def get_hosts(self) -> List[str]: ... + def get_account(self, host: Text) -> Tuple[Optional[str], Optional[str], Optional[str]]: ... + def get_macros(self) -> List[str]: ... + def get_macro(self, macro: Text) -> Tuple[str, ...]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/genericpath.pyi b/client/typeshed-fallback/stdlib/2and3/genericpath.pyi new file mode 100644 index 000000000..e0b1c6de2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/genericpath.pyi @@ -0,0 +1,21 @@ +from typing import Sequence, AnyStr, Text +import sys + +if sys.version_info >= (3, 0): + def commonprefix(m: Sequence[str]) -> str: ... +else: + def commonprefix(m: Sequence[AnyStr]) -> AnyStr: ... + +def exists(path: Text) -> bool: ... +def isfile(path: Text) -> bool: ... +def isdir(s: Text) -> bool: ... +def getsize(filename: Text) -> int: ... +def getmtime(filename: Text) -> float: ... +def getatime(filename: Text) -> float: ... +def getctime(filename: Text) -> float: ... + + +if sys.version_info >= (3, 4): + def samestat(s1: str, s2: str) -> int: ... + def samefile(f1: str, f2: str) -> int: ... + def sameopenfile(fp1: str, fp2: str) -> int: ... diff --git a/client/typeshed-fallback/stdlib/2and3/grp.pyi b/client/typeshed-fallback/stdlib/2and3/grp.pyi new file mode 100644 index 000000000..605472721 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/grp.pyi @@ -0,0 +1,10 @@ +from typing import List, NamedTuple, Optional + +struct_group = NamedTuple("struct_group", [("gr_name", str), + ("gr_passwd", Optional[str]), + ("gr_gid", int), + ("gr_mem", List[str])]) + +def getgrall() -> List[struct_group]: ... +def getgrgid(gid: int) -> struct_group: ... +def getgrnam(name: str) -> struct_group: ... diff --git a/client/typeshed-fallback/stdlib/2and3/hmac.pyi b/client/typeshed-fallback/stdlib/2and3/hmac.pyi new file mode 100644 index 000000000..fb5029c59 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/hmac.pyi @@ -0,0 +1,38 @@ +# Stubs for hmac + +from typing import Any, Callable, Optional, Union, overload, AnyStr +from types import ModuleType +import sys + +_B = Union[bytes, bytearray] + +# TODO more precise type for object of hashlib +_Hash = Any + +digest_size: None + +if sys.version_info >= (3, 4): + def new(key: _B, msg: Optional[_B] = ..., + digestmod: Optional[Union[str, Callable[[], _Hash], ModuleType]] = ...) -> HMAC: ... +else: + def new(key: _B, msg: Optional[_B] = ..., + digestmod: Optional[Union[Callable[[], _Hash], ModuleType]] = ...) -> HMAC: ... + +class HMAC: + if sys.version_info >= (3,): + digest_size = ... # type: int + if sys.version_info >= (3, 4): + block_size = ... # type: int + name = ... # type: str + def update(self, msg: _B) -> None: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def copy(self) -> HMAC: ... + +@overload +def compare_digest(a: bytearray, b: bytearray) -> bool: ... +@overload +def compare_digest(a: AnyStr, b: AnyStr) -> bool: ... + +if sys.version_info >= (3, 7): + def digest(key: _B, msg: _B, digest: str) -> bytes: ... diff --git a/client/typeshed-fallback/stdlib/2and3/imaplib.pyi b/client/typeshed-fallback/stdlib/2and3/imaplib.pyi new file mode 100644 index 000000000..ab32e7bac --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/imaplib.pyi @@ -0,0 +1,133 @@ +# Stubs for imaplib (Python 2) + +import imaplib +import subprocess +import sys +import time +from socket import socket as _socket +from ssl import SSLSocket +from typing import Any, Callable, Dict, IO, List, Optional, Pattern, Text, Tuple, Type, Union + +CommandResults = Tuple[str, List[Any]] + + +class IMAP4: + error: Type[Exception] = ... + abort: Type[Exception] = ... + readonly: Type[Exception] = ... + mustquote: Pattern[Text] = ... + debug: int = ... + state: str = ... + literal: Optional[Text] = ... + tagged_commands: Dict[str, str] = ... + untagged_responses: Dict[str, str] = ... + continuation_response: str = ... + is_readonly: bool = ... + tagnum: int = ... + tagpre: str = ... + tagre: Pattern[Text] = ... + welcome: bytes = ... + capabilities: Tuple[str] = ... + PROTOCOL_VERSION: str = ... + def __init__(self, host: str, port: int) -> None: ... + def __getattr__(self, attr: str) -> Any: ... + host: str = ... + port: int = ... + sock: _socket = ... + file: Union[IO[Text], IO[bytes]] = ... + def open(self, host: str = ..., port: int = ...) -> None: ... + def read(self, size: int) -> bytes: ... + def readline(self) -> bytes: ... + def send(self, data: bytes) -> None: ... + def shutdown(self) -> None: ... + def socket(self) -> _socket: ... + def recent(self) -> CommandResults: ... + def response(self, code: str) -> CommandResults: ... + def append(self, mailbox: str, flags: str, date_time: str, message: str) -> str: ... + def authenticate(self, mechanism: str, authobject: Callable) -> Tuple[str, str]: ... + def capability(self) -> CommandResults: ... + def check(self) -> CommandResults: ... + def close(self) -> CommandResults: ... + def copy(self, message_set: str, new_mailbox: str) -> CommandResults: ... + def create(self, mailbox: str) -> CommandResults: ... + def delete(self, mailbox: str) -> CommandResults: ... + def deleteacl(self, mailbox: str, who: str) -> CommandResults: ... + def expunge(self) -> CommandResults: ... + def fetch(self, message_set: str, message_parts: str) -> CommandResults: ... + def getacl(self, mailbox: str) -> CommandResults: ... + def getannotation(self, mailbox: str, entry: str, attribute: str) -> CommandResults: ... + def getquota(self, root: str) -> CommandResults: ... + def getquotaroot(self, mailbox: str) -> CommandResults: ... + def list(self, directory: str = ..., pattern: str = ...) -> CommandResults: ... + def login(self, user: str, password: str) -> CommandResults: ... + def login_cram_md5(self, user: str, password: str) -> CommandResults: ... + def logout(self) -> CommandResults: ... + def lsub(self, directory: str = ..., pattern: str = ...) -> CommandResults: ... + def myrights(self, mailbox: str) -> CommandResults: ... + def namespace(self) -> CommandResults: ... + def noop(self) -> CommandResults: ... + def partial(self, message_num: str, message_part: str, start: str, length: str) -> CommandResults: ... + def proxyauth(self, user: str) -> CommandResults: ... + def rename(self, oldmailbox: str, newmailbox: str) -> CommandResults: ... + def search(self, charset: Optional[str], *criteria: str) -> CommandResults: ... + def select(self, mailbox: str = ..., readonly: bool = ...) -> CommandResults: ... + def setacl(self, mailbox: str, who: str, what: str) -> CommandResults: ... + def setannotation(self, *args: List[str]) -> CommandResults: ... + def setquota(self, root: str, limits: str) -> CommandResults: ... + def sort(self, sort_criteria: str, charset: str, *search_criteria: List[str]) -> CommandResults: ... + if sys.version_info >= (3,): + def starttls(self, ssl_context: Optional[Any] = ...) -> CommandResults: ... + def status(self, mailbox: str, names: str) -> CommandResults: ... + def store(self, message_set: str, command: str, flags: str) -> CommandResults: ... + def subscribe(self, mailbox: str) -> CommandResults: ... + def thread(self, threading_algorithm: str, charset: str, *search_criteria: List[str]) -> CommandResults: ... + def uid(self, command: str, *args: List[str]) -> CommandResults: ... + def unsubscribe(self, mailbox: str) -> CommandResults: ... + def xatom(self, name: str, *args: List[str]) -> CommandResults: ... + def print_log(self) -> None: ... + +class IMAP4_SSL(IMAP4): + keyfile: str = ... + certfile: str = ... + def __init__(self, host: str = ..., port: int = ..., keyfile: Optional[str] = ..., certfile: Optional[str] = ...) -> None: ... + host: str = ... + port: int = ... + sock: _socket = ... + sslobj: SSLSocket = ... + file: IO[Any] = ... + def open(self, host: str = ..., port: Optional[int] = ...) -> None: ... + def read(self, size: int) -> bytes: ... + def readline(self) -> bytes: ... + def send(self, data: bytes) -> None: ... + def shutdown(self) -> None: ... + def socket(self) -> _socket: ... + def ssl(self) -> SSLSocket: ... + + +class IMAP4_stream(IMAP4): + command: str = ... + def __init__(self, command: str) -> None: ... + host: str = ... + port: int = ... + sock: _socket = ... + file: IO[Any] = ... + process: subprocess.Popen = ... + writefile: IO[Any] = ... + readfile: IO[Any] = ... + def open(self, host: str = ..., port: Optional[int] = ...) -> None: ... + def read(self, size: int) -> bytes: ... + def readline(self) -> bytes: ... + def send(self, data: bytes) -> None: ... + def shutdown(self) -> None: ... + +class _Authenticator: + mech: Callable = ... + def __init__(self, mechinst: Callable) -> None: ... + def process(self, data: str) -> str: ... + def encode(self, inp: bytes) -> str: ... + def decode(self, inp: str) -> bytes: ... + +def Internaldate2tuple(resp: str) -> time.struct_time: ... +def Int2AP(num: int) -> str: ... +def ParseFlags(resp: str) -> Tuple[str]: ... +def Time2Internaldate(date_time: Union[float, time.struct_time, str]) -> str: ... diff --git a/client/typeshed-fallback/stdlib/2and3/imghdr.pyi b/client/typeshed-fallback/stdlib/2and3/imghdr.pyi new file mode 100644 index 000000000..b9d8d17e3 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/imghdr.pyi @@ -0,0 +1,16 @@ +from typing import overload, Union, Text, BinaryIO, Optional, Any, List, Callable +import sys +import os + + +if sys.version_info >= (3, 6): + _File = Union[Text, os.PathLike[Text], BinaryIO] +else: + _File = Union[Text, BinaryIO] + + +@overload +def what(file: _File) -> Optional[str]: ... +@overload +def what(file: Any, h: bytes) -> Optional[str]: ... +tests: List[Callable[[bytes, BinaryIO], Optional[str]]] diff --git a/client/typeshed-fallback/stdlib/2and3/keyword.pyi b/client/typeshed-fallback/stdlib/2and3/keyword.pyi new file mode 100644 index 000000000..6e0fb5f14 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/keyword.pyi @@ -0,0 +1,6 @@ +# Stubs for keyword + +from typing import Sequence, Text, Union + +def iskeyword(s: Union[Text, bytes]) -> bool: ... +kwlist = ... # type: Sequence[str] diff --git a/client/typeshed-fallback/stdlib/2and3/lib2to3/__init__.pyi b/client/typeshed-fallback/stdlib/2and3/lib2to3/__init__.pyi new file mode 100644 index 000000000..145e31b1d --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/lib2to3/__init__.pyi @@ -0,0 +1 @@ +# Stubs for lib2to3 (Python 3.6) diff --git a/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/__init__.pyi b/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/__init__.pyi new file mode 100644 index 000000000..1adc82a6e --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/__init__.pyi @@ -0,0 +1,10 @@ +# Stubs for lib2to3.pgen2 (Python 3.6) + +import os +import sys +from typing import Text, Union + +if sys.version_info >= (3, 6): + _Path = Union[Text, os.PathLike] +else: + _Path = Text diff --git a/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/driver.pyi b/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/driver.pyi new file mode 100644 index 000000000..56785f087 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/driver.pyi @@ -0,0 +1,24 @@ +# Stubs for lib2to3.pgen2.driver (Python 3.6) + +import os +import sys +from typing import Any, Callable, IO, Iterable, List, Optional, Text, Tuple, Union + +from logging import Logger +from lib2to3.pytree import _Convert, _NL +from lib2to3.pgen2 import _Path +from lib2to3.pgen2.grammar import Grammar + + +class Driver: + grammar: Grammar + logger: Logger + convert: _Convert + def __init__(self, grammar: Grammar, convert: Optional[_Convert] = ..., logger: Optional[Logger] = ...) -> None: ... + def parse_tokens(self, tokens: Iterable[Any], debug: bool = ...) -> _NL: ... + def parse_stream_raw(self, stream: IO[Text], debug: bool = ...) -> _NL: ... + def parse_stream(self, stream: IO[Text], debug: bool = ...) -> _NL: ... + def parse_file(self, filename: _Path, encoding: Optional[Text] = ..., debug: bool = ...) -> _NL: ... + def parse_string(self, text: Text, debug: bool = ...) -> _NL: ... + +def load_grammar(gt: Text = ..., gp: Optional[Text] = ..., save: bool = ..., force: bool = ..., logger: Optional[Logger] = ...) -> Grammar: ... diff --git a/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/grammar.pyi b/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/grammar.pyi new file mode 100644 index 000000000..122d771db --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/grammar.pyi @@ -0,0 +1,29 @@ +# Stubs for lib2to3.pgen2.grammar (Python 3.6) + +from lib2to3.pgen2 import _Path + +from typing import Any, Dict, List, Optional, Text, Tuple, TypeVar + +_P = TypeVar('_P') +_Label = Tuple[int, Optional[Text]] +_DFA = List[List[Tuple[int, int]]] +_DFAS = Tuple[_DFA, Dict[int, int]] + +class Grammar: + symbol2number: Dict[Text, int] + number2symbol: Dict[int, Text] + states: List[_DFA] + dfas: Dict[int, _DFAS] + labels: List[_Label] + keywords: Dict[Text, int] + tokens: Dict[int, int] + symbol2label: Dict[Text, int] + start: int + def __init__(self) -> None: ... + def dump(self, filename: _Path) -> None: ... + def load(self, filename: _Path) -> None: ... + def copy(self: _P) -> _P: ... + def report(self) -> None: ... + +opmap_raw: Text +opmap: Dict[Text, Text] diff --git a/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/literals.pyi b/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/literals.pyi new file mode 100644 index 000000000..8719500da --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/literals.pyi @@ -0,0 +1,9 @@ +# Stubs for lib2to3.pgen2.literals (Python 3.6) + +from typing import Dict, Match, Text + +simple_escapes: Dict[Text, Text] + +def escape(m: Match) -> Text: ... +def evalString(s: Text) -> Text: ... +def test() -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/parse.pyi b/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/parse.pyi new file mode 100644 index 000000000..101d4760a --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/parse.pyi @@ -0,0 +1,29 @@ +# Stubs for lib2to3.pgen2.parse (Python 3.6) + +from typing import Any, Dict, List, Optional, Sequence, Set, Text, Tuple + +from lib2to3.pgen2.grammar import Grammar, _DFAS +from lib2to3.pytree import _NL, _Convert, _RawNode + +_Context = Sequence[Any] + +class ParseError(Exception): + msg: Text + type: int + value: Optional[Text] + context: _Context + def __init__(self, msg: Text, type: int, value: Optional[Text], context: _Context) -> None: ... + +class Parser: + grammar: Grammar + convert: _Convert + stack: List[Tuple[_DFAS, int, _RawNode]] + rootnode: Optional[_NL] + used_names: Set[Text] + def __init__(self, grammar: Grammar, convert: Optional[_Convert] = ...) -> None: ... + def setup(self, start: Optional[int] = ...) -> None: ... + def addtoken(self, type: int, value: Optional[Text], context: _Context) -> bool: ... + def classify(self, type: int, value: Optional[Text], context: _Context) -> int: ... + def shift(self, type: int, value: Optional[Text], newstate: int, context: _Context) -> None: ... + def push(self, type: int, newdfa: _DFAS, newstate: int, context: _Context) -> None: ... + def pop(self) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/pgen.pyi b/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/pgen.pyi new file mode 100644 index 000000000..42d503b4d --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/pgen.pyi @@ -0,0 +1,50 @@ +# Stubs for lib2to3.pgen2.pgen (Python 3.6) + +from typing import ( + Any, Dict, IO, Iterable, Iterator, List, NoReturn, Optional, Text, Tuple +) + +from lib2to3.pgen2 import _Path, grammar +from lib2to3.pgen2.tokenize import _TokenInfo + +class PgenGrammar(grammar.Grammar): ... + +class ParserGenerator: + filename: _Path + stream: IO[Text] + generator: Iterator[_TokenInfo] + first: Dict[Text, Dict[Text, int]] + def __init__(self, filename: _Path, stream: Optional[IO[Text]] = ...) -> None: ... + def make_grammar(self) -> PgenGrammar: ... + def make_first(self, c: PgenGrammar, name: Text) -> Dict[int, int]: ... + def make_label(self, c: PgenGrammar, label: Text) -> int: ... + def addfirstsets(self) -> None: ... + def calcfirst(self, name: Text) -> None: ... + def parse(self) -> Tuple[Dict[Text, List[DFAState]], Text]: ... + def make_dfa(self, start: NFAState, finish: NFAState) -> List[DFAState]: ... + def dump_nfa(self, name: Text, start: NFAState, finish: NFAState) -> List[DFAState]: ... + def dump_dfa(self, name: Text, dfa: Iterable[DFAState]) -> None: ... + def simplify_dfa(self, dfa: List[DFAState]) -> None: ... + def parse_rhs(self) -> Tuple[NFAState, NFAState]: ... + def parse_alt(self) -> Tuple[NFAState, NFAState]: ... + def parse_item(self) -> Tuple[NFAState, NFAState]: ... + def parse_atom(self) -> Tuple[NFAState, NFAState]: ... + def expect(self, type: int, value: Optional[Any] = ...) -> Text: ... + def gettoken(self) -> None: ... + def raise_error(self, msg: str, *args: Any) -> NoReturn: ... + +class NFAState: + arcs: List[Tuple[Optional[Text], NFAState]] + def __init__(self) -> None: ... + def addarc(self, next: NFAState, label: Optional[Text] = ...) -> None: ... + +class DFAState: + nfaset: Dict[NFAState, Any] + isfinal: bool + arcs: Dict[Text, DFAState] + def __init__(self, nfaset: Dict[NFAState, Any], final: NFAState) -> None: ... + def addarc(self, next: DFAState, label: Text) -> None: ... + def unifystate(self, old: DFAState, new: DFAState) -> None: ... + def __eq__(self, other: Any) -> bool: ... + +def generate_grammar(filename: _Path = ...) -> PgenGrammar: ... diff --git a/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/token.pyi b/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/token.pyi new file mode 100644 index 000000000..c256af8f2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/token.pyi @@ -0,0 +1,73 @@ +# Stubs for lib2to3.pgen2.token (Python 3.6) + +import sys +from typing import Dict, Text + +ENDMARKER: int +NAME: int +NUMBER: int +STRING: int +NEWLINE: int +INDENT: int +DEDENT: int +LPAR: int +RPAR: int +LSQB: int +RSQB: int +COLON: int +COMMA: int +SEMI: int +PLUS: int +MINUS: int +STAR: int +SLASH: int +VBAR: int +AMPER: int +LESS: int +GREATER: int +EQUAL: int +DOT: int +PERCENT: int +BACKQUOTE: int +LBRACE: int +RBRACE: int +EQEQUAL: int +NOTEQUAL: int +LESSEQUAL: int +GREATEREQUAL: int +TILDE: int +CIRCUMFLEX: int +LEFTSHIFT: int +RIGHTSHIFT: int +DOUBLESTAR: int +PLUSEQUAL: int +MINEQUAL: int +STAREQUAL: int +SLASHEQUAL: int +PERCENTEQUAL: int +AMPEREQUAL: int +VBAREQUAL: int +CIRCUMFLEXEQUAL: int +LEFTSHIFTEQUAL: int +RIGHTSHIFTEQUAL: int +DOUBLESTAREQUAL: int +DOUBLESLASH: int +DOUBLESLASHEQUAL: int +OP: int +COMMENT: int +NL: int +if sys.version_info >= (3,): + RARROW: int +if sys.version_info >= (3, 5): + AT: int + ATEQUAL: int + AWAIT: int + ASYNC: int +ERRORTOKEN: int +N_TOKENS: int +NT_OFFSET: int +tok_name: Dict[int, Text] + +def ISTERMINAL(x: int) -> bool: ... +def ISNONTERMINAL(x: int) -> bool: ... +def ISEOF(x: int) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/tokenize.pyi b/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/tokenize.pyi new file mode 100644 index 000000000..c10305ffd --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/lib2to3/pgen2/tokenize.pyi @@ -0,0 +1,30 @@ +# Stubs for lib2to3.pgen2.tokenize (Python 3.6) +# NOTE: Only elements from __all__ are present. + +from typing import Callable, Iterable, Iterator, List, Text, Tuple +from lib2to3.pgen2.token import * # noqa + + +_Coord = Tuple[int, int] +_TokenEater = Callable[[int, Text, _Coord, _Coord, Text], None] +_TokenInfo = Tuple[int, Text, _Coord, _Coord, Text] + + +class TokenError(Exception): ... +class StopTokenizing(Exception): ... + +def tokenize(readline: Callable[[], Text], tokeneater: _TokenEater = ...) -> None: ... + +class Untokenizer: + tokens: List[Text] + prev_row: int + prev_col: int + def __init__(self) -> None: ... + def add_whitespace(self, start: _Coord) -> None: ... + def untokenize(self, iterable: Iterable[_TokenInfo]) -> Text: ... + def compat(self, token: Tuple[int, Text], iterable: Iterable[_TokenInfo]) -> None: ... + +def untokenize(iterable: Iterable[_TokenInfo]) -> Text: ... +def generate_tokens( + readline: Callable[[], Text] +) -> Iterator[_TokenInfo]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/lib2to3/pygram.pyi b/client/typeshed-fallback/stdlib/2and3/lib2to3/pygram.pyi new file mode 100644 index 000000000..aeb7b93bf --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/lib2to3/pygram.pyi @@ -0,0 +1,116 @@ +# Stubs for lib2to3.pygram (Python 3.6) + +from typing import Any +from lib2to3.pgen2.grammar import Grammar + +class Symbols: + def __init__(self, grammar: Grammar) -> None: ... + +class python_symbols(Symbols): + and_expr: int + and_test: int + annassign: int + arglist: int + argument: int + arith_expr: int + assert_stmt: int + async_funcdef: int + async_stmt: int + atom: int + augassign: int + break_stmt: int + classdef: int + comp_for: int + comp_if: int + comp_iter: int + comp_op: int + comparison: int + compound_stmt: int + continue_stmt: int + decorated: int + decorator: int + decorators: int + del_stmt: int + dictsetmaker: int + dotted_as_name: int + dotted_as_names: int + dotted_name: int + encoding_decl: int + eval_input: int + except_clause: int + exec_stmt: int + expr: int + expr_stmt: int + exprlist: int + factor: int + file_input: int + flow_stmt: int + for_stmt: int + funcdef: int + global_stmt: int + if_stmt: int + import_as_name: int + import_as_names: int + import_from: int + import_name: int + import_stmt: int + lambdef: int + listmaker: int + not_test: int + old_lambdef: int + old_test: int + or_test: int + parameters: int + pass_stmt: int + power: int + print_stmt: int + raise_stmt: int + return_stmt: int + shift_expr: int + simple_stmt: int + single_input: int + sliceop: int + small_stmt: int + star_expr: int + stmt: int + subscript: int + subscriptlist: int + suite: int + term: int + test: int + testlist: int + testlist1: int + testlist_gexp: int + testlist_safe: int + testlist_star_expr: int + tfpdef: int + tfplist: int + tname: int + trailer: int + try_stmt: int + typedargslist: int + varargslist: int + vfpdef: int + vfplist: int + vname: int + while_stmt: int + with_item: int + with_stmt: int + with_var: int + xor_expr: int + yield_arg: int + yield_expr: int + yield_stmt: int + +class pattern_symbols(Symbols): + Alternative: int + Alternatives: int + Details: int + Matcher: int + NegatedUnit: int + Repeater: int + Unit: int + +python_grammar: Grammar +python_grammar_no_print_statement: Grammar +pattern_grammar: Grammar diff --git a/client/typeshed-fallback/stdlib/2and3/lib2to3/pytree.pyi b/client/typeshed-fallback/stdlib/2and3/lib2to3/pytree.pyi new file mode 100644 index 000000000..06a7c1229 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/lib2to3/pytree.pyi @@ -0,0 +1,86 @@ +# Stubs for lib2to3.pytree (Python 3.6) + +import sys +from typing import Any, Callable, Dict, Iterator, List, Optional, Text, Tuple, TypeVar, Union + +from lib2to3.pgen2.grammar import Grammar + +_P = TypeVar('_P') +_NL = Union[Node, Leaf] +_Context = Tuple[Text, int, int] +_Results = Dict[Text, _NL] +_RawNode = Tuple[int, Text, _Context, Optional[List[_NL]]] +_Convert = Callable[[Grammar, _RawNode], Any] + +HUGE: int + +def type_repr(type_num: int) -> Text: ... + +class Base: + type: int + parent: Optional[Node] + prefix: Text + children: List[_NL] + was_changed: bool + was_checked: bool + def __eq__(self, other: Any) -> bool: ... + def _eq(self: _P, other: _P) -> bool: ... + def clone(self: _P) -> _P: ... + def post_order(self) -> Iterator[_NL]: ... + def pre_order(self) -> Iterator[_NL]: ... + def replace(self, new: Union[_NL, List[_NL]]) -> None: ... + def get_lineno(self) -> int: ... + def changed(self) -> None: ... + def remove(self) -> Optional[int]: ... + @property + def next_sibling(self) -> Optional[_NL]: ... + @property + def prev_sibling(self) -> Optional[_NL]: ... + def leaves(self) -> Iterator[Leaf]: ... + def depth(self) -> int: ... + def get_suffix(self) -> Text: ... + if sys.version_info < (3,): + def get_prefix(self) -> Text: ... + def set_prefix(self, prefix: Text) -> None: ... + +class Node(Base): + fixers_applied: List[Any] + def __init__(self, type: int, children: List[_NL], context: Optional[Any] = ..., prefix: Optional[Text] = ..., fixers_applied: Optional[List[Any]] = ...) -> None: ... + def set_child(self, i: int, child: _NL) -> None: ... + def insert_child(self, i: int, child: _NL) -> None: ... + def append_child(self, child: _NL) -> None: ... + +class Leaf(Base): + lineno: int + column: int + value: Text + fixers_applied: List[Any] + def __init__(self, type: int, value: Text, context: Optional[_Context] = ..., prefix: Optional[Text] = ..., fixers_applied: List[Any] = ...) -> None: ... + +def convert(gr: Grammar, raw_node: _RawNode) -> _NL: ... + +class BasePattern: + type: int + content: Optional[Text] + name: Optional[Text] + def optimize(self) -> BasePattern: ... # sic, subclasses are free to optimize themselves into different patterns + def match(self, node: _NL, results: Optional[_Results] = ...) -> bool: ... + def match_seq(self, nodes: List[_NL], results: Optional[_Results] = ...) -> bool: ... + def generate_matches(self, nodes: List[_NL]) -> Iterator[Tuple[int, _Results]]: ... + +class LeafPattern(BasePattern): + def __init__(self, type: Optional[int] = ..., content: Optional[Text] = ..., name: Optional[Text] = ...) -> None: ... + +class NodePattern(BasePattern): + wildcards: bool + def __init__(self, type: Optional[int] = ..., content: Optional[Text] = ..., name: Optional[Text] = ...) -> None: ... + +class WildcardPattern(BasePattern): + min: int + max: int + def __init__(self, content: Optional[Text] = ..., min: int = ..., max: int = ..., name: Optional[Text] = ...) -> None: ... + +class NegatedPattern(BasePattern): + def __init__(self, content: Optional[Text] = ...) -> None: ... + +def generate_matches(patterns: List[BasePattern], nodes: List[_NL]) -> Iterator[Tuple[int, _Results]]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/linecache.pyi b/client/typeshed-fallback/stdlib/2and3/linecache.pyi new file mode 100644 index 000000000..3f35f469e --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/linecache.pyi @@ -0,0 +1,12 @@ +import sys +from typing import Any, Dict, List, Optional, Text + +_ModuleGlobals = Dict[str, Any] + +def getline(filename: Text, lineno: int, module_globals: Optional[_ModuleGlobals] = ...) -> str: ... +def clearcache() -> None: ... +def getlines(filename: Text, module_globals: Optional[_ModuleGlobals] = ...) -> List[str]: ... +def checkcache(filename: Optional[Text] = ...) -> None: ... +def updatecache(filename: Text, module_globals: Optional[_ModuleGlobals] = ...) -> List[str]: ... +if sys.version_info >= (3, 5): + def lazycache(filename: Text, module_globals: _ModuleGlobals) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/2and3/locale.pyi b/client/typeshed-fallback/stdlib/2and3/locale.pyi new file mode 100644 index 000000000..431c87cd4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/locale.pyi @@ -0,0 +1,113 @@ +# Stubs for locale + +from decimal import Decimal +from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union +import sys + +# workaround for mypy#2010 +if sys.version_info < (3,): + from __builtin__ import str as _str +else: + from builtins import str as _str + +CODESET = ... # type: int +D_T_FMT = ... # type: int +D_FMT = ... # type: int +T_FMT = ... # type: int +T_FMT_AMPM = ... # type: int + +DAY_1 = ... # type: int +DAY_2 = ... # type: int +DAY_3 = ... # type: int +DAY_4 = ... # type: int +DAY_5 = ... # type: int +DAY_6 = ... # type: int +DAY_7 = ... # type: int +ABDAY_1 = ... # type: int +ABDAY_2 = ... # type: int +ABDAY_3 = ... # type: int +ABDAY_4 = ... # type: int +ABDAY_5 = ... # type: int +ABDAY_6 = ... # type: int +ABDAY_7 = ... # type: int + +MON_1 = ... # type: int +MON_2 = ... # type: int +MON_3 = ... # type: int +MON_4 = ... # type: int +MON_5 = ... # type: int +MON_6 = ... # type: int +MON_7 = ... # type: int +MON_8 = ... # type: int +MON_9 = ... # type: int +MON_10 = ... # type: int +MON_11 = ... # type: int +MON_12 = ... # type: int +ABMON_1 = ... # type: int +ABMON_2 = ... # type: int +ABMON_3 = ... # type: int +ABMON_4 = ... # type: int +ABMON_5 = ... # type: int +ABMON_6 = ... # type: int +ABMON_7 = ... # type: int +ABMON_8 = ... # type: int +ABMON_9 = ... # type: int +ABMON_10 = ... # type: int +ABMON_11 = ... # type: int +ABMON_12 = ... # type: int + +RADIXCHAR = ... # type: int +THOUSEP = ... # type: int +YESEXPR = ... # type: int +NOEXPR = ... # type: int +CRNCYSTR = ... # type: int + +ERA = ... # type: int +ERA_D_T_FMT = ... # type: int +ERA_D_FMT = ... # type: int +ERA_T_FMT = ... # type: int + +ALT_DIGITS = ... # type: int + +LC_CTYPE = ... # type: int +LC_COLLATE = ... # type: int +LC_TIME = ... # type: int +LC_MONETARY = ... # type: int +LC_MESSAGES = ... # type: int +LC_NUMERIC = ... # type: int +LC_ALL = ... # type: int + +CHAR_MAX = ... # type: int + +class Error(Exception): ... + +def setlocale(category: int, + locale: Union[_str, Iterable[_str], None] = ...) -> _str: ... +def localeconv() -> Mapping[_str, Union[int, _str, List[int]]]: ... +def nl_langinfo(option: int) -> _str: ... +def getdefaultlocale(envvars: Tuple[_str, ...] = ...) -> Tuple[Optional[_str], Optional[_str]]: ... +def getlocale(category: int = ...) -> Sequence[_str]: ... +def getpreferredencoding(do_setlocale: bool = ...) -> _str: ... +def normalize(localename: _str) -> _str: ... +def resetlocale(category: int = ...) -> None: ... +def strcoll(string1: _str, string2: _str) -> int: ... +def strxfrm(string: _str) -> _str: ... +def format(format: _str, val: Union[float, Decimal], grouping: bool = ..., + monetary: bool = ...) -> _str: ... +if sys.version_info >= (3, 7): + def format_string(format: _str, val: Sequence[Any], + grouping: bool = ..., monetary: bool = ...) -> _str: ... +else: + def format_string(format: _str, val: Sequence[Any], + grouping: bool = ...) -> _str: ... +def currency(val: Union[int, float, Decimal], symbol: bool = ..., grouping: bool = ..., + international: bool = ...) -> _str: ... +if sys.version_info >= (3, 5): + def delocalize(string: _str) -> None: ... +def atof(string: _str) -> float: ... +def atoi(string: _str) -> int: ... +def str(float: float) -> _str: ... + +locale_alias: Dict[_str, _str] # undocumented +locale_encoding_alias: Dict[_str, _str] # undocumented +windows_locale: Dict[int, _str] # undocumented diff --git a/client/typeshed-fallback/stdlib/2and3/logging/__init__.pyi b/client/typeshed-fallback/stdlib/2and3/logging/__init__.pyi new file mode 100644 index 000000000..744057261 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/logging/__init__.pyi @@ -0,0 +1,432 @@ +# Stubs for logging (Python 3.4) + +from typing import ( + Any, Callable, Dict, Iterable, List, Mapping, MutableMapping, Optional, IO, + Tuple, Text, Union, overload, +) +from string import Template +from time import struct_time +from types import TracebackType, FrameType +import sys +import threading + +_SysExcInfoType = Union[Tuple[type, BaseException, Optional[TracebackType]], + Tuple[None, None, None]] +if sys.version_info >= (3, 5): + _ExcInfoType = Union[None, bool, _SysExcInfoType, BaseException] +else: + _ExcInfoType = Union[None, bool, _SysExcInfoType] +_ArgsType = Union[Tuple[Any, ...], Mapping[str, Any]] +_FilterType = Union[Filter, Callable[[LogRecord], int]] +_Level = Union[int, Text] +if sys.version_info >= (3, 6): + from os import PathLike + _Path = Union[str, PathLike[str]] +else: + _Path = str + +raiseExceptions: bool + +def currentframe() -> FrameType: ... + +if sys.version_info >= (3,): + _levelToName = ... # type: Dict[int, str] + _nameToLevel = ... # type: Dict[str, int] +else: + _levelNames = ... # type: dict + +class Filterer(object): + filters = ... # type: List[Filter] + def __init__(self) -> None: ... + def addFilter(self, filter: Filter) -> None: ... + def removeFilter(self, filter: Filter) -> None: ... + def filter(self, record: LogRecord) -> bool: ... + +class Logger(Filterer): + name = ... # type: str + level = ... # type: int + parent = ... # type: Union[Logger, PlaceHolder] + propagate = ... # type: bool + handlers = ... # type: List[Handler] + disabled = ... # type: int + def __init__(self, name: str, level: _Level = ...) -> None: ... + def setLevel(self, level: Union[int, str]) -> None: ... + def isEnabledFor(self, lvl: int) -> bool: ... + def getEffectiveLevel(self) -> int: ... + def getChild(self, suffix: str) -> Logger: ... + if sys.version_info >= (3,): + def debug(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def info(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warning(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warn(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def error(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def critical(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + fatal = critical + def log(self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def exception(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + else: + def debug(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def info(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def warning(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + warn = warning + def error(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def critical(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + fatal = critical + def log(self, + level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def exception(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def addFilter(self, filt: _FilterType) -> None: ... + def removeFilter(self, filt: _FilterType) -> None: ... + def filter(self, record: LogRecord) -> bool: ... + def addHandler(self, hdlr: Handler) -> None: ... + def removeHandler(self, hdlr: Handler) -> None: ... + if sys.version_info >= (3,): + def findCaller(self, stack_info: bool = ...) -> Tuple[str, int, str, Optional[str]]: ... + else: + def findCaller(self) -> Tuple[str, int, str]: ... + def handle(self, record: LogRecord) -> None: ... + if sys.version_info >= (3,): + def makeRecord(self, name: str, lvl: int, fn: str, lno: int, msg: Any, + args: _ArgsType, + exc_info: Optional[_SysExcInfoType], + func: Optional[str] = ..., + extra: Optional[Mapping[str, Any]] = ..., + sinfo: Optional[str] = ...) -> LogRecord: ... + else: + def makeRecord(self, + name: str, lvl: int, fn: str, lno: int, msg: Any, + args: _ArgsType, + exc_info: Optional[_SysExcInfoType], + func: Optional[str] = ..., + extra: Optional[Mapping[str, Any]] = ...) -> LogRecord: ... + if sys.version_info >= (3,): + def hasHandlers(self) -> bool: ... + + +CRITICAL: int +FATAL: int +ERROR: int +WARNING: int +WARN: int +INFO: int +DEBUG: int +NOTSET: int + + +class Handler(Filterer): + level: int # undocumented + formatter: Optional[Formatter] # undocumented + lock: Optional[threading.Lock] # undocumented + name: Optional[str] # undocumented + def __init__(self, level: _Level = ...) -> None: ... + def createLock(self) -> None: ... + def acquire(self) -> None: ... + def release(self) -> None: ... + def setLevel(self, lvl: Union[int, str]) -> None: ... + def setFormatter(self, form: Formatter) -> None: ... + def addFilter(self, filt: _FilterType) -> None: ... + def removeFilter(self, filt: _FilterType) -> None: ... + def filter(self, record: LogRecord) -> bool: ... + def flush(self) -> None: ... + def close(self) -> None: ... + def handle(self, record: LogRecord) -> None: ... + def handleError(self, record: LogRecord) -> None: ... + def format(self, record: LogRecord) -> str: ... + def emit(self, record: LogRecord) -> None: ... + + +class Formatter: + converter = ... # type: Callable[[Optional[float]], struct_time] + _fmt = ... # type: Optional[str] + datefmt = ... # type: Optional[str] + if sys.version_info >= (3,): + _style = ... # type: PercentStyle + default_time_format = ... # type: str + default_msec_format = ... # type: str + + if sys.version_info >= (3,): + def __init__(self, fmt: Optional[str] = ..., + datefmt: Optional[str] = ..., + style: str = ...) -> None: ... + else: + def __init__(self, + fmt: Optional[str] = ..., + datefmt: Optional[str] = ...) -> None: ... + + def format(self, record: LogRecord) -> str: ... + def formatTime(self, record: LogRecord, datefmt: str = ...) -> str: ... + def formatException(self, exc_info: _SysExcInfoType) -> str: ... + if sys.version_info >= (3,): + def formatStack(self, stack_info: str) -> str: ... + + +class Filter: + def __init__(self, name: str = ...) -> None: ... + def filter(self, record: LogRecord) -> int: ... + + +class LogRecord: + args = ... # type: _ArgsType + asctime = ... # type: str + created = ... # type: int + exc_info = ... # type: Optional[_SysExcInfoType] + exc_text = ... # type: Optional[str] + filename = ... # type: str + funcName = ... # type: str + levelname = ... # type: str + levelno = ... # type: int + lineno = ... # type: int + module = ... # type: str + msecs = ... # type: int + message = ... # type: str + msg = ... # type: str + name = ... # type: str + pathname = ... # type: str + process = ... # type: int + processName = ... # type: str + relativeCreated = ... # type: int + if sys.version_info >= (3,): + stack_info = ... # type: Optional[str] + thread = ... # type: int + threadName = ... # type: str + if sys.version_info >= (3,): + def __init__(self, name: str, level: int, pathname: str, lineno: int, + msg: Any, args: _ArgsType, + exc_info: Optional[_SysExcInfoType], + func: Optional[str] = ..., + sinfo: Optional[str] = ...) -> None: ... + else: + def __init__(self, + name: str, level: int, pathname: str, lineno: int, + msg: Any, args: _ArgsType, + exc_info: Optional[_SysExcInfoType], + func: Optional[str] = ...) -> None: ... + def getMessage(self) -> str: ... + + +class LoggerAdapter: + logger: Logger + extra: Mapping[str, Any] + def __init__(self, logger: Logger, extra: Mapping[str, Any]) -> None: ... + def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> Tuple[Any, MutableMapping[str, Any]]: ... + if sys.version_info >= (3,): + def debug(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def info(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warning(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warn(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def error(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def exception(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def critical(self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def log(self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + else: + def debug(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def info(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def warning(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def error(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def exception(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def critical(self, + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def log(self, + level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def isEnabledFor(self, lvl: int) -> bool: ... + if sys.version_info >= (3,): + def getEffectiveLevel(self) -> int: ... + def setLevel(self, lvl: Union[int, str]) -> None: ... + def hasHandlers(self) -> bool: ... + + +if sys.version_info >= (3,): + def getLogger(name: Optional[str] = ...) -> Logger: ... +else: + @overload + def getLogger() -> Logger: ... + @overload + def getLogger(name: Union[Text, str]) -> Logger: ... +def getLoggerClass() -> type: ... +if sys.version_info >= (3,): + def getLogRecordFactory() -> Callable[..., LogRecord]: ... + +if sys.version_info >= (3,): + def debug(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def info(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warning(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def warn(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def error(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def critical(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def exception(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... + def log(level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + stack_info: bool = ..., extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any) -> None: ... +else: + def debug(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def info(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def warning(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + warn = warning + def error(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def critical(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def exception(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + def log(level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... +fatal = critical + +def disable(lvl: int) -> None: ... +def addLevelName(lvl: int, levelName: str) -> None: ... +def getLevelName(lvl: Union[int, str]) -> Any: ... + +def makeLogRecord(attrdict: Mapping[str, Any]) -> LogRecord: ... + +if sys.version_info >= (3,): + def basicConfig(*, filename: _Path = ..., filemode: str = ..., + format: str = ..., datefmt: str = ..., style: str = ..., + level: _Level = ..., stream: IO[str] = ..., + handlers: Iterable[Handler] = ...) -> None: ... +else: + @overload + def basicConfig() -> None: ... + @overload + def basicConfig(*, filename: str = ..., filemode: str = ..., + format: str = ..., datefmt: str = ..., + level: _Level = ..., stream: IO[str] = ...) -> None: ... +def shutdown() -> None: ... + +def setLoggerClass(klass: type) -> None: ... + +def captureWarnings(capture: bool) -> None: ... + +if sys.version_info >= (3,): + def setLogRecordFactory(factory: Callable[..., LogRecord]) -> None: ... + + +if sys.version_info >= (3,): + lastResort = ... # type: Optional[StreamHandler] + + +class StreamHandler(Handler): + stream = ... # type: IO[str] + if sys.version_info >= (3,): + terminator = ... # type: str + def __init__(self, stream: Optional[IO[str]] = ...) -> None: ... + + +class FileHandler(Handler): + baseFilename = ... # type: str + mode = ... # type: str + encoding = ... # type: Optional[str] + delay = ... # type: bool + def __init__(self, filename: _Path, mode: str = ..., + encoding: Optional[str] = ..., delay: bool = ...) -> None: ... + + +class NullHandler(Handler): ... + + +class PlaceHolder: + def __init__(self, alogger: Logger) -> None: ... + def append(self, alogger: Logger) -> None: ... + + +# Below aren't in module docs but still visible + +class RootLogger(Logger): ... + +root = ... # type: RootLogger + + +if sys.version_info >= (3,): + class PercentStyle(object): + default_format = ... # type: str + asctime_format = ... # type: str + asctime_search = ... # type: str + _fmt = ... # type: str + + def __init__(self, fmt: str) -> None: ... + def usesTime(self) -> bool: ... + def format(self, record: Any) -> str: ... + + class StrFormatStyle(PercentStyle): + ... + + class StringTemplateStyle(PercentStyle): + _tpl = ... # type: Template + + _STYLES = ... # type: Dict[str, Tuple[PercentStyle, str]] + + +BASIC_FORMAT = ... # type: str diff --git a/client/typeshed-fallback/stdlib/2and3/logging/config.pyi b/client/typeshed-fallback/stdlib/2and3/logging/config.pyi new file mode 100644 index 000000000..e3a3a915b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/logging/config.pyi @@ -0,0 +1,32 @@ +# Stubs for logging.config (Python 3.4) + +from typing import Any, Callable, Dict, Optional, IO, Union +import sys +if sys.version_info >= (3,): + from configparser import RawConfigParser +else: + from ConfigParser import RawConfigParser +if sys.version_info >= (3, 6): + from os import PathLike + +if sys.version_info >= (3, 7): + _Path = Union[str, bytes, PathLike[str]] +elif sys.version_info >= (3, 6): + _Path = Union[str, PathLike[str]] +else: + _Path = str + + +def dictConfig(config: Dict[str, Any]) -> None: ... +if sys.version_info >= (3, 4): + def fileConfig(fname: Union[_Path, IO[str], RawConfigParser], + defaults: Optional[Dict[str, str]] = ..., + disable_existing_loggers: bool = ...) -> None: ... + def listen(port: int = ..., + verify: Optional[Callable[[bytes], Optional[bytes]]] = ...) -> None: ... +else: + def fileConfig(fname: Union[str, IO[str]], + defaults: Optional[Dict[str, str]] = ..., + disable_existing_loggers: bool = ...) -> None: ... + def listen(port: int = ...) -> None: ... +def stopListening() -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/logging/handlers.pyi b/client/typeshed-fallback/stdlib/2and3/logging/handlers.pyi new file mode 100644 index 000000000..9a604ae1a --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/logging/handlers.pyi @@ -0,0 +1,213 @@ +# Stubs for logging.handlers (Python 2.4) + +import datetime +from logging import Handler, FileHandler, LogRecord +from socket import SocketType +import ssl +import sys +from typing import Any, Callable, Dict, List, Optional, Tuple, Union, overload +if sys.version_info >= (3,): + from queue import Queue +else: + from Queue import Queue + +# TODO update socket stubs to add SocketKind +_SocketKind = int +if sys.version_info >= (3, 6): + from os import PathLike + _Path = Union[str, PathLike[str]] +else: + _Path = str + +DEFAULT_TCP_LOGGING_PORT: int +DEFAULT_UDP_LOGGING_PORT: int +DEFAULT_HTTP_LOGGING_PORT: int +DEFAULT_SOAP_LOGGING_PORT: int +SYSLOG_UDP_PORT: int +SYSLOG_TCP_PORT: int + +class WatchedFileHandler(Handler): + @overload + def __init__(self, filename: _Path) -> None: ... + @overload + def __init__(self, filename: _Path, mode: str) -> None: ... + @overload + def __init__(self, filename: _Path, mode: str, + encoding: Optional[str]) -> None: ... + @overload + def __init__(self, filename: _Path, mode: str, encoding: Optional[str], + delay: bool) -> None: ... + + +if sys.version_info >= (3,): + class BaseRotatingHandler(FileHandler): + terminator = ... # type: str + namer = ... # type: Optional[Callable[[str], str]] + rotator = ... # type: Optional[Callable[[str, str], None]] + def __init__(self, filename: _Path, mode: str, + encoding: Optional[str] = ..., + delay: bool = ...) -> None: ... + def rotation_filename(self, default_name: str) -> None: ... + def rotate(self, source: str, dest: str) -> None: ... + + +if sys.version_info >= (3,): + class RotatingFileHandler(BaseRotatingHandler): + def __init__(self, filename: _Path, mode: str = ..., maxBytes: int = ..., + backupCount: int = ..., encoding: Optional[str] = ..., + delay: bool = ...) -> None: ... + def doRollover(self) -> None: ... +else: + class RotatingFileHandler(Handler): + def __init__(self, filename: str, mode: str = ..., maxBytes: int = ..., + backupCount: int = ..., encoding: Optional[str] = ..., + delay: bool = ...) -> None: ... + def doRollover(self) -> None: ... + + +if sys.version_info >= (3,): + class TimedRotatingFileHandler(BaseRotatingHandler): + if sys.version_info >= (3, 4): + def __init__(self, filename: _Path, when: str = ..., + interval: int = ..., + backupCount: int = ..., encoding: Optional[str] = ..., + delay: bool = ..., utc: bool = ..., + atTime: Optional[datetime.datetime] = ...) -> None: ... + else: + def __init__(self, + filename: str, when: str = ..., interval: int = ..., + backupCount: int = ..., encoding: Optional[str] = ..., + delay: bool = ..., utc: bool = ...) -> None: ... + def doRollover(self) -> None: ... +else: + class TimedRotatingFileHandler(Handler): + def __init__(self, + filename: str, when: str = ..., interval: int = ..., + backupCount: int = ..., encoding: Optional[str] = ..., + delay: bool = ..., utc: bool = ...) -> None: ... + def doRollover(self) -> None: ... + + +class SocketHandler(Handler): + retryStart = ... # type: float + retryFactor = ... # type: float + retryMax = ... # type: float + if sys.version_info >= (3, 4): + def __init__(self, host: str, port: Optional[int]) -> None: ... + else: + def __init__(self, host: str, port: int) -> None: ... + def makeSocket(self) -> SocketType: ... + def makePickle(self, record: LogRecord) -> bytes: ... + def send(self, packet: bytes) -> None: ... + def createSocket(self) -> None: ... + + +class DatagramHandler(SocketHandler): ... + + +class SysLogHandler(Handler): + LOG_ALERT = ... # type: int + LOG_CRIT = ... # type: int + LOG_DEBUG = ... # type: int + LOG_EMERG = ... # type: int + LOG_ERR = ... # type: int + LOG_INFO = ... # type: int + LOG_NOTICE = ... # type: int + LOG_WARNING = ... # type: int + LOG_AUTH = ... # type: int + LOG_AUTHPRIV = ... # type: int + LOG_CRON = ... # type: int + LOG_DAEMON = ... # type: int + LOG_FTP = ... # type: int + LOG_KERN = ... # type: int + LOG_LPR = ... # type: int + LOG_MAIL = ... # type: int + LOG_NEWS = ... # type: int + LOG_SYSLOG = ... # type: int + LOG_USER = ... # type: int + LOG_UUCP = ... # type: int + LOG_LOCAL0 = ... # type: int + LOG_LOCAL1 = ... # type: int + LOG_LOCAL2 = ... # type: int + LOG_LOCAL3 = ... # type: int + LOG_LOCAL4 = ... # type: int + LOG_LOCAL5 = ... # type: int + LOG_LOCAL6 = ... # type: int + LOG_LOCAL7 = ... # type: int + def __init__(self, address: Union[Tuple[str, int], str] = ..., + facility: int = ..., socktype: _SocketKind = ...) -> None: ... + def encodePriority(self, facility: Union[int, str], + priority: Union[int, str]) -> int: ... + def mapPriority(self, levelName: str) -> str: ... + + +class NTEventLogHandler(Handler): + def __init__(self, appname: str, dllname: str = ..., + logtype: str = ...) -> None: ... + def getEventCategory(self, record: LogRecord) -> int: ... + # TODO correct return value? + def getEventType(self, record: LogRecord) -> int: ... + def getMessageID(self, record: LogRecord) -> int: ... + + +class SMTPHandler(Handler): + # TODO `secure` can also be an empty tuple + if sys.version_info >= (3,): + def __init__(self, mailhost: Union[str, Tuple[str, int]], fromaddr: str, + toaddrs: List[str], subject: str, + credentials: Optional[Tuple[str, str]] = ..., + secure: Union[Tuple[str], Tuple[str, str], None] = ..., + timeout: float = ...) -> None: ... + else: + def __init__(self, + mailhost: Union[str, Tuple[str, int]], fromaddr: str, + toaddrs: List[str], subject: str, + credentials: Optional[Tuple[str, str]] = ..., + secure: Union[Tuple[str], Tuple[str, str], None] = ...) -> None: ... + def getSubject(self, record: LogRecord) -> str: ... + + +class BufferingHandler(Handler): + def __init__(self, capacity: int) -> None: ... + def shouldFlush(self, record: LogRecord) -> bool: ... + +class MemoryHandler(BufferingHandler): + def __init__(self, capacity: int, flushLevel: int = ..., + target: Optional[Handler] = ...) -> None: ... + def setTarget(self, target: Handler) -> None: ... + + +class HTTPHandler(Handler): + if sys.version_info >= (3, 5): + def __init__(self, host: str, url: str, method: str = ..., + secure: bool = ..., + credentials: Optional[Tuple[str, str]] = ..., + context: Optional[ssl.SSLContext] = ...) -> None: ... + elif sys.version_info >= (3,): + def __init__(self, + host: str, url: str, method: str = ..., secure: bool = ..., + credentials: Optional[Tuple[str, str]] = ...) -> None: ... + else: + def __init__(self, + host: str, url: str, method: str = ...) -> None: ... + def mapLogRecord(self, record: LogRecord) -> Dict[str, Any]: ... + + +if sys.version_info >= (3,): + class QueueHandler(Handler): + def __init__(self, queue: Queue) -> None: ... + def prepare(self, record: LogRecord) -> Any: ... + def enqueue(self, record: LogRecord) -> None: ... + + class QueueListener: + if sys.version_info >= (3, 5): + def __init__(self, queue: Queue, *handlers: Handler, + respect_handler_level: bool = ...) -> None: ... + else: + def __init__(self, + queue: Queue, *handlers: Handler) -> None: ... + def dequeue(self, block: bool) -> LogRecord: ... + def prepare(self, record: LogRecord) -> Any: ... + def start(self) -> None: ... + def stop(self) -> None: ... + def enqueue_sentinel(self) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/macpath.pyi b/client/typeshed-fallback/stdlib/2and3/macpath.pyi new file mode 100644 index 000000000..09663afa4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/macpath.pyi @@ -0,0 +1,177 @@ +# NB: path.pyi and stdlib/2 and stdlib/3 must remain consistent! +# Stubs for os.path +# Ron Murawski + +import os +import sys +from typing import ( + overload, List, Any, AnyStr, Sequence, Tuple, BinaryIO, TextIO, + TypeVar, Union, Text, Callable, Optional +) + +_T = TypeVar('_T') + +if sys.version_info >= (3, 6): + from builtins import _PathLike + _PathType = Union[bytes, Text, _PathLike] + _StrPath = Union[Text, _PathLike[Text]] + _BytesPath = Union[bytes, _PathLike[bytes]] +else: + _PathType = Union[bytes, Text] + _StrPath = Text + _BytesPath = bytes + +# ----- os.path variables ----- +supports_unicode_filenames: bool +# aliases (also in os) +curdir: str +pardir: str +sep: str +altsep: str +extsep: str +pathsep: str +defpath: str +devnull: str + +# ----- os.path function stubs ----- +if sys.version_info >= (3, 6): + # Overloads are necessary to work around python/mypy#3644. + @overload + def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def abspath(path: AnyStr) -> AnyStr: ... + @overload + def basename(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def basename(path: AnyStr) -> AnyStr: ... + @overload + def dirname(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def dirname(path: AnyStr) -> AnyStr: ... + @overload + def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expanduser(path: AnyStr) -> AnyStr: ... + @overload + def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expandvars(path: AnyStr) -> AnyStr: ... + @overload + def normcase(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normcase(path: AnyStr) -> AnyStr: ... + @overload + def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + @overload + def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(path: AnyStr) -> AnyStr: ... + else: + @overload + def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(filename: AnyStr) -> AnyStr: ... + +else: + def abspath(path: AnyStr) -> AnyStr: ... + def basename(path: AnyStr) -> AnyStr: ... + def dirname(path: AnyStr) -> AnyStr: ... + def expanduser(path: AnyStr) -> AnyStr: ... + def expandvars(path: AnyStr) -> AnyStr: ... + def normcase(path: AnyStr) -> AnyStr: ... + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + def realpath(path: AnyStr) -> AnyStr: ... + else: + def realpath(filename: AnyStr) -> AnyStr: ... + +if sys.version_info >= (3, 6): + # In reality it returns str for sequences of _StrPath and bytes for sequences + # of _BytesPath, but mypy does not accept such a signature. + def commonpath(paths: Sequence[_PathType]) -> Any: ... +elif sys.version_info >= (3, 5): + def commonpath(paths: Sequence[AnyStr]) -> AnyStr: ... + +# NOTE: Empty lists results in '' (str) regardless of contained type. +# Also, in Python 2 mixed sequences of Text and bytes results in either Text or bytes +# So, fall back to Any +def commonprefix(list: Sequence[_PathType]) -> Any: ... + +if sys.version_info >= (3, 3): + def exists(path: Union[_PathType, int]) -> bool: ... +else: + def exists(path: _PathType) -> bool: ... +def lexists(path: _PathType) -> bool: ... + +# These return float if os.stat_float_times() == True, +# but int is a subclass of float. +def getatime(path: _PathType) -> float: ... +def getmtime(path: _PathType) -> float: ... +def getctime(path: _PathType) -> float: ... + +def getsize(path: _PathType) -> int: ... +def isabs(path: _PathType) -> bool: ... +def isfile(path: _PathType) -> bool: ... +def isdir(path: _PathType) -> bool: ... +def islink(path: _PathType) -> bool: ... +def ismount(path: _PathType) -> bool: ... + +if sys.version_info < (3, 0): + # Make sure signatures are disjunct, and allow combinations of bytes and unicode. + # (Since Python 2 allows that, too) + # Note that e.g. os.path.join("a", "b", "c", "d", u"e") will still result in + # a type error. + @overload + def join(__p1: bytes, *p: bytes) -> bytes: ... + @overload + def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: bytes, __p2: bytes, __p3: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: bytes, __p2: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: Text, *p: _PathType) -> Text: ... +elif sys.version_info >= (3, 6): + # Mypy complains that the signatures overlap (same for relpath below), but things seem to behave correctly anyway. + @overload + def join(path: _StrPath, *paths: _StrPath) -> Text: ... + @overload + def join(path: _BytesPath, *paths: _BytesPath) -> bytes: ... +else: + def join(path: AnyStr, *paths: AnyStr) -> AnyStr: ... + +@overload +def relpath(path: _BytesPath, start: Optional[_BytesPath] = ...) -> bytes: ... +@overload +def relpath(path: _StrPath, start: Optional[_StrPath] = ...) -> Text: ... + +def samefile(path1: _PathType, path2: _PathType) -> bool: ... +def sameopenfile(fp1: int, fp2: int) -> bool: ... +def samestat(stat1: os.stat_result, stat2: os.stat_result) -> bool: ... + +if sys.version_info >= (3, 6): + @overload + def split(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def split(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +else: + def split(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitdrive(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitext(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + +if sys.platform == 'win32': + def splitunc(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + +if sys.version_info < (3,): + def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/marshal.pyi b/client/typeshed-fallback/stdlib/2and3/marshal.pyi new file mode 100644 index 000000000..eb2d57abd --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/marshal.pyi @@ -0,0 +1,8 @@ +from typing import Any, IO + +version = ... # type: int + +def dump(value: Any, file: IO[Any], version: int = ...) -> None: ... +def load(file: IO[Any]) -> Any: ... +def dumps(value: Any, version: int = ...) -> str: ... +def loads(string: str) -> Any: ... diff --git a/client/typeshed-fallback/stdlib/2and3/math.pyi b/client/typeshed-fallback/stdlib/2and3/math.pyi new file mode 100644 index 000000000..6703fc5b2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/math.pyi @@ -0,0 +1,71 @@ +# Stubs for math +# See: http://docs.python.org/2/library/math.html + +from typing import Tuple, Iterable, SupportsFloat, SupportsInt + +import sys + +e = ... # type: float +pi = ... # type: float +if sys.version_info >= (3, 5): + inf = ... # type: float + nan = ... # type: float +if sys.version_info >= (3, 6): + tau = ... # type: float + +def acos(x: SupportsFloat) -> float: ... +def acosh(x: SupportsFloat) -> float: ... +def asin(x: SupportsFloat) -> float: ... +def asinh(x: SupportsFloat) -> float: ... +def atan(x: SupportsFloat) -> float: ... +def atan2(y: SupportsFloat, x: SupportsFloat) -> float: ... +def atanh(x: SupportsFloat) -> float: ... +if sys.version_info >= (3,): + def ceil(x: SupportsFloat) -> int: ... +else: + def ceil(x: SupportsFloat) -> float: ... +def copysign(x: SupportsFloat, y: SupportsFloat) -> float: ... +def cos(x: SupportsFloat) -> float: ... +def cosh(x: SupportsFloat) -> float: ... +def degrees(x: SupportsFloat) -> float: ... +def erf(x: SupportsFloat) -> float: ... +def erfc(x: SupportsFloat) -> float: ... +def exp(x: SupportsFloat) -> float: ... +def expm1(x: SupportsFloat) -> float: ... +def fabs(x: SupportsFloat) -> float: ... +def factorial(x: SupportsInt) -> int: ... +if sys.version_info >= (3,): + def floor(x: SupportsFloat) -> int: ... +else: + def floor(x: SupportsFloat) -> float: ... +def fmod(x: SupportsFloat, y: SupportsFloat) -> float: ... +def frexp(x: SupportsFloat) -> Tuple[float, int]: ... +def fsum(iterable: Iterable) -> float: ... +def gamma(x: SupportsFloat) -> float: ... +if sys.version_info >= (3, 5): + def gcd(a: int, b: int) -> int: ... +def hypot(x: SupportsFloat, y: SupportsFloat) -> float: ... +if sys.version_info >= (3, 5): + def isclose(a: SupportsFloat, b: SupportsFloat, rel_tol: SupportsFloat = ..., abs_tol: SupportsFloat = ...) -> bool: ... +def isinf(x: SupportsFloat) -> bool: ... +if sys.version_info >= (3,): + def isfinite(x: SupportsFloat) -> bool: ... +def isnan(x: SupportsFloat) -> bool: ... +def ldexp(x: SupportsFloat, i: int) -> float: ... +def lgamma(x: SupportsFloat) -> float: ... +def log(x: SupportsFloat, base: SupportsFloat = ...) -> float: ... +def log10(x: SupportsFloat) -> float: ... +def log1p(x: SupportsFloat) -> float: ... +if sys.version_info >= (3, 3): + def log2(x: SupportsFloat) -> float: ... +def modf(x: SupportsFloat) -> Tuple[float, float]: ... +def pow(x: SupportsFloat, y: SupportsFloat) -> float: ... +def radians(x: SupportsFloat) -> float: ... +if sys.version_info >= (3, 7): + def remainder(x: SupportsFloat, y: SupportsFloat) -> float: ... +def sin(x: SupportsFloat) -> float: ... +def sinh(x: SupportsFloat) -> float: ... +def sqrt(x: SupportsFloat) -> float: ... +def tan(x: SupportsFloat) -> float: ... +def tanh(x: SupportsFloat) -> float: ... +def trunc(x: SupportsFloat) -> int: ... diff --git a/client/typeshed-fallback/stdlib/2and3/mimetypes.pyi b/client/typeshed-fallback/stdlib/2and3/mimetypes.pyi new file mode 100644 index 000000000..493e612d2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/mimetypes.pyi @@ -0,0 +1,38 @@ +# Stubs for mimetypes + +from typing import Dict, IO, List, Optional, Sequence, Text, Tuple +import sys + +def guess_type(url: Text, + strict: bool = ...) -> Tuple[Optional[str], Optional[str]]: ... +def guess_all_extensions(type: str, strict: bool = ...) -> List[str]: ... +def guess_extension(type: str, strict: bool = ...) -> Optional[str]: ... + +def init(files: Optional[Sequence[str]] = ...) -> None: ... +def read_mime_types(filename: str) -> Optional[Dict[str, str]]: ... +def add_type(type: str, ext: str, strict: bool = ...) -> None: ... + +inited = ... # type: bool +knownfiles = ... # type: List[str] +suffix_map = ... # type: Dict[str, str] +encodings_map = ... # type: Dict[str, str] +types_map = ... # type: Dict[str, str] +common_types = ... # type: Dict[str, str] + +class MimeTypes: + suffix_map = ... # type: Dict[str, str] + encodings_map = ... # type: Dict[str, str] + types_map = ... # type: Tuple[Dict[str, str], Dict[str, str]] + types_map_inv = ... # type: Tuple[Dict[str, str], Dict[str, str]] + def __init__(self, filenames: Tuple[str, ...] = ..., + strict: bool = ...) -> None: ... + def guess_extension(self, type: str, + strict: bool = ...) -> Optional[str]: ... + def guess_type(self, url: str, + strict: bool = ...) -> Tuple[Optional[str], Optional[str]]: ... + def guess_all_extensions(self, type: str, + strict: bool = ...) -> List[str]: ... + def read(self, filename: str, strict: bool = ...) -> None: ... + def readfp(self, fp: IO[str], strict: bool = ...) -> None: ... + if sys.platform == 'win32': + def read_windows_registry(self, strict: bool = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/mmap.pyi b/client/typeshed-fallback/stdlib/2and3/mmap.pyi new file mode 100644 index 000000000..b255ec198 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/mmap.pyi @@ -0,0 +1,73 @@ +import sys +from typing import (Optional, Sequence, Union, Generic, overload, + Iterable, Iterator, Sized, ContextManager, AnyStr) + +ACCESS_DEFAULT = ... # type: int +ACCESS_READ = ... # type: int +ACCESS_WRITE = ... # type: int +ACCESS_COPY = ... # type: int + +ALLOCATIONGRANULARITY = ... # type: int + +if sys.platform != 'win32': + MAP_ANON = ... # type: int + MAP_ANONYMOUS = ... # type: int + MAP_DENYWRITE = ... # type: int + MAP_EXECUTABLE = ... # type: int + MAP_PRIVATE = ... # type: int + MAP_SHARED = ... # type: int + PROT_EXEC = ... # type: int + PROT_READ = ... # type: int + PROT_WRITE = ... # type: int + + PAGESIZE = ... # type: int + +class _mmap(Generic[AnyStr]): + if sys.platform == 'win32': + def __init__(self, fileno: int, length: int, + tagname: Optional[str] = ..., access: int = ..., + offset: int = ...) -> None: ... + else: + def __init__(self, + fileno: int, length: int, flags: int = ..., + prot: int = ..., access: int = ..., + offset: int = ...) -> None: ... + def close(self) -> None: ... + def find(self, sub: AnyStr, + start: int = ..., end: int = ...) -> int: ... + def flush(self, offset: int = ..., size: int = ...) -> int: ... + def move(self, dest: int, src: int, count: int) -> None: ... + def read(self, n: int = ...) -> AnyStr: ... + def read_byte(self) -> AnyStr: ... + def readline(self) -> AnyStr: ... + def resize(self, newsize: int) -> None: ... + def seek(self, pos: int, whence: int = ...) -> None: ... + def size(self) -> int: ... + def tell(self) -> int: ... + def write(self, bytes: AnyStr) -> None: ... + def write_byte(self, byte: AnyStr) -> None: ... + def __len__(self) -> int: ... + +if sys.version_info >= (3,): + class mmap(_mmap, ContextManager[mmap], Iterable[bytes], Sized): + closed = ... # type: bool + def rfind(self, sub: bytes, start: int = ..., stop: int = ...) -> int: ... + @overload + def __getitem__(self, index: int) -> int: ... + @overload + def __getitem__(self, index: slice) -> bytes: ... + def __delitem__(self, index: Union[int, slice]) -> None: ... + @overload + def __setitem__(self, index: int, object: int) -> None: ... + @overload + def __setitem__(self, index: slice, object: bytes) -> None: ... + # Doesn't actually exist, but the object is actually iterable because it has __getitem__ and + # __len__, so we claim that there is also an __iter__ to help type checkers. + def __iter__(self) -> Iterator[bytes]: ... +else: + class mmap(_mmap, Sequence[bytes]): + def rfind(self, string: bytes, start: int = ..., stop: int = ...) -> int: ... + def __getitem__(self, index: Union[int, slice]) -> bytes: ... + def __getslice__(self, i: Optional[int], j: Optional[int]) -> bytes: ... + def __delitem__(self, index: Union[int, slice]) -> None: ... + def __setitem__(self, index: Union[int, slice], object: bytes) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/netrc.pyi b/client/typeshed-fallback/stdlib/2and3/netrc.pyi new file mode 100644 index 000000000..3ceae8899 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/netrc.pyi @@ -0,0 +1,19 @@ +from typing import AnyStr, Dict, List, Optional, Tuple, overload + + +class NetrcParseError(Exception): + filename: Optional[str] + lineno: Optional[int] + msg: str + + +# (login, account, password) tuple +_NetrcTuple = Tuple[str, Optional[str], Optional[str]] + + +class netrc: + hosts: Dict[str, _NetrcTuple] + macros: Dict[str, List[str]] + + def __init__(self, file: str = ...) -> None: ... + def authenticators(self, host: str) -> Optional[_NetrcTuple]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/nis.pyi b/client/typeshed-fallback/stdlib/2and3/nis.pyi new file mode 100644 index 000000000..87223caf2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/nis.pyi @@ -0,0 +1,10 @@ +import sys +from typing import Dict, List + +if sys.platform != 'win32': + def cat(map: str, domain: str = ...) -> Dict[str, str]: ... + def get_default_domain() -> str: ... + def maps(domain: str = ...) -> List[str]: ... + def match(key: str, map: str, domain: str = ...) -> str: ... + + class error(Exception): ... diff --git a/client/typeshed-fallback/stdlib/2and3/ntpath.pyi b/client/typeshed-fallback/stdlib/2and3/ntpath.pyi new file mode 100644 index 000000000..09663afa4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/ntpath.pyi @@ -0,0 +1,177 @@ +# NB: path.pyi and stdlib/2 and stdlib/3 must remain consistent! +# Stubs for os.path +# Ron Murawski + +import os +import sys +from typing import ( + overload, List, Any, AnyStr, Sequence, Tuple, BinaryIO, TextIO, + TypeVar, Union, Text, Callable, Optional +) + +_T = TypeVar('_T') + +if sys.version_info >= (3, 6): + from builtins import _PathLike + _PathType = Union[bytes, Text, _PathLike] + _StrPath = Union[Text, _PathLike[Text]] + _BytesPath = Union[bytes, _PathLike[bytes]] +else: + _PathType = Union[bytes, Text] + _StrPath = Text + _BytesPath = bytes + +# ----- os.path variables ----- +supports_unicode_filenames: bool +# aliases (also in os) +curdir: str +pardir: str +sep: str +altsep: str +extsep: str +pathsep: str +defpath: str +devnull: str + +# ----- os.path function stubs ----- +if sys.version_info >= (3, 6): + # Overloads are necessary to work around python/mypy#3644. + @overload + def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def abspath(path: AnyStr) -> AnyStr: ... + @overload + def basename(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def basename(path: AnyStr) -> AnyStr: ... + @overload + def dirname(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def dirname(path: AnyStr) -> AnyStr: ... + @overload + def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expanduser(path: AnyStr) -> AnyStr: ... + @overload + def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expandvars(path: AnyStr) -> AnyStr: ... + @overload + def normcase(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normcase(path: AnyStr) -> AnyStr: ... + @overload + def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + @overload + def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(path: AnyStr) -> AnyStr: ... + else: + @overload + def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(filename: AnyStr) -> AnyStr: ... + +else: + def abspath(path: AnyStr) -> AnyStr: ... + def basename(path: AnyStr) -> AnyStr: ... + def dirname(path: AnyStr) -> AnyStr: ... + def expanduser(path: AnyStr) -> AnyStr: ... + def expandvars(path: AnyStr) -> AnyStr: ... + def normcase(path: AnyStr) -> AnyStr: ... + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + def realpath(path: AnyStr) -> AnyStr: ... + else: + def realpath(filename: AnyStr) -> AnyStr: ... + +if sys.version_info >= (3, 6): + # In reality it returns str for sequences of _StrPath and bytes for sequences + # of _BytesPath, but mypy does not accept such a signature. + def commonpath(paths: Sequence[_PathType]) -> Any: ... +elif sys.version_info >= (3, 5): + def commonpath(paths: Sequence[AnyStr]) -> AnyStr: ... + +# NOTE: Empty lists results in '' (str) regardless of contained type. +# Also, in Python 2 mixed sequences of Text and bytes results in either Text or bytes +# So, fall back to Any +def commonprefix(list: Sequence[_PathType]) -> Any: ... + +if sys.version_info >= (3, 3): + def exists(path: Union[_PathType, int]) -> bool: ... +else: + def exists(path: _PathType) -> bool: ... +def lexists(path: _PathType) -> bool: ... + +# These return float if os.stat_float_times() == True, +# but int is a subclass of float. +def getatime(path: _PathType) -> float: ... +def getmtime(path: _PathType) -> float: ... +def getctime(path: _PathType) -> float: ... + +def getsize(path: _PathType) -> int: ... +def isabs(path: _PathType) -> bool: ... +def isfile(path: _PathType) -> bool: ... +def isdir(path: _PathType) -> bool: ... +def islink(path: _PathType) -> bool: ... +def ismount(path: _PathType) -> bool: ... + +if sys.version_info < (3, 0): + # Make sure signatures are disjunct, and allow combinations of bytes and unicode. + # (Since Python 2 allows that, too) + # Note that e.g. os.path.join("a", "b", "c", "d", u"e") will still result in + # a type error. + @overload + def join(__p1: bytes, *p: bytes) -> bytes: ... + @overload + def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: bytes, __p2: bytes, __p3: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: bytes, __p2: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: Text, *p: _PathType) -> Text: ... +elif sys.version_info >= (3, 6): + # Mypy complains that the signatures overlap (same for relpath below), but things seem to behave correctly anyway. + @overload + def join(path: _StrPath, *paths: _StrPath) -> Text: ... + @overload + def join(path: _BytesPath, *paths: _BytesPath) -> bytes: ... +else: + def join(path: AnyStr, *paths: AnyStr) -> AnyStr: ... + +@overload +def relpath(path: _BytesPath, start: Optional[_BytesPath] = ...) -> bytes: ... +@overload +def relpath(path: _StrPath, start: Optional[_StrPath] = ...) -> Text: ... + +def samefile(path1: _PathType, path2: _PathType) -> bool: ... +def sameopenfile(fp1: int, fp2: int) -> bool: ... +def samestat(stat1: os.stat_result, stat2: os.stat_result) -> bool: ... + +if sys.version_info >= (3, 6): + @overload + def split(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def split(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +else: + def split(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitdrive(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitext(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + +if sys.platform == 'win32': + def splitunc(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + +if sys.version_info < (3,): + def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/numbers.pyi b/client/typeshed-fallback/stdlib/2and3/numbers.pyi new file mode 100644 index 000000000..50b561c24 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/numbers.pyi @@ -0,0 +1,140 @@ +# Stubs for numbers (Python 3.5) +# See https://docs.python.org/2.7/library/numbers.html +# and https://docs.python.org/3/library/numbers.html +# +# Note: these stubs are incomplete. The more complex type +# signatures are currently omitted. + +from typing import Any, Optional, SupportsFloat +from abc import ABCMeta, abstractmethod +import sys + +class Number(metaclass=ABCMeta): + @abstractmethod + def __hash__(self) -> int: ... + +class Complex(Number): + @abstractmethod + def __complex__(self) -> complex: ... + if sys.version_info >= (3, 0): + def __bool__(self) -> bool: ... + else: + def __nonzero__(self) -> bool: ... + @property + @abstractmethod + def real(self): ... + @property + @abstractmethod + def imag(self): ... + @abstractmethod + def __add__(self, other): ... + @abstractmethod + def __radd__(self, other): ... + @abstractmethod + def __neg__(self): ... + @abstractmethod + def __pos__(self): ... + def __sub__(self, other): ... + def __rsub__(self, other): ... + @abstractmethod + def __mul__(self, other): ... + @abstractmethod + def __rmul__(self, other): ... + if sys.version_info < (3, 0): + @abstractmethod + def __div__(self, other): ... + @abstractmethod + def __rdiv__(self, other): ... + @abstractmethod + def __truediv__(self, other): ... + @abstractmethod + def __rtruediv__(self, other): ... + @abstractmethod + def __pow__(self, exponent): ... + @abstractmethod + def __rpow__(self, base): ... + def __abs__(self): ... + def conjugate(self): ... + def __eq__(self, other: object) -> bool: ... + if sys.version_info < (3, 0): + def __ne__(self, other: object) -> bool: ... + +class Real(Complex, SupportsFloat): + @abstractmethod + def __float__(self) -> float: ... + @abstractmethod + def __trunc__(self) -> int: ... + if sys.version_info >= (3, 0): + @abstractmethod + def __floor__(self) -> int: ... + @abstractmethod + def __ceil__(self) -> int: ... + @abstractmethod + def __round__(self, ndigits: Optional[int] = ...): ... + def __divmod__(self, other): ... + def __rdivmod__(self, other): ... + @abstractmethod + def __floordiv__(self, other): ... + @abstractmethod + def __rfloordiv__(self, other): ... + @abstractmethod + def __mod__(self, other): ... + @abstractmethod + def __rmod__(self, other): ... + @abstractmethod + def __lt__(self, other) -> bool: ... + @abstractmethod + def __le__(self, other) -> bool: ... + def __complex__(self) -> complex: ... + @property + def real(self): ... + @property + def imag(self): ... + def conjugate(self): ... + +class Rational(Real): + @property + @abstractmethod + def numerator(self) -> int: ... + @property + @abstractmethod + def denominator(self) -> int: ... + def __float__(self) -> float: ... + +class Integral(Rational): + if sys.version_info >= (3, 0): + @abstractmethod + def __int__(self) -> int: ... + else: + @abstractmethod + def __long__(self) -> long: ... + def __index__(self) -> int: ... + @abstractmethod + def __pow__(self, exponent, modulus: Optional[Any] = ...): ... + @abstractmethod + def __lshift__(self, other): ... + @abstractmethod + def __rlshift__(self, other): ... + @abstractmethod + def __rshift__(self, other): ... + @abstractmethod + def __rrshift__(self, other): ... + @abstractmethod + def __and__(self, other): ... + @abstractmethod + def __rand__(self, other): ... + @abstractmethod + def __xor__(self, other): ... + @abstractmethod + def __rxor__(self, other): ... + @abstractmethod + def __or__(self, other): ... + @abstractmethod + def __ror__(self, other): ... + @abstractmethod + def __invert__(self): ... + def __float__(self) -> float: ... + @property + def numerator(self) -> int: ... + @property + def denominator(self) -> int: ... diff --git a/client/typeshed-fallback/stdlib/2and3/opcode.pyi b/client/typeshed-fallback/stdlib/2and3/opcode.pyi new file mode 100644 index 000000000..4cc1ab03d --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/opcode.pyi @@ -0,0 +1,23 @@ +from typing import List, Dict, Optional, Sequence + +import sys + +cmp_op = ... # type: Sequence[str] +hasconst = ... # type: List[int] +hasname = ... # type: List[int] +hasjrel = ... # type: List[int] +hasjabs = ... # type: List[int] +haslocal = ... # type: List[int] +hascompare = ... # type: List[int] +hasfree = ... # type: List[int] +opname = ... # type: List[str] + +opmap = ... # type: Dict[str, int] +HAVE_ARGUMENT = ... # type: int +EXTENDED_ARG = ... # type: int + +if sys.version_info >= (3, 4): + def stack_effect(opcode: int, oparg: Optional[int] = ...) -> int: ... + +if sys.version_info >= (3, 6): + hasnargs = ... # type: List[int] diff --git a/client/typeshed-fallback/stdlib/2and3/operator.pyi b/client/typeshed-fallback/stdlib/2and3/operator.pyi new file mode 100644 index 000000000..eafc37cb3 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/operator.pyi @@ -0,0 +1,227 @@ +# Stubs for operator + +from typing import ( + Any, Callable, Container, Mapping, MutableMapping, MutableSequence, Sequence, SupportsAbs, Tuple, + TypeVar, overload, +) +import sys + + +_T = TypeVar('_T') +_K = TypeVar('_K') +_V = TypeVar('_V') + + +def lt(a: Any, b: Any) -> Any: ... +def le(a: Any, b: Any) -> Any: ... +def eq(a: Any, b: Any) -> Any: ... +def ne(a: Any, b: Any) -> Any: ... +def ge(a: Any, b: Any) -> Any: ... +def gt(a: Any, b: Any) -> Any: ... +def __lt__(a: Any, b: Any) -> Any: ... +def __le__(a: Any, b: Any) -> Any: ... +def __eq__(a: Any, b: Any) -> Any: ... +def __ne__(a: Any, b: Any) -> Any: ... +def __ge__(a: Any, b: Any) -> Any: ... +def __gt__(a: Any, b: Any) -> Any: ... + +def not_(obj: Any) -> bool: ... +def __not__(obj: Any) -> bool: ... + +def truth(x: Any) -> bool: ... + +def is_(a: Any, b: Any) -> bool: ... + +def is_not(a: Any, b: Any) -> bool: ... + +def abs(x: SupportsAbs) -> Any: ... +def __abs__(a: SupportsAbs) -> Any: ... + +def add(a: Any, b: Any) -> Any: ... +def __add__(a: Any, b: Any) -> Any: ... + +def and_(a: Any, b: Any) -> Any: ... +def __and__(a: Any, b: Any) -> Any: ... + +if sys.version_info < (3, ): + def div(a: Any, b: Any) -> Any: ... + def __div__(a: Any, b: Any) -> Any: ... + +def floordiv(a: Any, b: Any) -> Any: ... +def __floordiv__(a: Any, b: Any) -> Any: ... + +def index(a: Any) -> int: ... +def __index__(a: Any) -> int: ... + +def inv(obj: Any) -> Any: ... +def invert(obj: Any) -> Any: ... +def __inv__(obj: Any) -> Any: ... +def __invert__(obj: Any) -> Any: ... + +def lshift(a: Any, b: Any) -> Any: ... +def __lshift__(a: Any, b: Any) -> Any: ... + +def mod(a: Any, b: Any) -> Any: ... +def __mod__(a: Any, b: Any) -> Any: ... + +def mul(a: Any, b: Any) -> Any: ... +def __mul__(a: Any, b: Any) -> Any: ... + +if sys.version_info >= (3, 5): + def matmul(a: Any, b: Any) -> Any: ... + def __matmul__(a: Any, b: Any) -> Any: ... + +def neg(obj: Any) -> Any: ... +def __neg__(obj: Any) -> Any: ... + +def or_(a: Any, b: Any) -> Any: ... +def __or__(a: Any, b: Any) -> Any: ... + +def pos(obj: Any) -> Any: ... +def __pos__(obj: Any) -> Any: ... + +def pow(a: Any, b: Any) -> Any: ... +def __pow__(a: Any, b: Any) -> Any: ... + +def rshift(a: Any, b: Any) -> Any: ... +def __rshift__(a: Any, b: Any) -> Any: ... + +def sub(a: Any, b: Any) -> Any: ... +def __sub__(a: Any, b: Any) -> Any: ... + +def truediv(a: Any, b: Any) -> Any: ... +def __truediv__(a: Any, b: Any) -> Any: ... + +def xor(a: Any, b: Any) -> Any: ... +def __xor__(a: Any, b: Any) -> Any: ... + +def concat(a: Sequence[_T], b: Sequence[_T]) -> Sequence[_T]: ... +def __concat__(a: Sequence[_T], b: Sequence[_T]) -> Sequence[_T]: ... + +def contains(a: Container[Any], b: Any) -> bool: ... +def __contains__(a: Container[Any], b: Any) -> bool: ... + +def countOf(a: Container[Any], b: Any) -> int: ... + +@overload +def delitem(a: MutableSequence[_T], b: int) -> None: ... +@overload +def delitem(a: MutableMapping[_K, _V], b: _K) -> None: ... +@overload +def __delitem__(a: MutableSequence[_T], b: int) -> None: ... +@overload +def __delitem__(a: MutableMapping[_K, _V], b: _K) -> None: ... + +if sys.version_info < (3, ): + def delslice(a: MutableSequence[Any], b: int, c: int) -> None: ... + def __delslice__(a: MutableSequence[Any], b: int, c: int) -> None: ... + +@overload +def getitem(a: Sequence[_T], b: int) -> _T: ... +@overload +def getitem(a: Mapping[_K, _V], b: _K) -> _V: ... +@overload +def __getitem__(a: Sequence[_T], b: int) -> _T: ... +@overload +def __getitem__(a: Mapping[_K, _V], b: _K) -> _V: ... + +if sys.version_info < (3, ): + def getslice(a: Sequence[_T], b: int, c: int) -> Sequence[_T]: ... + def __getslice__(a: Sequence[_T], b: int, c: int) -> Sequence[_T]: ... + +def indexOf(a: Sequence[_T], b: _T) -> int: ... + +if sys.version_info < (3, ): + def repeat(a: Any, b: int) -> Any: ... + def __repeat__(a: Any, b: int) -> Any: ... + +if sys.version_info < (3, ): + def sequenceIncludes(a: Container[Any], b: Any) -> bool: ... + +@overload +def setitem(a: MutableSequence[_T], b: int, c: _T) -> None: ... +@overload +def setitem(a: MutableMapping[_K, _V], b: _K, c: _V) -> None: ... +@overload +def __setitem__(a: MutableSequence[_T], b: int, c: _T) -> None: ... +@overload +def __setitem__(a: MutableMapping[_K, _V], b: _K, c: _V) -> None: ... + +if sys.version_info < (3, ): + def setslice(a: MutableSequence[_T], b: int, c: int, v: Sequence[_T]) -> None: ... + def __setslice__(a: MutableSequence[_T], b: int, c: int, v: Sequence[_T]) -> None: ... + + +if sys.version_info >= (3, 4): + def length_hint(obj: Any, default: int = ...) -> int: ... + +@overload +def attrgetter(attr: str) -> Callable[[Any], Any]: ... +@overload +def attrgetter(*attrs: str) -> Callable[[Any], Tuple[Any, ...]]: ... + +@overload +def itemgetter(item: Any) -> Callable[[Any], Any]: ... +@overload +def itemgetter(*items: Any) -> Callable[[Any], Tuple[Any, ...]]: ... + +def methodcaller(name: str, *args: Any, **kwargs: Any) -> Callable[..., Any]: ... + + +def iadd(a: Any, b: Any) -> Any: ... +def __iadd__(a: Any, b: Any) -> Any: ... + +def iand(a: Any, b: Any) -> Any: ... +def __iand__(a: Any, b: Any) -> Any: ... + +def iconcat(a: Any, b: Any) -> Any: ... +def __iconcat__(a: Any, b: Any) -> Any: ... + +if sys.version_info < (3, ): + def idiv(a: Any, b: Any) -> Any: ... + def __idiv__(a: Any, b: Any) -> Any: ... + +def ifloordiv(a: Any, b: Any) -> Any: ... +def __ifloordiv__(a: Any, b: Any) -> Any: ... + +def ilshift(a: Any, b: Any) -> Any: ... +def __ilshift__(a: Any, b: Any) -> Any: ... + +def imod(a: Any, b: Any) -> Any: ... +def __imod__(a: Any, b: Any) -> Any: ... + +def imul(a: Any, b: Any) -> Any: ... +def __imul__(a: Any, b: Any) -> Any: ... + +if sys.version_info >= (3, 5): + def imatmul(a: Any, b: Any) -> Any: ... + def __imatmul__(a: Any, b: Any) -> Any: ... + +def ior(a: Any, b: Any) -> Any: ... +def __ior__(a: Any, b: Any) -> Any: ... + +def ipow(a: Any, b: Any) -> Any: ... +def __ipow__(a: Any, b: Any) -> Any: ... + +if sys.version_info < (3, ): + def irepeat(a: Any, b: int) -> Any: ... + def __irepeat__(a: Any, b: int) -> Any: ... + +def irshift(a: Any, b: Any) -> Any: ... +def __irshift__(a: Any, b: Any) -> Any: ... + +def isub(a: Any, b: Any) -> Any: ... +def __isub__(a: Any, b: Any) -> Any: ... + +def itruediv(a: Any, b: Any) -> Any: ... +def __itruediv__(a: Any, b: Any) -> Any: ... + +def ixor(a: Any, b: Any) -> Any: ... +def __ixor__(a: Any, b: Any) -> Any: ... + + +if sys.version_info < (3, ): + def isCallable(x: Any) -> bool: ... + def isMappingType(x: Any) -> bool: ... + def isNumberType(x: Any) -> bool: ... + def isSequenceType(x: Any) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/2and3/optparse.pyi b/client/typeshed-fallback/stdlib/2and3/optparse.pyi new file mode 100644 index 000000000..359134197 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/optparse.pyi @@ -0,0 +1,228 @@ +# Generated by pytype, with only minor tweaks. Might be incomplete. +import sys +from typing import Any, AnyStr, Callable, Dict, IO, Iterable, List, Mapping, Optional, Sequence, Tuple, Union + +# See https://groups.google.com/forum/#!topic/python-ideas/gA1gdj3RZ5g +if sys.version_info >= (3,): + _Text = str +else: + _Text = Union[str, unicode] + +NO_DEFAULT = ... # type: Tuple[_Text, ...] +SUPPRESS_HELP = ... # type: _Text +SUPPRESS_USAGE = ... # type: _Text + +def check_builtin(option: Option, opt: Any, value: _Text) -> Any: ... +def check_choice(option: Option, opt: Any, value: _Text) -> Any: ... +if sys.version_info < (3,): + def isbasestring(x: Any) -> bool: ... + +class OptParseError(Exception): + msg = ... # type: _Text + def __init__(self, msg: _Text) -> None: ... + +class BadOptionError(OptParseError): + opt_str = ... # type: _Text + def __init__(self, opt_str: _Text) -> None: ... + +class AmbiguousOptionError(BadOptionError): + possibilities = ... # type: Iterable[_Text] + def __init__(self, opt_str: _Text, possibilities: Sequence[_Text]) -> None: ... + +class OptionError(OptParseError): + msg = ... # type: _Text + option_id = ... # type: _Text + def __init__(self, msg: _Text, option: Option) -> None: ... + +class OptionConflictError(OptionError): ... + +class OptionValueError(OptParseError): ... + + +class HelpFormatter: + NO_DEFAULT_VALUE = ... # type: _Text + _long_opt_fmt = ... # type: _Text + _short_opt_fmt = ... # type: _Text + current_indent = ... # type: int + default_tag = ... # type: _Text + help_position = ... # type: Any + help_width = ... # type: Any + indent_increment = ... # type: int + level = ... # type: int + max_help_position = ... # type: int + option_strings = ... # type: Dict[Option, _Text] + parser = ... # type: OptionParser + short_first = ... # type: Any + width = ... # type: int + def __init__(self, indent_increment: int, max_help_position: int, width: Optional[int], short_first: int) -> None: ... + def _format__Text(self, _Text: _Text) -> _Text: ... + def dedent(self) -> None: ... + def expand_default(self, option: Option) -> _Text: ... + def format_description(self, description: _Text) -> _Text: ... + def format_epilog(self, epilog) -> _Text: ... + def format_heading(self, heading: Any) -> _Text: ... + def format_option(self, option: OptionParser) -> _Text: ... + def format_option_strings(self, option: OptionParser) -> Any: ... + def format_usage(self, usage: Any) -> _Text: ... + def indent(self) -> None: ... + def set_long_opt_delimiter(self, delim: _Text) -> None: ... + def set_parser(self, parser: OptionParser) -> None: ... + def set_short_opt_delimiter(self, delim: _Text) -> None: ... + def store_option_strings(self, parser: OptionParser) -> None: ... + +class IndentedHelpFormatter(HelpFormatter): + def __init__(self, + indent_increment: int = ..., + max_help_position: int = ..., + width: Optional[int] = ..., + short_first: int = ...) -> None: ... + def format_heading(self, heading: _Text) -> _Text: ... + def format_usage(self, usage: _Text) -> _Text: ... + +class TitledHelpFormatter(HelpFormatter): + def __init__(self, + indent_increment: int = ..., + max_help_position: int = ..., + width: Optional[int] = ..., + short_first: int = ...) -> None: ... + def format_heading(self, heading: _Text) -> _Text: ... + def format_usage(self, usage: _Text) -> _Text: ... + +class Option: + ACTIONS = ... # type: Tuple[_Text, ...] + ALWAYS_TYPED_ACTIONS = ... # type: Tuple[_Text, ...] + ATTRS = ... # type: List[_Text] + CHECK_METHODS = ... # type: Optional[List[Callable]] + CONST_ACTIONS = ... # type: Tuple[_Text, ...] + STORE_ACTIONS = ... # type: Tuple[_Text, ...] + TYPED_ACTIONS = ... # type: Tuple[_Text, ...] + TYPES = ... # type: Tuple[_Text, ...] + TYPE_CHECKER = ... # type: Dict[_Text, Callable] + _long_opts = ... # type: List[_Text] + _short_opts = ... # type: List[_Text] + action = ... # type: _Text + dest = ... # type: Optional[_Text] + nargs = ... # type: int + type = ... # type: Any + def __init__(self, *opts, **attrs) -> None: ... + def _check_action(self) -> None: ... + def _check_callback(self) -> None: ... + def _check_choice(self) -> None: ... + def _check_const(self) -> None: ... + def _check_dest(self) -> None: ... + def _check_nargs(self) -> None: ... + def _check_opt_strings(self, opts: Optional[_Text]) -> Any: ... + def _check_type(self) -> None: ... + def _set_attrs(self, attrs: Dict[_Text, Any]) -> None: ... + def _set_opt_strings(self, opts: _Text) -> None: ... + def check_value(self, opt: Any, value: Any) -> Any: ... + def convert_value(self, opt: Any, value: Any) -> Any: ... + def get_opt_string(self) -> _Text: ... + def process(self, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... + def take_action(self, action: _Text, dest: _Text, opt: Any, value: Any, values: Any, parser: OptionParser) -> int: ... + def takes_value(self) -> bool: ... + +make_option = Option + +class OptionContainer: + _long_opt = ... # type: Dict[_Text, Option] + _short_opt = ... # type: Dict[_Text, Option] + conflict_handler = ... # type: _Text + defaults = ... # type: Dict[_Text, Any] + description = ... # type: Any + option_class = ... # type: Any + def __init__(self, option_class: Option, conflict_handler: Any, description: Any) -> None: ... + def _check_conflict(self, option: Any) -> None: ... + def _create_option_mappings(self) -> None: ... + def _share_option_mappings(self, parser: OptionParser) -> None: ... + def add_option(self, *args, **kwargs) -> Any: ... + def add_options(self, option_list: Iterable[Option]) -> None: ... + def destroy(self) -> None: ... + def format_description(self, formatter: Optional[HelpFormatter]) -> Any: ... + def format_help(self, formatter: Optional[HelpFormatter]) -> _Text: ... + def format_option_help(self, formatter: Optional[HelpFormatter]) -> _Text: ... + def get_description(self) -> Any: ... + def get_option(self, opt_str: _Text) -> Optional[Option]: ... + def has_option(self, opt_str: _Text) -> bool: ... + def remove_option(self, opt_str: _Text) -> None: ... + def set_conflict_handler(self, handler: Any) -> None: ... + def set_description(self, description: Any) -> None: ... + +class OptionGroup(OptionContainer): + option_list = ... # type: List[Option] + parser = ... # type: OptionParser + title = ... # type: _Text + def __init__(self, parser: OptionParser, title: _Text, description: Optional[_Text] = ...) -> None: ... + def _create_option_list(self) -> None: ... + def set_title(self, title: _Text) -> None: ... + +class Values: + def __init__(self, defaults: Optional[Mapping[str, Any]] = ...) -> None: ... + def _update(self, dict: Mapping[_Text, Any], mode: Any) -> None: ... + def _update_careful(self, dict: Mapping[_Text, Any]) -> None: ... + def _update_loose(self, dict: Mapping[_Text, Any]) -> None: ... + def ensure_value(self, attr: _Text, value: Any) -> Any: ... + def read_file(self, filename: _Text, mode: _Text) -> None: ... + def read_module(self, modname: _Text, mode: _Text) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + +class OptionParser(OptionContainer): + allow_interspersed_args = ... # type: bool + epilog = ... # type: Optional[_Text] + formatter = ... # type: HelpFormatter + largs = ... # type: Optional[List[_Text]] + option_groups = ... # type: List[OptionParser] + option_list = ... # type: List[Option] + process_default_values = ... # type: Any + prog = ... # type: Optional[_Text] + rargs = ... # type: Optional[List[Any]] + standard_option_list = ... # type: List[Option] + usage = ... # type: Optional[_Text] + values = ... # type: Optional[Values] + version = ... # type: _Text + def __init__(self, + usage: Optional[_Text] = ..., + option_list: Iterable[Option] = ..., + option_class: Option = ..., + version: Optional[_Text] = ..., + conflict_handler: _Text = ..., + description: Optional[_Text] = ..., + formatter: Optional[HelpFormatter] = ..., + add_help_option: bool = ..., + prog: Optional[_Text] = ..., + epilog: Optional[_Text] = ...) -> None: ... + def _add_help_option(self) -> None: ... + def _add_version_option(self) -> None: ... + def _create_option_list(self) -> None: ... + def _get_all_options(self) -> List[Option]: ... + def _get_args(self, args: Iterable) -> List[Any]: ... + def _init_parsing_state(self) -> None: ... + def _match_long_opt(self, opt: _Text) -> _Text: ... + def _populate_option_list(self, option_list: Iterable[Option], add_help: bool = ...) -> None: ... + def _process_args(self, largs: List, rargs: List, values: Values) -> None: ... + def _process_long_opt(self, rargs: List, values: Any) -> None: ... + def _process_short_opts(self, rargs: List, values: Any) -> None: ... + def add_option_group(self, *args, **kwargs) -> OptionParser: ... + def check_values(self, values: Values, args: List[_Text]) -> Tuple[Values, List[_Text]]: ... + def disable_interspersed_args(self) -> None: ... + def enable_interspersed_args(self) -> None: ... + def error(self, msg: _Text) -> None: ... + def exit(self, status: int = ..., msg: Optional[str] = ...) -> None: ... + def expand_prog_name(self, s: Optional[_Text]) -> Any: ... + def format_epilog(self, formatter: HelpFormatter) -> Any: ... + def format_help(self, formatter: Optional[HelpFormatter] = ...) -> _Text: ... + def format_option_help(self, formatter: Optional[HelpFormatter] = ...) -> _Text: ... + def get_default_values(self) -> Values: ... + def get_option_group(self, opt_str: _Text) -> Any: ... + def get_prog_name(self) -> _Text: ... + def get_usage(self) -> _Text: ... + def get_version(self) -> _Text: ... + def parse_args(self, args: Optional[Sequence[AnyStr]] = ..., values: Optional[Values] = ...) -> Tuple[Values, List[AnyStr]]: ... + def print_usage(self, file: Optional[IO[str]] = ...) -> None: ... + def print_help(self, file: Optional[IO[str]] = ...) -> None: ... + def print_version(self, file: Optional[IO[str]] = ...) -> None: ... + def set_default(self, dest: Any, value: Any) -> None: ... + def set_defaults(self, **kwargs) -> None: ... + def set_process_default_values(self, process: Any) -> None: ... + def set_usage(self, usage: _Text) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/pdb.pyi b/client/typeshed-fallback/stdlib/2and3/pdb.pyi new file mode 100644 index 000000000..d63eaf0a6 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/pdb.pyi @@ -0,0 +1,21 @@ +# NOTE: This stub is incomplete - only contains some global functions + +import sys +from typing import Any, Dict, Optional + +class Restart(Exception): ... + +def run(statement: str, globals: Optional[Dict[str, Any]] = ..., + locals: Optional[Dict[str, Any]] = ...) -> None: ... +def runeval(expression: str, globals: Optional[Dict[str, Any]] = ..., + locals: Optional[Dict[str, Any]] = ...) -> Any: ... +def runctx(statement: str, globals: Dict[str, Any], locals: Dict[str, Any]) -> None: ... +def runcall(*args: Any, **kwds: Any) -> Any: ... + +if sys.version_info >= (3, 7): + def set_trace(*, header: Optional[str] = ...) -> None: ... +else: + def set_trace() -> None: ... + +def post_mortem(t: Optional[Any] = ...) -> None: ... +def pm() -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/pickle.pyi b/client/typeshed-fallback/stdlib/2and3/pickle.pyi new file mode 100644 index 000000000..7bfad8f3b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/pickle.pyi @@ -0,0 +1,140 @@ +import sys +from typing import Any, IO, Mapping, Union, Tuple, Callable, Optional, Iterator + +HIGHEST_PROTOCOL: int +if sys.version_info >= (3, 0): + DEFAULT_PROTOCOL: int + + +if sys.version_info >= (3, 0): + def dump(obj: Any, file: IO[bytes], protocol: Optional[int] = ..., *, + fix_imports: bool = ...) -> None: ... + def dumps(obj: Any, protocol: Optional[int] = ..., *, + fix_imports: bool = ...) -> bytes: ... + def loads(bytes_object: bytes, *, fix_imports: bool = ..., + encoding: str = ..., errors: str = ...) -> Any: ... + def load(file: IO[bytes], *, fix_imports: bool = ..., encoding: str = ..., + errors: str = ...) -> Any: ... +else: + def dump(obj: Any, file: IO[bytes], protocol: Optional[int] = ...) -> None: ... + def dumps(obj: Any, protocol: Optional[int] = ...) -> bytes: ... + def load(file: IO[bytes]) -> Any: ... + def loads(string: bytes) -> Any: ... + +class PickleError(Exception): ... +class PicklingError(PickleError): ... +class UnpicklingError(PickleError): ... + +_reducedtype = Union[str, + Tuple[Callable[..., Any], Tuple], + Tuple[Callable[..., Any], Tuple, Any], + Tuple[Callable[..., Any], Tuple, Any, + Optional[Iterator]], + Tuple[Callable[..., Any], Tuple, Any, + Optional[Iterator], Optional[Iterator]]] + + +class Pickler: + fast: bool + if sys.version_info >= (3, 3): + dispatch_table: Mapping[type, Callable[[Any], _reducedtype]] + + if sys.version_info >= (3, 0): + def __init__(self, file: IO[bytes], protocol: Optional[int] = ..., *, + fix_imports: bool = ...) -> None: ... + else: + def __init__(self, file: IO[bytes], protocol: Optional[int] = ...) -> None: ... + + def dump(self, obj: Any) -> None: ... + def clear_memo(self) -> None: ... + def persistent_id(self, obj: Any) -> Any: ... + + +class Unpickler: + if sys.version_info >= (3, 0): + def __init__(self, file: IO[bytes], *, fix_imports: bool = ..., + encoding: str = ..., errors: str = ...) -> None: ... + else: + def __init__(self, file: IO[bytes]) -> None: ... + + def load(self) -> Any: ... + def find_class(self, module: str, name: str) -> Any: ... + if sys.version_info >= (3, 0): + def persistent_load(self, pid: Any) -> Any: ... + +MARK: bytes +STOP: bytes +POP: bytes +POP_MARK: bytes +DUP: bytes +FLOAT: bytes +INT: bytes +BININT: bytes +BININT1: bytes +LONG: bytes +BININT2: bytes +NONE: bytes +PERSID: bytes +BINPERSID: bytes +REDUCE: bytes +STRING: bytes +BINSTRING: bytes +SHORT_BINSTRING: bytes +UNICODE: bytes +BINUNICODE: bytes +APPEND: bytes +BUILD: bytes +GLOBAL: bytes +DICT: bytes +EMPTY_DICT: bytes +APPENDS: bytes +GET: bytes +BINGET: bytes +INST: bytes +LONG_BINGET: bytes +LIST: bytes +EMPTY_LIST: bytes +OBJ: bytes +PUT: bytes +BINPUT: bytes +LONG_BINPUT: bytes +SETITEM: bytes +TUPLE: bytes +EMPTY_TUPLE: bytes +SETITEMS: bytes +BINFLOAT: bytes + +TRUE: bytes +FALSE: bytes + +# protocol 2 +PROTO: bytes +NEWOBJ: bytes +EXT1: bytes +EXT2: bytes +EXT4: bytes +TUPLE1: bytes +TUPLE2: bytes +TUPLE3: bytes +NEWTRUE: bytes +NEWFALSE: bytes +LONG1: bytes +LONG4: bytes + +if sys.version_info >= (3, 0): + # protocol 3 + BINBYTES: bytes + SHORT_BINBYTES: bytes + +if sys.version_info >= (3, 4): + # protocol 4 + SHORT_BINUNICODE: bytes + BINUNICODE8: bytes + BINBYTES8: bytes + EMPTY_SET: bytes + ADDITEMS: bytes + FROZENSET: bytes + NEWOBJ_EX: bytes + STACK_GLOBAL: bytes + MEMOIZE: bytes + FRAME: bytes diff --git a/client/typeshed-fallback/stdlib/2and3/pickletools.pyi b/client/typeshed-fallback/stdlib/2and3/pickletools.pyi new file mode 100644 index 000000000..c03664697 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/pickletools.pyi @@ -0,0 +1,145 @@ +# Stubs for pickletools (Python 2 and 3) +import sys +from typing import Any, Callable, IO, Iterator, List, MutableMapping, Optional, Text, Tuple, Type, Union + +_Reader = Callable[[IO[bytes]], Any] + +if sys.version_info >= (3, 0): + bytes_types: Tuple[Type[Any], ...] + +UP_TO_NEWLINE: int +TAKEN_FROM_ARGUMENT1: int +TAKEN_FROM_ARGUMENT4: int +if sys.version_info >= (3, 3): + TAKEN_FROM_ARGUMENT4U: int +if sys.version_info >= (3, 4): + TAKEN_FROM_ARGUMENT8U: int + +class ArgumentDescriptor(object): + name: str + n: int + reader: _Reader + doc: str + def __init__(self, name: str, n: int, reader: _Reader, doc: str) -> None: ... + +def read_uint1(f: IO[bytes]) -> int: ... +uint1: ArgumentDescriptor + +def read_uint2(f: IO[bytes]) -> int: ... +uint2: ArgumentDescriptor + +def read_int4(f: IO[bytes]) -> int: ... +int4: ArgumentDescriptor + +if sys.version_info >= (3, 3): + def read_uint4(f: IO[bytes]) -> int: ... + uint4: ArgumentDescriptor + +if sys.version_info >= (3, 5): + def read_uint8(f: IO[bytes]) -> int: ... + uint8: ArgumentDescriptor + +def read_stringnl(f: IO[bytes], decode: bool = ..., stripquotes: bool = ...) -> Union[bytes, Text]: ... +stringnl: ArgumentDescriptor + +def read_stringnl_noescape(f: IO[bytes]) -> str: ... +stringnl_noescape: ArgumentDescriptor + +def read_stringnl_noescape_pair(f: IO[bytes]) -> Text: ... +stringnl_noescape_pair: ArgumentDescriptor + +def read_string1(f: IO[bytes]) -> str: ... +string1: ArgumentDescriptor + +def read_string4(f: IO[bytes]) -> str: ... +string4: ArgumentDescriptor + +if sys.version_info >= (3, 3): + def read_bytes1(f: IO[bytes]) -> bytes: ... + bytes1: ArgumentDescriptor + + def read_bytes4(f: IO[bytes]) -> bytes: ... + bytes4: ArgumentDescriptor + +if sys.version_info >= (3, 4): + def read_bytes8(f: IO[bytes]) -> bytes: ... + bytes8: ArgumentDescriptor + +def read_unicodestringnl(f: IO[bytes]) -> Text: ... +unicodestringnl: ArgumentDescriptor + +if sys.version_info >= (3, 4): + def read_unicodestring1(f: IO[bytes]) -> Text: ... + unicodestring1: ArgumentDescriptor + +def read_unicodestring4(f: IO[bytes]) -> Text: ... +unicodestring4: ArgumentDescriptor + +if sys.version_info >= (3, 4): + def read_unicodestring8(f: IO[bytes]) -> Text: ... + unicodestring8: ArgumentDescriptor + +def read_decimalnl_short(f: IO[bytes]) -> int: ... +def read_decimalnl_long(f: IO[bytes]) -> int: ... +decimalnl_short: ArgumentDescriptor +decimalnl_long: ArgumentDescriptor + +def read_floatnl(f: IO[bytes]) -> float: ... +floatnl: ArgumentDescriptor + +def read_float8(f: IO[bytes]) -> float: ... +float8: ArgumentDescriptor + +def read_long1(f: IO[bytes]) -> int: ... +long1: ArgumentDescriptor + +def read_long4(f: IO[bytes]) -> int: ... +long4: ArgumentDescriptor + +class StackObject(object): + name: str + obtype: Union[Type[Any], Tuple[Type[Any], ...]] + doc: str + def __init__(self, name: str, obtype: Union[Type[Any], Tuple[Type[Any], ...]], doc: str) -> None: ... + +pyint: StackObject +pylong: StackObject +pyinteger_or_bool: StackObject +pybool: StackObject +pyfloat: StackObject +if sys.version_info >= (3, 4): + pybytes_or_str: StackObject +pystring: StackObject +if sys.version_info >= (3, 0): + pybytes: StackObject +pyunicode: StackObject +pynone: StackObject +pytuple: StackObject +pylist: StackObject +pydict: StackObject +if sys.version_info >= (3, 4): + pyset: StackObject + pyfrozenset: StackObject +anyobject: StackObject +markobject: StackObject +stackslice: StackObject + +class OpcodeInfo(object): + name: str + code: str + arg: Optional[ArgumentDescriptor] + stack_before: List[StackObject] + stack_after: List[StackObject] + proto: int + doc: str + def __init__(self, name: str, code: str, arg: Optional[ArgumentDescriptor], + stack_before: List[StackObject], stack_after: List[StackObject], proto: int, doc: str) -> None: ... + +opcodes: List[OpcodeInfo] + +def genops(pickle: Union[bytes, IO[bytes]]) -> Iterator[Tuple[OpcodeInfo, Optional[Any], Optional[int]]]: ... +def optimize(p: Union[bytes, IO[bytes]]) -> bytes: ... +if sys.version_info >= (3, 2): + def dis(pickle: Union[bytes, IO[bytes]], out: Optional[IO[str]] = ..., memo: Optional[MutableMapping[int, Any]] = ..., indentlevel: int = ..., annotate: int = ...) -> None: ... +else: + def dis(pickle: Union[bytes, IO[bytes]], out: Optional[IO[str]] = ..., memo: Optional[MutableMapping[int, Any]] = ..., indentlevel: int = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/pkgutil.pyi b/client/typeshed-fallback/stdlib/2and3/pkgutil.pyi new file mode 100644 index 000000000..c7bad4221 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/pkgutil.pyi @@ -0,0 +1,35 @@ +# Stubs for pkgutil + +from typing import Any, Callable, Generator, IO, Iterable, Optional, Tuple, NamedTuple +import sys + +if sys.version_info >= (3,): + from importlib.abc import Loader +else: + Loader = Any + +if sys.version_info >= (3, 6): + ModuleInfo = NamedTuple('ModuleInfo', [('module_finder', Any), ('name', str), ('ispkg', bool)]) + _YMFNI = Generator[ModuleInfo, None, None] +else: + _YMFNI = Generator[Tuple[Any, str, bool], None, None] + + +def extend_path(path: Iterable[str], name: str) -> Iterable[str]: ... + +class ImpImporter: + def __init__(self, dirname: Optional[str] = ...) -> None: ... + +class ImpLoader: + def __init__(self, fullname: str, file: IO[str], filename: str, + etc: Tuple[str, str, int]) -> None: ... + +def find_loader(fullname: str) -> Loader: ... +def get_importer(path_item: str) -> Any: ... # TODO precise type +def get_loader(module_or_name: str) -> Loader: ... +def iter_importers(fullname: str = ...) -> Generator[Any, None, None]: ... # TODO precise type +def iter_modules(path: Optional[Iterable[str]] = ..., + prefix: str = ...) -> _YMFNI: ... # TODO precise type +def walk_packages(path: Optional[Iterable[str]] = ..., prefix: str = ..., + onerror: Optional[Callable[[str], None]] = ...) -> _YMFNI: ... +def get_data(package: str, resource: str) -> Optional[bytes]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/plistlib.pyi b/client/typeshed-fallback/stdlib/2and3/plistlib.pyi new file mode 100644 index 000000000..d325930bd --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/plistlib.pyi @@ -0,0 +1,57 @@ +# Stubs for plistlib + +from typing import ( + Any, IO, Mapping, MutableMapping, Optional, Union, + Type, TypeVar, +) +from typing import Dict as DictT +import sys +if sys.version_info >= (3,): + from enum import Enum + + class PlistFormat(Enum): + FMT_XML = ... + FMT_BINARY = ... + FMT_XML = PlistFormat.FMT_XML + FMT_BINARY = PlistFormat.FMT_BINARY + +mm = MutableMapping[str, Any] +_D = TypeVar('_D', bound=mm) +if sys.version_info >= (3,): + _Path = str +else: + _Path = Union[str, unicode] + +if sys.version_info >= (3, 4): + def load(fp: IO[bytes], *, fmt: Optional[PlistFormat] = ..., + use_builtin_types: bool = ..., dict_type: Type[_D] = ...) -> _D: ... + def loads(data: bytes, *, fmt: Optional[PlistFormat] = ..., + use_builtin_types: bool = ..., dict_type: Type[_D] = ...) -> _D: ... + def dump(value: Mapping[str, Any], fp: IO[bytes], *, + fmt: PlistFormat = ..., sort_keys: bool = ..., + skipkeys: bool = ...) -> None: ... + def dumps(value: Mapping[str, Any], *, fmt: PlistFormat = ..., + skipkeys: bool = ..., sort_keys: bool = ...) -> bytes: ... + +def readPlist(pathOrFile: Union[_Path, IO[bytes]]) -> DictT[str, Any]: ... +def writePlist(value: Mapping[str, Any], pathOrFile: Union[_Path, IO[bytes]]) -> None: ... +def readPlistFromBytes(data: bytes) -> DictT[str, Any]: ... +def writePlistToBytes(value: Mapping[str, Any]) -> bytes: ... +if sys.version_info < (3,): + def readPlistFromResource(path: _Path, restype: str = ..., + resid: int = ...) -> DictT[str, Any]: ... + def writePlistToResource(rootObject: Mapping[str, Any], path: _Path, + restype: str = ..., + resid: int = ...) -> None: ... + def readPlistFromString(data: str) -> DictT[str, Any]: ... + def writePlistToString(rootObject: Mapping[str, Any]) -> str: ... + +if sys.version_info < (3, 7): + class Dict(dict): + def __getattr__(self, attr: str) -> Any: ... + def __setattr__(self, attr: str, value: Any) -> None: ... + def __delattr__(self, attr: str) -> None: ... + +class Data: + data = ... # type: bytes + def __init__(self, data: bytes) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/poplib.pyi b/client/typeshed-fallback/stdlib/2and3/poplib.pyi new file mode 100644 index 000000000..d2b7dab6c --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/poplib.pyi @@ -0,0 +1,77 @@ +# Stubs for poplib (Python 2 and 3) + +import socket +import ssl +import sys +from typing import ( + Any, BinaryIO, Dict, List, NoReturn, Optional, overload, Pattern, Text, + Tuple, +) + +_LongResp = Tuple[bytes, List[bytes], int] + +class error_proto(Exception): ... + +POP3_PORT: int +POP3_SSL_PORT: int +CR: bytes +LF: bytes +CRLF: bytes + + +class POP3: + if sys.version_info >= (3, 0): + encoding: Text + + host: Text + port: int + sock: socket.socket + file: BinaryIO + welcome: bytes + + def __init__(self, host: Text, port: int = ..., timeout: float = ...) -> None: ... + def getwelcome(self) -> bytes: ... + def set_debuglevel(self, level: int) -> None: ... + def user(self, user: Text) -> bytes: ... + def pass_(self, pswd: Text) -> bytes: ... + def stat(self) -> Tuple[int, int]: ... + def list(self, which: Optional[Any] = ...) -> _LongResp: ... + def retr(self, which: Any) -> _LongResp: ... + def dele(self, which: Any) -> bytes: ... + def noop(self) -> bytes: ... + def rset(self) -> bytes: ... + def quit(self) -> bytes: ... + def close(self) -> None: ... + def rpop(self, user: Text) -> bytes: ... + + timestamp: Pattern[Text] + + if sys.version_info < (3, 0): + def apop(self, user: Text, secret: Text) -> bytes: ... + else: + def apop(self, user: Text, password: Text) -> bytes: ... + def top(self, which: Any, howmuch: int) -> _LongResp: ... + + @overload + def uidl(self) -> _LongResp: ... + @overload + def uidl(self, which: Any) -> bytes: ... + + if sys.version_info >= (3, 5): + def utf8(self) -> bytes: ... + if sys.version_info >= (3, 4): + def capa(self) -> Dict[Text, List[Text]]: ... + def stls(self, context: Optional[ssl.SSLContext] = ...) -> bytes: ... + + +class POP3_SSL(POP3): + if sys.version_info >= (3, 0): + def __init__(self, host: Text, port: int = ..., keyfile: Optional[Text] = ..., certfile: Optional[Text] = ..., + timeout: float = ..., context: Optional[ssl.SSLContext] = ...) -> None: ... + else: + def __init__(self, host: Text, port: int = ..., keyfile: Optional[Text] = ..., certfile: Optional[Text] = ..., + timeout: float = ...) -> None: ... + + if sys.version_info >= (3, 4): + # "context" is actually the last argument, but that breaks LSP and it doesn't really matter because all the arguments are ignored + def stls(self, context: Any = ..., keyfile: Any = ..., certfile: Any = ...) -> bytes: ... diff --git a/client/typeshed-fallback/stdlib/2and3/posixpath.pyi b/client/typeshed-fallback/stdlib/2and3/posixpath.pyi new file mode 100644 index 000000000..09663afa4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/posixpath.pyi @@ -0,0 +1,177 @@ +# NB: path.pyi and stdlib/2 and stdlib/3 must remain consistent! +# Stubs for os.path +# Ron Murawski + +import os +import sys +from typing import ( + overload, List, Any, AnyStr, Sequence, Tuple, BinaryIO, TextIO, + TypeVar, Union, Text, Callable, Optional +) + +_T = TypeVar('_T') + +if sys.version_info >= (3, 6): + from builtins import _PathLike + _PathType = Union[bytes, Text, _PathLike] + _StrPath = Union[Text, _PathLike[Text]] + _BytesPath = Union[bytes, _PathLike[bytes]] +else: + _PathType = Union[bytes, Text] + _StrPath = Text + _BytesPath = bytes + +# ----- os.path variables ----- +supports_unicode_filenames: bool +# aliases (also in os) +curdir: str +pardir: str +sep: str +altsep: str +extsep: str +pathsep: str +defpath: str +devnull: str + +# ----- os.path function stubs ----- +if sys.version_info >= (3, 6): + # Overloads are necessary to work around python/mypy#3644. + @overload + def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def abspath(path: AnyStr) -> AnyStr: ... + @overload + def basename(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def basename(path: AnyStr) -> AnyStr: ... + @overload + def dirname(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def dirname(path: AnyStr) -> AnyStr: ... + @overload + def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expanduser(path: AnyStr) -> AnyStr: ... + @overload + def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expandvars(path: AnyStr) -> AnyStr: ... + @overload + def normcase(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normcase(path: AnyStr) -> AnyStr: ... + @overload + def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + @overload + def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(path: AnyStr) -> AnyStr: ... + else: + @overload + def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(filename: AnyStr) -> AnyStr: ... + +else: + def abspath(path: AnyStr) -> AnyStr: ... + def basename(path: AnyStr) -> AnyStr: ... + def dirname(path: AnyStr) -> AnyStr: ... + def expanduser(path: AnyStr) -> AnyStr: ... + def expandvars(path: AnyStr) -> AnyStr: ... + def normcase(path: AnyStr) -> AnyStr: ... + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + def realpath(path: AnyStr) -> AnyStr: ... + else: + def realpath(filename: AnyStr) -> AnyStr: ... + +if sys.version_info >= (3, 6): + # In reality it returns str for sequences of _StrPath and bytes for sequences + # of _BytesPath, but mypy does not accept such a signature. + def commonpath(paths: Sequence[_PathType]) -> Any: ... +elif sys.version_info >= (3, 5): + def commonpath(paths: Sequence[AnyStr]) -> AnyStr: ... + +# NOTE: Empty lists results in '' (str) regardless of contained type. +# Also, in Python 2 mixed sequences of Text and bytes results in either Text or bytes +# So, fall back to Any +def commonprefix(list: Sequence[_PathType]) -> Any: ... + +if sys.version_info >= (3, 3): + def exists(path: Union[_PathType, int]) -> bool: ... +else: + def exists(path: _PathType) -> bool: ... +def lexists(path: _PathType) -> bool: ... + +# These return float if os.stat_float_times() == True, +# but int is a subclass of float. +def getatime(path: _PathType) -> float: ... +def getmtime(path: _PathType) -> float: ... +def getctime(path: _PathType) -> float: ... + +def getsize(path: _PathType) -> int: ... +def isabs(path: _PathType) -> bool: ... +def isfile(path: _PathType) -> bool: ... +def isdir(path: _PathType) -> bool: ... +def islink(path: _PathType) -> bool: ... +def ismount(path: _PathType) -> bool: ... + +if sys.version_info < (3, 0): + # Make sure signatures are disjunct, and allow combinations of bytes and unicode. + # (Since Python 2 allows that, too) + # Note that e.g. os.path.join("a", "b", "c", "d", u"e") will still result in + # a type error. + @overload + def join(__p1: bytes, *p: bytes) -> bytes: ... + @overload + def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: bytes, __p2: bytes, __p3: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: bytes, __p2: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: Text, *p: _PathType) -> Text: ... +elif sys.version_info >= (3, 6): + # Mypy complains that the signatures overlap (same for relpath below), but things seem to behave correctly anyway. + @overload + def join(path: _StrPath, *paths: _StrPath) -> Text: ... + @overload + def join(path: _BytesPath, *paths: _BytesPath) -> bytes: ... +else: + def join(path: AnyStr, *paths: AnyStr) -> AnyStr: ... + +@overload +def relpath(path: _BytesPath, start: Optional[_BytesPath] = ...) -> bytes: ... +@overload +def relpath(path: _StrPath, start: Optional[_StrPath] = ...) -> Text: ... + +def samefile(path1: _PathType, path2: _PathType) -> bool: ... +def sameopenfile(fp1: int, fp2: int) -> bool: ... +def samestat(stat1: os.stat_result, stat2: os.stat_result) -> bool: ... + +if sys.version_info >= (3, 6): + @overload + def split(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def split(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +else: + def split(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitdrive(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitext(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + +if sys.platform == 'win32': + def splitunc(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + +if sys.version_info < (3,): + def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/pprint.pyi b/client/typeshed-fallback/stdlib/2and3/pprint.pyi new file mode 100644 index 000000000..90a87ab0f --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/pprint.pyi @@ -0,0 +1,40 @@ +# Stubs for pprint + +# Based on http://docs.python.org/2/library/pprint.html +# Based on http://docs.python.org/3/library/pprint.html + +import sys +from typing import Any, Dict, Tuple, IO + +if sys.version_info >= (3, 4): + def pformat(o: object, indent: int = ..., width: int = ..., + depth: int = ..., compact: bool = ...) -> str: ... +else: + def pformat(o: object, indent: int = ..., width: int = ..., + depth: int = ...) -> str: ... + +if sys.version_info >= (3, 4): + def pprint(o: object, stream: IO[str] = ..., indent: int = ..., width: int = ..., + depth: int = ..., compact: bool = ...) -> None: ... +else: + def pprint(o: object, stream: IO[str] = ..., indent: int = ..., width: int = ..., + depth: int = ...) -> None: ... + +def isreadable(o: object) -> bool: ... +def isrecursive(o: object) -> bool: ... +def saferepr(o: object) -> str: ... + +class PrettyPrinter: + if sys.version_info >= (3, 4): + def __init__(self, indent: int = ..., width: int = ..., depth: int = ..., + stream: IO[str] = ..., compact: bool = ...) -> None: ... + else: + def __init__(self, indent: int = ..., width: int = ..., depth: int = ..., + stream: IO[str] = ...) -> None: ... + + def pformat(self, o: object) -> str: ... + def pprint(self, o: object) -> None: ... + def isreadable(self, o: object) -> bool: ... + def isrecursive(self, o: object) -> bool: ... + def format(self, o: object, context: Dict[int, Any], maxlevels: int, + level: int) -> Tuple[str, bool, bool]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/profile.pyi b/client/typeshed-fallback/stdlib/2and3/profile.pyi new file mode 100644 index 000000000..31236bbfb --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/profile.pyi @@ -0,0 +1,27 @@ +import os +import sys +from typing import Any, Callable, Dict, Optional, Text, TypeVar, Union + +def run(statement: str, filename: Optional[str] = ..., sort: Union[str, int] = ...) -> None: ... +def runctx(statement: str, globals: Dict[str, Any], locals: Dict[str, Any], filename: Optional[str] = ..., sort: Union[str, int] = ...) -> None: ... + +_SelfT = TypeVar('_SelfT', bound='Profile') +_T = TypeVar('_T') +if sys.version_info >= (3, 6): + _Path = Union[bytes, Text, os.PathLike[Any]] +else: + _Path = Union[bytes, Text] + +class Profile: + def __init__(self, timer: Optional[Callable[[], float]] = ..., bias: Optional[int] = ...) -> None: ... + def set_cmd(self, cmd: str) -> None: ... + def simulate_call(self, name: str) -> None: ... + def simulate_cmd_complete(self) -> None: ... + def print_stats(self, sort: Union[str, int] = ...) -> None: ... + def dump_stats(self, file: _Path) -> None: ... + def create_stats(self) -> None: ... + def snapshot_stats(self) -> None: ... + def run(self: _SelfT, cmd: str) -> _SelfT: ... + def runctx(self: _SelfT, cmd: str, globals: Dict[str, Any], locals: Dict[str, Any]) -> _SelfT: ... + def runcall(self, func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... + def calibrate(self, m: int, verbose: int = ...) -> float: ... diff --git a/client/typeshed-fallback/stdlib/2and3/pstats.pyi b/client/typeshed-fallback/stdlib/2and3/pstats.pyi new file mode 100644 index 000000000..8bf1b0dae --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/pstats.pyi @@ -0,0 +1,39 @@ +from profile import Profile +from cProfile import Profile as _cProfile +import os +import sys +from typing import Any, Dict, IO, Iterable, List, Text, Tuple, TypeVar, Union, overload + +_Selector = Union[str, float, int] +_T = TypeVar('_T', bound='Stats') +if sys.version_info >= (3, 6): + _Path = Union[bytes, Text, os.PathLike[Any]] +else: + _Path = Union[bytes, Text] + +class Stats: + def __init__(self: _T, __arg: Union[None, str, Text, Profile, _cProfile] = ..., + *args: Union[None, str, Text, Profile, _cProfile, _T], + stream: IO[Any] = ...) -> None: ... + def init(self, arg: Union[None, str, Text, Profile, _cProfile]) -> None: ... + def load_stats(self, arg: Union[None, str, Text, Profile, _cProfile]) -> None: ... + def get_top_level_stats(self) -> None: ... + def add(self: _T, *arg_list: Union[None, str, Text, Profile, _cProfile, _T]) -> _T: ... + def dump_stats(self, filename: _Path) -> None: ... + def get_sort_arg_defs(self) -> Dict[str, Tuple[Tuple[Tuple[int, int], ...], str]]: ... + @overload + def sort_stats(self: _T, field: int) -> _T: ... + @overload + def sort_stats(self: _T, *field: str) -> _T: ... + def reverse_order(self: _T) -> _T: ... + def strip_dirs(self: _T) -> _T: ... + def calc_callees(self) -> None: ... + def eval_print_amount(self, sel: _Selector, list: List[str], msg: str) -> Tuple[List[str], str]: ... + def get_print_list(self, sel_list: Iterable[_Selector]) -> Tuple[int, List[str]]: ... + def print_stats(self: _T, *amount: _Selector) -> _T: ... + def print_callees(self: _T, *amount: _Selector) -> _T: ... + def print_callers(self: _T, *amount: _Selector) -> _T: ... + def print_call_heading(self, name_size: int, column_title: str) -> None: ... + def print_call_line(self, name_size: int, source: str, call_dict: Dict[str, Any], arrow: str = ...) -> None: ... + def print_title(self) -> None: ... + def print_line(self, func: str) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/pty.pyi b/client/typeshed-fallback/stdlib/2and3/pty.pyi new file mode 100644 index 000000000..3931bb0a9 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/pty.pyi @@ -0,0 +1,20 @@ +# Stubs for pty (Python 2 and 3) +import sys +from typing import Callable, Iterable, Tuple, Union + +_Reader = Callable[[int], bytes] + +STDIN_FILENO: int +STDOUT_FILENO: int +STDERR_FILENO: int + +CHILD: int + +def openpty() -> Tuple[int, int]: ... +def master_open() -> Tuple[int, str]: ... +def slave_open(tty_name: str) -> int: ... +def fork() -> Tuple[int, int]: ... +if sys.version_info >= (3, 4): + def spawn(argv: Union[str, Iterable[str]], master_read: _Reader = ..., stdin_read: _Reader = ...) -> int: ... +else: + def spawn(argv: Union[str, Iterable[str]], master_read: _Reader = ..., stdin_read: _Reader = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/pwd.pyi b/client/typeshed-fallback/stdlib/2and3/pwd.pyi new file mode 100644 index 000000000..5bd0bbb64 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/pwd.pyi @@ -0,0 +1,13 @@ +from typing import List, NamedTuple + +struct_passwd = NamedTuple("struct_passwd", [("pw_name", str), + ("pw_passwd", str), + ("pw_uid", int), + ("pw_gid", int), + ("pw_gecos", str), + ("pw_dir", str), + ("pw_shell", str)]) + +def getpwall() -> List[struct_passwd]: ... +def getpwuid(uid: int) -> struct_passwd: ... +def getpwnam(name: str) -> struct_passwd: ... diff --git a/client/typeshed-fallback/stdlib/2and3/py_compile.pyi b/client/typeshed-fallback/stdlib/2and3/py_compile.pyi new file mode 100644 index 000000000..ad8e8c8a3 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/py_compile.pyi @@ -0,0 +1,20 @@ +# Stubs for py_compile (Python 2 and 3) +import sys + +from typing import Optional, List, Text, AnyStr, Union + +_EitherStr = Union[bytes, Text] + +class PyCompileError(Exception): + exc_type_name = ... # type: str + exc_value = ... # type: BaseException + file = ... # type: str + msg = ... # type: str + def __init__(self, exc_type: str, exc_value: BaseException, file: str, msg: str = ...) -> None: ... + +if sys.version_info >= (3, 2): + def compile(file: AnyStr, cfile: Optional[AnyStr] = ..., dfile: Optional[AnyStr] = ..., doraise: bool = ..., optimize: int = ...) -> Optional[AnyStr]: ... +else: + def compile(file: _EitherStr, cfile: Optional[_EitherStr] = ..., dfile: Optional[_EitherStr] = ..., doraise: bool = ...) -> None: ... + +def main(args: Optional[List[Text]] = ...) -> int: ... diff --git a/client/typeshed-fallback/stdlib/2and3/pyclbr.pyi b/client/typeshed-fallback/stdlib/2and3/pyclbr.pyi new file mode 100644 index 000000000..127f2ae38 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/pyclbr.pyi @@ -0,0 +1,40 @@ +from typing import List, Union, Sequence, Optional, Dict + + +class Class: + module = ... # type: str + name = ... # type: str + super = ... # type: Optional[List[Union[Class, str]]] + methods = ... # type: Dict[str, int] + file = ... # type: int + lineno = ... # type: int + + def __init__(self, + module: str, + name: str, + super: Optional[List[Union[Class, str]]], + file: str, + lineno: int) -> None: ... + + +class Function: + module = ... # type: str + name = ... # type: str + file = ... # type: int + lineno = ... # type: int + + def __init__(self, + module: str, + name: str, + file: str, + lineno: int) -> None: ... + + +def readmodule(module: str, + path: Optional[Sequence[str]] = ... + ) -> Dict[str, Class]: ... + + +def readmodule_ex(module: str, + path: Optional[Sequence[str]] = ... + ) -> Dict[str, Union[Class, Function, List[str]]]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/pyexpat/__init__.pyi b/client/typeshed-fallback/stdlib/2and3/pyexpat/__init__.pyi new file mode 100644 index 000000000..670e56106 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/pyexpat/__init__.pyi @@ -0,0 +1,75 @@ +from typing import List, Tuple, Optional, Callable, Any, Protocol, Union, Dict, Text + +import pyexpat.errors as errors +import pyexpat.model as model + +EXPAT_VERSION: str # undocumented +version_info: Tuple[int, int, int] # undocumented +native_encoding: str # undocumented +features: List[Tuple[str, int]] # undocumented + +class ExpatError(Exception): + code: int + lineno: int + offset: int + +error = ExpatError + +class _Reader(Protocol): + def read(self, length: int) -> bytes: ... + +XML_PARAM_ENTITY_PARSING_NEVER: int +XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE: int +XML_PARAM_ENTITY_PARSING_ALWAYS: int + +_Model = Tuple[int, int, Optional[str], tuple] + +class XMLParserType(object): + def Parse(self, data: Union[Text, bytes], isfinal: bool = ...) -> int: ... + def ParseFile(self, file: _Reader) -> int: ... + def SetBase(self, base: Text) -> None: ... + def GetBase(self) -> Optional[str]: ... + def GetInputContext(self) -> Optional[bytes]: ... + def ExternalEntityParserCreate(self, context: Optional[Text], encoding: Text = ...) -> XMLParserType: ... + def SetParamEntityParsing(self, flag: int) -> int: ... + def UseForeignDTD(self, flag: bool = ...) -> None: ... + buffer_size: int + buffer_text: bool + buffer_used: int + namespace_prefixes: bool # undocumented + ordered_attributes: bool + specified_attributes: bool + ErrorByteIndex: int + ErrorCode: int + ErrorColumnNumber: int + ErrorLineNumber: int + CurrentByteIndex: int + CurrentColumnNumber: int + CurrentLineNumber: int + XmlDeclHandler: Optional[Callable[[str, Optional[str], int], Any]] + StartDoctypeDeclHandler: Optional[Callable[[str, Optional[str], Optional[str], bool], Any]] + EndDoctypeDeclHandler: Optional[Callable[[], Any]] + ElementDeclHandler: Optional[Callable[[str, _Model], Any]] + AttlistDeclHandler: Optional[Callable[[str, str, str, Optional[str], bool], Any]] + StartElementHandler: Optional[Union[ + Callable[[str, Dict[str, str]], Any], + Callable[[str, List[str]], Any], + Callable[[str, Union[Dict[str, str]], List[str]], Any]]] + EndElementHandler: Optional[Callable[[str], Any]] + ProcessingInstructionHandler: Optional[Callable[[str, str], Any]] + CharacterDataHandler: Optional[Callable[[str], Any]] + UnparsedEntityDeclHandler: Optional[Callable[[str, Optional[str], str, Optional[str], str], Any]] + EntityDeclHandler: Optional[Callable[[str, bool, Optional[str], Optional[str], str, Optional[str], Optional[str]], Any]] + NotationDeclHandler: Optional[Callable[[str, Optional[str], str, Optional[str]], Any]] + StartNamespaceDeclHandler: Optional[Callable[[str, str], Any]] + EndNamespaceDeclHandler: Optional[Callable[[str], Any]] + CommentHandler: Optional[Callable[[str], Any]] + StartCdataSectionHandler: Optional[Callable[[], Any]] + EndCdataSectionHandler: Optional[Callable[[], Any]] + DefaultHandler: Optional[Callable[[str], Any]] + DefaultHandlerExpand: Optional[Callable[[str], Any]] + NotStandaloneHandler: Optional[Callable[[], int]] + ExternalEntityRefHandler: Optional[Callable[[str, Optional[str], Optional[str], Optional[str]], int]] + +def ErrorString(errno: int) -> str: ... +def ParserCreate(encoding: Optional[Text] = ..., namespace_separator: Optional[Text] = ...) -> XMLParserType: ... diff --git a/client/typeshed-fallback/stdlib/2and3/pyexpat/errors.pyi b/client/typeshed-fallback/stdlib/2and3/pyexpat/errors.pyi new file mode 100644 index 000000000..6cde43e3b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/pyexpat/errors.pyi @@ -0,0 +1,44 @@ +import sys +from typing import Dict + +if sys.version_info >= (3, 2): + codes: Dict[str, int] + messages: Dict[int, str] + +XML_ERROR_ABORTED: str +XML_ERROR_ASYNC_ENTITY: str +XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF: str +XML_ERROR_BAD_CHAR_REF: str +XML_ERROR_BINARY_ENTITY_REF: str +XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING: str +XML_ERROR_DUPLICATE_ATTRIBUTE: str +XML_ERROR_ENTITY_DECLARED_IN_PE: str +XML_ERROR_EXTERNAL_ENTITY_HANDLING: str +XML_ERROR_FEATURE_REQUIRES_XML_DTD: str +XML_ERROR_FINISHED: str +XML_ERROR_INCOMPLETE_PE: str +XML_ERROR_INCORRECT_ENCODING: str +XML_ERROR_INVALID_TOKEN: str +XML_ERROR_JUNK_AFTER_DOC_ELEMENT: str +XML_ERROR_MISPLACED_XML_PI: str +XML_ERROR_NOT_STANDALONE: str +XML_ERROR_NOT_SUSPENDED: str +XML_ERROR_NO_ELEMENTS: str +XML_ERROR_NO_MEMORY: str +XML_ERROR_PARAM_ENTITY_REF: str +XML_ERROR_PARTIAL_CHAR: str +XML_ERROR_PUBLICID: str +XML_ERROR_RECURSIVE_ENTITY_REF: str +XML_ERROR_SUSPENDED: str +XML_ERROR_SUSPEND_PE: str +XML_ERROR_SYNTAX: str +XML_ERROR_TAG_MISMATCH: str +XML_ERROR_TEXT_DECL: str +XML_ERROR_UNBOUND_PREFIX: str +XML_ERROR_UNCLOSED_CDATA_SECTION: str +XML_ERROR_UNCLOSED_TOKEN: str +XML_ERROR_UNDECLARING_PREFIX: str +XML_ERROR_UNDEFINED_ENTITY: str +XML_ERROR_UNEXPECTED_STATE: str +XML_ERROR_UNKNOWN_ENCODING: str +XML_ERROR_XML_DECL: str diff --git a/client/typeshed-fallback/stdlib/2and3/pyexpat/model.pyi b/client/typeshed-fallback/stdlib/2and3/pyexpat/model.pyi new file mode 100644 index 000000000..f357cf651 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/pyexpat/model.pyi @@ -0,0 +1,11 @@ +XML_CTYPE_ANY: int +XML_CTYPE_CHOICE: int +XML_CTYPE_EMPTY: int +XML_CTYPE_MIXED: int +XML_CTYPE_NAME: int +XML_CTYPE_SEQ: int + +XML_CQUANT_NONE: int +XML_CQUANT_OPT: int +XML_CQUANT_PLUS: int +XML_CQUANT_REP: int diff --git a/client/typeshed-fallback/stdlib/2and3/quopri.pyi b/client/typeshed-fallback/stdlib/2and3/quopri.pyi new file mode 100644 index 000000000..2823f8c40 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/quopri.pyi @@ -0,0 +1,8 @@ +# Stubs for quopri (Python 2 and 3) + +from typing import BinaryIO + +def encode(input: BinaryIO, output: BinaryIO, quotetabs: int, header: int = ...) -> None: ... +def encodestring(s: bytes, quotetabs: int = ..., header: int = ...) -> bytes: ... +def decode(input: BinaryIO, output: BinaryIO, header: int = ...) -> None: ... +def decodestring(s: bytes, header: int = ...) -> bytes: ... diff --git a/client/typeshed-fallback/stdlib/2and3/readline.pyi b/client/typeshed-fallback/stdlib/2and3/readline.pyi new file mode 100644 index 000000000..aff2debf2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/readline.pyi @@ -0,0 +1,41 @@ +# Stubs for readline + +from typing import Callable, Optional, Sequence +import sys + +_CompleterT = Optional[Callable[[str, int], Optional[str]]] +_CompDispT = Optional[Callable[[str, Sequence[str], int], None]] + + +def parse_and_bind(string: str) -> None: ... +def read_init_file(filename: str = ...) -> None: ... + +def get_line_buffer() -> str: ... +def insert_text(string: str) -> None: ... +def redisplay() -> None: ... + +def read_history_file(filename: str = ...) -> None: ... +def write_history_file(filename: str = ...) -> None: ... +if sys.version_info >= (3, 5): + def append_history_file(nelements: int, filename: str = ...) -> None: ... +def get_history_length() -> int: ... +def set_history_length(length: int) -> None: ... + +def clear_history() -> None: ... +def get_current_history_length() -> int: ... +def get_history_item(index: int) -> str: ... +def remove_history_item(pos: int) -> None: ... +def replace_history_item(pos: int, line: str) -> None: ... +def add_history(string: str) -> None: ... + +def set_startup_hook(function: Optional[Callable[[], None]] = ...) -> None: ... +def set_pre_input_hook(function: Optional[Callable[[], None]] = ...) -> None: ... + +def set_completer(function: _CompleterT = ...) -> None: ... +def get_completer() -> _CompleterT: ... +def get_completion_type() -> int: ... +def get_begidx() -> int: ... +def get_endidx() -> int: ... +def set_completer_delims(string: str) -> None: ... +def get_completer_delims() -> str: ... +def set_completion_display_matches_hook(function: _CompDispT = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/rlcompleter.pyi b/client/typeshed-fallback/stdlib/2and3/rlcompleter.pyi new file mode 100644 index 000000000..3db9d0c40 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/rlcompleter.pyi @@ -0,0 +1,14 @@ +# Stubs for rlcompleter + +from typing import Any, Dict, Optional, Union +import sys + +if sys.version_info >= (3,): + _Text = str +else: + _Text = Union[str, unicode] + + +class Completer: + def __init__(self, namespace: Optional[Dict[str, Any]] = ...) -> None: ... + def complete(self, text: _Text, state: int) -> Optional[str]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/sched.pyi b/client/typeshed-fallback/stdlib/2and3/sched.pyi new file mode 100644 index 000000000..5d5cf33d2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/sched.pyi @@ -0,0 +1,27 @@ +import sys +from typing import Any, Callable, Dict, List, NamedTuple, Optional, Text, Tuple + +Event = NamedTuple('Event', [ + ('time', float), + ('priority', Any), + ('action', Callable[..., Any]), + ('argument', Tuple[Any, ...]), + ('kwargs', Dict[Text, Any]), +]) + +class scheduler: + if sys.version_info >= (3, 3): + def __init__(self, timefunc: Callable[[], float] = ..., delayfunc: Callable[[float], None] = ...) -> None: ... + def enterabs(self, time: float, priority: Any, action: Callable[..., Any], argument: Tuple[Any, ...] = ..., kwargs: Dict[str, Any] = ...) -> Event: ... + def enter(self, delay: float, priority: Any, action: Callable[..., Any], argument: Tuple[Any, ...] = ..., kwargs: Dict[str, Any] = ...) -> Event: ... + def run(self, blocking: bool = ...) -> Optional[float]: ... + else: + def __init__(self, timefunc: Callable[[], float], delayfunc: Callable[[float], None]) -> None: ... + def enterabs(self, time: float, priority: Any, action: Callable[..., Any], argument: Tuple[Any, ...]) -> Event: ... + def enter(self, delay: float, priority: Any, action: Callable[..., Any], argument: Tuple[Any, ...]) -> Event: ... + def run(self) -> None: ... + + def cancel(self, event: Event) -> None: ... + def empty(self) -> bool: ... + @property + def queue(self) -> List[Event]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/select.pyi b/client/typeshed-fallback/stdlib/2and3/select.pyi new file mode 100644 index 000000000..ab9ffc636 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/select.pyi @@ -0,0 +1,137 @@ +import sys +from typing import Any, Optional, Sequence, Tuple, Iterable, List, Union + +# When we have protocols, this should change to a protocol with a fileno method +# See https://docs.python.org/3/c-api/file.html#c.PyObject_AsFileDescriptor +_FileDescriptor = Union[int, Any] + +EPOLLERR: int +EPOLLET: int +EPOLLHUP: int +EPOLLIN: int +EPOLLMSG: int +EPOLLONESHOT: int +EPOLLOUT: int +EPOLLPRI: int +EPOLLRDBAND: int +EPOLLRDNORM: int +EPOLLWRBAND: int +EPOLLWRNORM: int +EPOLL_RDHUP: int +KQ_EV_ADD: int +KQ_EV_CLEAR: int +KQ_EV_DELETE: int +KQ_EV_DISABLE: int +KQ_EV_ENABLE: int +KQ_EV_EOF: int +KQ_EV_ERROR: int +KQ_EV_FLAG1: int +KQ_EV_ONESHOT: int +KQ_EV_SYSFLAGS: int +KQ_FILTER_AIO: int +KQ_FILTER_NETDEV: int +KQ_FILTER_PROC: int +KQ_FILTER_READ: int +KQ_FILTER_SIGNAL: int +KQ_FILTER_TIMER: int +KQ_FILTER_VNODE: int +KQ_FILTER_WRITE: int +KQ_NOTE_ATTRIB: int +KQ_NOTE_CHILD: int +KQ_NOTE_DELETE: int +KQ_NOTE_EXEC: int +KQ_NOTE_EXIT: int +KQ_NOTE_EXTEND: int +KQ_NOTE_FORK: int +KQ_NOTE_LINK: int +KQ_NOTE_LINKDOWN: int +KQ_NOTE_LINKINV: int +KQ_NOTE_LINKUP: int +KQ_NOTE_LOWAT: int +KQ_NOTE_PCTRLMASK: int +KQ_NOTE_PDATAMASK: int +KQ_NOTE_RENAME: int +KQ_NOTE_REVOKE: int +KQ_NOTE_TRACK: int +KQ_NOTE_TRACKERR: int +KQ_NOTE_WRITE: int +PIPE_BUF: int +POLLERR: int +POLLHUP: int +POLLIN: int +POLLMSG: int +POLLNVAL: int +POLLOUT: int +POLLPRI: int +POLLRDBAND: int +POLLRDNORM: int +POLLWRBAND: int +POLLWRNORM: int + +class poll: + def __init__(self) -> None: ... + def register(self, fd: _FileDescriptor, eventmask: int = ...) -> None: ... + def modify(self, fd: _FileDescriptor, eventmask: int) -> None: ... + def unregister(self, fd: _FileDescriptor) -> None: ... + def poll(self, timeout: Optional[float] = ...) -> List[Tuple[int, int]]: ... + +def select(rlist: Sequence[Any], wlist: Sequence[Any], xlist: Sequence[Any], + timeout: Optional[float] = ...) -> Tuple[List[Any], + List[Any], + List[Any]]: ... + +if sys.version_info >= (3, 3): + error = OSError +else: + class error(Exception): ... + +# BSD only +class kevent(object): + data: Any + fflags: int + filter: int + flags: int + ident: int + udata: Any + def __init__(self, ident: _FileDescriptor, filter: int = ..., flags: int = ..., fflags: int = ..., data: Any = ..., udata: Any = ...) -> None: ... + +# BSD only +class kqueue(object): + closed: bool + def __init__(self) -> None: ... + def close(self) -> None: ... + def control(self, changelist: Optional[Iterable[kevent]], max_events: int, timeout: float = ...) -> List[kevent]: ... + def fileno(self) -> int: ... + @classmethod + def fromfd(cls, fd: _FileDescriptor) -> kqueue: ... + +# Linux only +class epoll(object): + if sys.version_info >= (3, 3): + def __init__(self, sizehint: int = ..., flags: int = ...) -> None: ... + else: + def __init__(self, sizehint: int = ...) -> None: ... + if sys.version_info >= (3, 4): + def __enter__(self) -> epoll: ... + def __exit__(self, *args: Any) -> None: ... + def close(self) -> None: ... + closed: bool + def fileno(self) -> int: ... + def register(self, fd: _FileDescriptor, eventmask: int = ...) -> None: ... + def modify(self, fd: _FileDescriptor, eventmask: int) -> None: ... + def unregister(self, fd: _FileDescriptor) -> None: ... + def poll(self, timeout: float = ..., maxevents: int = ...) -> List[Tuple[int, int]]: ... + @classmethod + def fromfd(cls, fd: _FileDescriptor) -> epoll: ... + +if sys.version_info >= (3, 3): + # Solaris only + class devpoll: + if sys.version_info >= (3, 4): + def close(self) -> None: ... + closed: bool + def fileno(self) -> int: ... + def register(self, fd: _FileDescriptor, eventmask: int = ...) -> None: ... + def modify(self, fd: _FileDescriptor, eventmask: int = ...) -> None: ... + def unregister(self, fd: _FileDescriptor) -> None: ... + def poll(self, timeout: Optional[float] = ...) -> List[Tuple[int, int]]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/shutil.pyi b/client/typeshed-fallback/stdlib/2and3/shutil.pyi new file mode 100644 index 000000000..de1f8fcc8 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/shutil.pyi @@ -0,0 +1,135 @@ +import os +import sys + +# 'bytes' paths are not properly supported: they don't work with all functions, +# sometimes they only work partially (broken exception messages), and the test +# cases don't use them. + +from typing import ( + List, Iterable, Callable, Any, Tuple, Sequence, NamedTuple, IO, + AnyStr, Optional, Union, Set, TypeVar, overload, Type, Protocol, Text +) + +if sys.version_info >= (3, 6): + _Path = Union[str, os.PathLike[str]] + _AnyStr = str + _AnyPath = TypeVar("_AnyPath", str, os.PathLike[str]) + # Return value of some functions that may either return a path-like object that was passed in or + # a string + _PathReturn = Any +elif sys.version_info >= (3,): + _Path = str + _AnyStr = str + _AnyPath = str + _PathReturn = str +else: + _Path = Text + _AnyStr = TypeVar("_AnyStr", str, unicode) + _AnyPath = TypeVar("_AnyPath", str, unicode) + _PathReturn = Type[None] + +if sys.version_info >= (3,): + class Error(OSError): ... + class SameFileError(Error): ... + class SpecialFileError(OSError): ... + class ExecError(OSError): ... + class ReadError(OSError): ... + class RegistryError(Exception): ... +else: + class Error(EnvironmentError): ... + class SpecialFileError(EnvironmentError): ... + class ExecError(EnvironmentError): ... + +_S_co = TypeVar("_S_co", covariant=True) +_S_contra = TypeVar("_S_contra", contravariant=True) + +class _Reader(Protocol[_S_co]): + def read(self, length: int) -> _S_co: ... + +class _Writer(Protocol[_S_contra]): + def write(self, data: _S_contra) -> Any: ... + +def copyfileobj(fsrc: _Reader[AnyStr], fdst: _Writer[AnyStr], + length: int = ...) -> None: ... + +if sys.version_info >= (3,): + def copyfile(src: _Path, dst: _AnyPath, *, + follow_symlinks: bool = ...) -> _AnyPath: ... + def copymode(src: _Path, dst: _Path, *, + follow_symlinks: bool = ...) -> None: ... + def copystat(src: _Path, dst: _Path, *, + follow_symlinks: bool = ...) -> None: ... + def copy(src: _Path, dst: _Path, *, + follow_symlinks: bool = ...) -> _PathReturn: ... + def copy2(src: _Path, dst: _Path, *, + follow_symlinks: bool = ...) -> _PathReturn: ... +else: + def copyfile(src: _Path, dst: _Path) -> None: ... + def copymode(src: _Path, dst: _Path) -> None: ... + def copystat(src: _Path, dst: _Path) -> None: ... + def copy(src: _Path, dst: _Path) -> _PathReturn: ... + def copy2(src: _Path, dst: _Path) -> _PathReturn: ... + +def ignore_patterns(*patterns: _Path) -> Callable[[Any, List[_AnyStr]], Set[_AnyStr]]: ... + +if sys.version_info >= (3,): + _IgnoreFn = Union[None, Callable[[str, List[str]], Iterable[str]], Callable[[_Path, List[str]], Iterable[str]]] + def copytree(src: _Path, dst: _Path, symlinks: bool = ..., + ignore: _IgnoreFn = ..., + copy_function: Callable[[str, str], None] = ..., + ignore_dangling_symlinks: bool = ...) -> _PathReturn: ... +else: + _IgnoreFn = Union[None, Callable[[AnyStr, List[AnyStr]], Iterable[AnyStr]]] + def copytree(src: AnyStr, dst: AnyStr, symlinks: bool = ..., + ignore: _IgnoreFn = ...) -> _PathReturn: ... + +if sys.version_info >= (3,): + @overload + def rmtree(path: bytes, ignore_errors: bool = ..., + onerror: Optional[Callable[[Any, str, Any], Any]] = ...) -> None: ... + @overload + def rmtree(path: _AnyPath, ignore_errors: bool = ..., + onerror: Optional[Callable[[Any, _AnyPath, Any], Any]] = ...) -> None: ... +else: + def rmtree(path: _AnyPath, ignore_errors: bool = ..., + onerror: Optional[Callable[[Any, _AnyPath, Any], Any]] = ...) -> None: ... + +if sys.version_info >= (3, 5): + _CopyFn = Union[Callable[[str, str], None], Callable[[_Path, _Path], None]] + def move(src: _Path, dst: _Path, + copy_function: _CopyFn = ...) -> _PathReturn: ... +else: + def move(src: _Path, dst: _Path) -> _PathReturn: ... + +if sys.version_info >= (3,): + _ntuple_diskusage = NamedTuple('usage', [('total', int), + ('used', int), + ('free', int)]) + def disk_usage(path: _Path) -> _ntuple_diskusage: ... + def chown(path: _Path, user: Optional[str] = ..., + group: Optional[str] = ...) -> None: ... + def which(cmd: _Path, mode: int = ..., + path: Optional[_Path] = ...) -> Optional[str]: ... + +def make_archive(base_name: _AnyStr, format: str, root_dir: Optional[_Path] = ..., + base_dir: Optional[_Path] = ..., verbose: bool = ..., + dry_run: bool = ..., owner: Optional[str] = ..., group: Optional[str] = ..., + logger: Optional[Any] = ...) -> _AnyStr: ... +def get_archive_formats() -> List[Tuple[str, str]]: ... + +def register_archive_format(name: str, function: Callable[..., Any], + extra_args: Optional[Sequence[Union[Tuple[str, Any], List[Any]]]] = ..., + description: str = ...) -> None: ... +def unregister_archive_format(name: str) -> None: ... + +if sys.version_info >= (3,): + # Should be _Path once http://bugs.python.org/issue30218 is fixed + def unpack_archive(filename: str, extract_dir: Optional[_Path] = ..., + format: Optional[str] = ...) -> None: ... + def register_unpack_format(name: str, extensions: List[str], function: Any, + extra_args: Sequence[Tuple[str, Any]] = ..., + description: str = ...) -> None: ... + def unregister_unpack_format(name: str) -> None: ... + def get_unpack_formats() -> List[Tuple[str, List[str], str]]: ... + + def get_terminal_size(fallback: Tuple[int, int] = ...) -> os.terminal_size: ... diff --git a/client/typeshed-fallback/stdlib/2and3/site.pyi b/client/typeshed-fallback/stdlib/2and3/site.pyi new file mode 100644 index 000000000..411677ae2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/site.pyi @@ -0,0 +1,17 @@ +# Stubs for site + +from typing import List, Iterable, Optional +import sys + +PREFIXES = ... # type: List[str] +ENABLE_USER_SITE = ... # type: Optional[bool] +USER_SITE = ... # type: Optional[str] +USER_BASE = ... # type: Optional[str] + +if sys.version_info < (3,): + def main() -> None: ... +def addsitedir(sitedir: str, + known_paths: Optional[Iterable[str]] = ...) -> None: ... +def getsitepackages(prefixes: Optional[Iterable[str]] = ...) -> List[str]: ... +def getuserbase() -> str: ... +def getusersitepackages() -> str: ... diff --git a/client/typeshed-fallback/stdlib/2and3/smtpd.pyi b/client/typeshed-fallback/stdlib/2and3/smtpd.pyi new file mode 100644 index 000000000..923b8bc65 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/smtpd.pyi @@ -0,0 +1,87 @@ +# Stubs for smtpd (Python 2 and 3) +import sys +import socket +import asyncore +import asynchat + +from typing import Any, DefaultDict, List, Optional, Text, Tuple, Type + +_Address = Tuple[str, int] # (host, port) + + +class SMTPChannel(asynchat.async_chat): + COMMAND: int + DATA: int + + if sys.version_info >= (3, 3): + command_size_limits: DefaultDict[str, int] + + if sys.version_info >= (3,): + smtp_server: SMTPServer + conn: socket.socket + addr: Any + received_lines: List[Text] + smtp_state: int + seen_greeting: str + mailfrom: str + rcpttos: List[str] + received_data: str + fqdn: str + peer: str + + command_size_limit: int + data_size_limit: int + + if sys.version_info >= (3, 5): + enable_SMTPUTF8: bool + + if sys.version_info >= (3, 3): + @property + def max_command_size_limit(self) -> int: ... + + if sys.version_info >= (3, 5): + def __init__(self, server: SMTPServer, conn: socket.socket, addr: Any, data_size_limit: int = ..., + map: Optional[asyncore._maptype] = ..., enable_SMTPUTF8: bool = ..., decode_data: bool = ...) -> None: ... + elif sys.version_info >= (3, 4): + def __init__(self, server: SMTPServer, conn: socket.socket, addr: Any, data_size_limit: int = ..., + map: Optional[asyncore._maptype] = ...) -> None: ... + else: + def __init__(self, server: SMTPServer, conn: socket.socket, addr: Any, data_size_limit: int = ...) -> None: ... + def push(self, msg: bytes) -> None: ... + def collect_incoming_data(self, data: bytes) -> None: ... + def found_terminator(self) -> None: ... + def smtp_HELO(self, arg: str) -> None: ... + def smtp_NOOP(self, arg: str) -> None: ... + def smtp_QUIT(self, arg: str) -> None: ... + def smtp_MAIL(self, arg: str) -> None: ... + def smtp_RCPT(self, arg: str) -> None: ... + def smtp_RSET(self, arg: str) -> None: ... + def smtp_DATA(self, arg: str) -> None: ... + if sys.version_info >= (3, 3): + def smtp_EHLO(self, arg: str) -> None: ... + def smtp_HELP(self, arg: str) -> None: ... + def smtp_VRFY(self, arg: str) -> None: ... + def smtp_EXPN(self, arg: str) -> None: ... + +class SMTPServer(asyncore.dispatcher): + channel_class: Type[SMTPChannel] + + data_size_limit: int + enable_SMTPUTF8: bool + + if sys.version_info >= (3, 5): + def __init__(self, localaddr: _Address, remoteaddr: _Address, + data_size_limit: int = ..., map: Optional[asyncore._maptype] = ..., + enable_SMTPUTF8: bool = ..., decode_data: bool = ...) -> None: ... + elif sys.version_info >= (3, 4): + def __init__(self, localaddr: _Address, remoteaddr: _Address, + data_size_limit: int = ..., map: Optional[asyncore._maptype] = ...) -> None: ... + else: + def __init__(self, localaddr: _Address, remoteaddr: _Address, + data_size_limit: int = ...) -> None: ... + def handle_accepted(self, conn: socket.socket, addr: Any) -> None: ... + def process_message(self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: str, **kwargs: Any) -> Optional[str]: ... + +class DebuggingServer(SMTPServer): ... +class PureProxy(SMTPServer): ... +class MailmanProxy(PureProxy): ... diff --git a/client/typeshed-fallback/stdlib/2and3/sndhdr.pyi b/client/typeshed-fallback/stdlib/2and3/sndhdr.pyi new file mode 100644 index 000000000..aecd70b46 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/sndhdr.pyi @@ -0,0 +1,25 @@ +# Stubs for sndhdr (Python 2 and 3) + +import os +import sys +from typing import Any, NamedTuple, Optional, Tuple, Union + +if sys.version_info >= (3, 5): + SndHeaders = NamedTuple('SndHeaders', [ + ('filetype', str), + ('framerate', int), + ('nchannels', int), + ('nframes', int), + ('sampwidth', Union[int, str]), + ]) + _SndHeaders = SndHeaders +else: + _SndHeaders = Tuple[str, int, int, int, Union[int, str]] + +if sys.version_info >= (3, 6): + _Path = Union[str, bytes, os.PathLike[Any]] +else: + _Path = Union[str, bytes] + +def what(filename: _Path) -> Optional[_SndHeaders]: ... +def whathdr(filename: _Path) -> Optional[_SndHeaders]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/socket.pyi b/client/typeshed-fallback/stdlib/2and3/socket.pyi new file mode 100644 index 000000000..63439fb25 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/socket.pyi @@ -0,0 +1,624 @@ +# Stubs for socket +# Ron Murawski + +# based on: http://docs.python.org/3.2/library/socket.html +# see: http://hg.python.org/cpython/file/3d0686d90f55/Lib/socket.py +# see: http://nullege.com/codes/search/socket +# adapted for Python 2.7 by Michal Pokorny +import sys +from typing import Any, Iterable, Tuple, List, Optional, Union, overload, TypeVar, Text + +_WriteBuffer = Union[bytearray, memoryview] + +# ----- variables and constants ----- + +AF_UNIX: AddressFamily +AF_INET: AddressFamily +AF_INET6: AddressFamily +SOCK_STREAM: SocketKind +SOCK_DGRAM: SocketKind +SOCK_RAW: SocketKind +SOCK_RDM: SocketKind +SOCK_SEQPACKET: SocketKind +SOCK_CLOEXEC: SocketKind +SOCK_NONBLOCK: SocketKind +SOMAXCONN: int +has_ipv6: bool +_GLOBAL_DEFAULT_TIMEOUT: Any +SocketType: Any +SocketIO: Any + +# These are flags that may exist on Python 3.6. Many don't exist on all platforms. +AF_AAL5: AddressFamily +AF_APPLETALK: AddressFamily +AF_ASH: AddressFamily +AF_ATMPVC: AddressFamily +AF_ATMSVC: AddressFamily +AF_AX25: AddressFamily +AF_BLUETOOTH: AddressFamily +AF_BRIDGE: AddressFamily +AF_CAN: AddressFamily +AF_DECnet: AddressFamily +AF_ECONET: AddressFamily +AF_IPX: AddressFamily +AF_IRDA: AddressFamily +AF_KEY: AddressFamily +AF_LLC: AddressFamily +AF_NETBEUI: AddressFamily +AF_NETLINK: AddressFamily +AF_NETROM: AddressFamily +AF_PACKET: AddressFamily +AF_PPPOX: AddressFamily +AF_RDS: AddressFamily +AF_ROSE: AddressFamily +AF_ROUTE: AddressFamily +AF_SECURITY: AddressFamily +AF_SNA: AddressFamily +AF_SYSTEM: AddressFamily +AF_TIPC: AddressFamily +AF_UNSPEC: AddressFamily +AF_WANPIPE: AddressFamily +AF_X25: AddressFamily +AI_ADDRCONFIG: AddressInfo +AI_ALL: AddressInfo +AI_CANONNAME: AddressInfo +AI_DEFAULT: AddressInfo +AI_MASK: AddressInfo +AI_NUMERICHOST: AddressInfo +AI_NUMERICSERV: AddressInfo +AI_PASSIVE: AddressInfo +AI_V4MAPPED: AddressInfo +AI_V4MAPPED_CFG: AddressInfo +BDADDR_ANY: str +BDADDR_LOCAL: str +BTPROTO_HCI: int +BTPROTO_L2CAP: int +BTPROTO_RFCOMM: int +BTPROTO_SCO: int +CAN_EFF_FLAG: int +CAN_EFF_MASK: int +CAN_ERR_FLAG: int +CAN_ERR_MASK: int +CAN_RAW: int +CAN_RAW_ERR_FILTER: int +CAN_RAW_FILTER: int +CAN_RAW_LOOPBACK: int +CAN_RAW_RECV_OWN_MSGS: int +CAN_RTR_FLAG: int +CAN_SFF_MASK: int +CAPI: int +EAGAIN: int +EAI_ADDRFAMILY: int +EAI_AGAIN: int +EAI_BADFLAGS: int +EAI_BADHINTS: int +EAI_FAIL: int +EAI_FAMILY: int +EAI_MAX: int +EAI_MEMORY: int +EAI_NODATA: int +EAI_NONAME: int +EAI_OVERFLOW: int +EAI_PROTOCOL: int +EAI_SERVICE: int +EAI_SOCKTYPE: int +EAI_SYSTEM: int +EBADF: int +EINTR: int +EWOULDBLOCK: int +HCI_DATA_DIR: int +HCI_FILTER: int +HCI_TIME_STAMP: int +INADDR_ALLHOSTS_GROUP: int +INADDR_ANY: int +INADDR_BROADCAST: int +INADDR_LOOPBACK: int +INADDR_MAX_LOCAL_GROUP: int +INADDR_NONE: int +INADDR_UNSPEC_GROUP: int +IPPORT_RESERVED: int +IPPORT_USERRESERVED: int +IPPROTO_AH: int +IPPROTO_BIP: int +IPPROTO_DSTOPTS: int +IPPROTO_EGP: int +IPPROTO_EON: int +IPPROTO_ESP: int +IPPROTO_FRAGMENT: int +IPPROTO_GGP: int +IPPROTO_GRE: int +IPPROTO_HELLO: int +IPPROTO_HOPOPTS: int +IPPROTO_ICMP: int +IPPROTO_ICMPV6: int +IPPROTO_IDP: int +IPPROTO_IGMP: int +IPPROTO_IP: int +IPPROTO_IPCOMP: int +IPPROTO_IPIP: int +IPPROTO_IPV4: int +IPPROTO_IPV6: int +IPPROTO_MAX: int +IPPROTO_MOBILE: int +IPPROTO_ND: int +IPPROTO_NONE: int +IPPROTO_PIM: int +IPPROTO_PUP: int +IPPROTO_RAW: int +IPPROTO_ROUTING: int +IPPROTO_RSVP: int +IPPROTO_SCTP: int +IPPROTO_TCP: int +IPPROTO_TP: int +IPPROTO_UDP: int +IPPROTO_VRRP: int +IPPROTO_XTP: int +IPV6_CHECKSUM: int +IPV6_DONTFRAG: int +IPV6_DSTOPTS: int +IPV6_HOPLIMIT: int +IPV6_HOPOPTS: int +IPV6_JOIN_GROUP: int +IPV6_LEAVE_GROUP: int +IPV6_MULTICAST_HOPS: int +IPV6_MULTICAST_IF: int +IPV6_MULTICAST_LOOP: int +IPV6_NEXTHOP: int +IPV6_PATHMTU: int +IPV6_PKTINFO: int +IPV6_RECVDSTOPTS: int +IPV6_RECVHOPLIMIT: int +IPV6_RECVHOPOPTS: int +IPV6_RECVPATHMTU: int +IPV6_RECVPKTINFO: int +IPV6_RECVRTHDR: int +IPV6_RECVTCLASS: int +IPV6_RTHDR: int +IPV6_RTHDR_TYPE_0: int +IPV6_RTHDRDSTOPTS: int +IPV6_TCLASS: int +IPV6_UNICAST_HOPS: int +IPV6_USE_MIN_MTU: int +IPV6_V6ONLY: int +IP_ADD_MEMBERSHIP: int +IP_DEFAULT_MULTICAST_LOOP: int +IP_DEFAULT_MULTICAST_TTL: int +IP_DROP_MEMBERSHIP: int +IP_HDRINCL: int +IP_MAX_MEMBERSHIPS: int +IP_MULTICAST_IF: int +IP_MULTICAST_LOOP: int +IP_MULTICAST_TTL: int +IP_OPTIONS: int +IP_RECVDSTADDR: int +IP_RECVOPTS: int +IP_RECVRETOPTS: int +IP_RETOPTS: int +IP_TOS: int +IP_TRANSPARENT: int +IP_TTL: int +IPX_TYPE: int +LOCAL_PEERCRED: int +MSG_BCAST: MsgFlag +MSG_BTAG: MsgFlag +MSG_CMSG_CLOEXEC: MsgFlag +MSG_CONFIRM: MsgFlag +MSG_CTRUNC: MsgFlag +MSG_DONTROUTE: MsgFlag +MSG_DONTWAIT: MsgFlag +MSG_EOF: MsgFlag +MSG_EOR: MsgFlag +MSG_ERRQUEUE: MsgFlag +MSG_ETAG: MsgFlag +MSG_FASTOPEN: MsgFlag +MSG_MCAST: MsgFlag +MSG_MORE: MsgFlag +MSG_NOSIGNAL: MsgFlag +MSG_NOTIFICATION: MsgFlag +MSG_OOB: MsgFlag +MSG_PEEK: MsgFlag +MSG_TRUNC: MsgFlag +MSG_WAITALL: MsgFlag +NETLINK_ARPD: int +NETLINK_CRYPTO: int +NETLINK_DNRTMSG: int +NETLINK_FIREWALL: int +NETLINK_IP6_FW: int +NETLINK_NFLOG: int +NETLINK_ROUTE6: int +NETLINK_ROUTE: int +NETLINK_SKIP: int +NETLINK_TAPBASE: int +NETLINK_TCPDIAG: int +NETLINK_USERSOCK: int +NETLINK_W1: int +NETLINK_XFRM: int +NI_DGRAM: int +NI_MAXHOST: int +NI_MAXSERV: int +NI_NAMEREQD: int +NI_NOFQDN: int +NI_NUMERICHOST: int +NI_NUMERICSERV: int +PACKET_BROADCAST: int +PACKET_FASTROUTE: int +PACKET_HOST: int +PACKET_LOOPBACK: int +PACKET_MULTICAST: int +PACKET_OTHERHOST: int +PACKET_OUTGOING: int +PF_CAN: int +PF_PACKET: int +PF_RDS: int +PF_SYSTEM: int +SCM_CREDENTIALS: int +SCM_CREDS: int +SCM_RIGHTS: int +SHUT_RD: int +SHUT_RDWR: int +SHUT_WR: int +SOL_ATALK: int +SOL_AX25: int +SOL_CAN_BASE: int +SOL_CAN_RAW: int +SOL_HCI: int +SOL_IP: int +SOL_IPX: int +SOL_NETROM: int +SOL_RDS: int +SOL_ROSE: int +SOL_SOCKET: int +SOL_TCP: int +SOL_TIPC: int +SOL_UDP: int +SO_ACCEPTCONN: int +SO_BINDTODEVICE: int +SO_BROADCAST: int +SO_DEBUG: int +SO_DONTROUTE: int +SO_ERROR: int +SO_EXCLUSIVEADDRUSE: int +SO_KEEPALIVE: int +SO_LINGER: int +SO_MARK: int +SO_OOBINLINE: int +SO_PASSCRED: int +SO_PEERCRED: int +SO_PRIORITY: int +SO_RCVBUF: int +SO_RCVLOWAT: int +SO_RCVTIMEO: int +SO_REUSEADDR: int +SO_REUSEPORT: int +SO_SETFIB: int +SO_SNDBUF: int +SO_SNDLOWAT: int +SO_SNDTIMEO: int +SO_TYPE: int +SO_USELOOPBACK: int +SYSPROTO_CONTROL: int +TCP_CORK: int +TCP_DEFER_ACCEPT: int +TCP_FASTOPEN: int +TCP_INFO: int +TCP_KEEPCNT: int +TCP_KEEPIDLE: int +TCP_KEEPINTVL: int +TCP_LINGER2: int +TCP_MAXSEG: int +TCP_NODELAY: int +TCP_NOTSENT_LOWAT: int +TCP_QUICKACK: int +TCP_SYNCNT: int +TCP_WINDOW_CLAMP: int +TIPC_ADDR_ID: int +TIPC_ADDR_NAME: int +TIPC_ADDR_NAMESEQ: int +TIPC_CFG_SRV: int +TIPC_CLUSTER_SCOPE: int +TIPC_CONN_TIMEOUT: int +TIPC_CRITICAL_IMPORTANCE: int +TIPC_DEST_DROPPABLE: int +TIPC_HIGH_IMPORTANCE: int +TIPC_IMPORTANCE: int +TIPC_LOW_IMPORTANCE: int +TIPC_MEDIUM_IMPORTANCE: int +TIPC_NODE_SCOPE: int +TIPC_PUBLISHED: int +TIPC_SRC_DROPPABLE: int +TIPC_SUB_CANCEL: int +TIPC_SUB_PORTS: int +TIPC_SUB_SERVICE: int +TIPC_SUBSCR_TIMEOUT: int +TIPC_TOP_SRV: int +TIPC_WAIT_FOREVER: int +TIPC_WITHDRAWN: int +TIPC_ZONE_SCOPE: int + +if sys.version_info >= (3, 3): + RDS_CANCEL_SENT_TO: int + RDS_CMSG_RDMA_ARGS: int + RDS_CMSG_RDMA_DEST: int + RDS_CMSG_RDMA_MAP: int + RDS_CMSG_RDMA_STATUS: int + RDS_CMSG_RDMA_UPDATE: int + RDS_CONG_MONITOR: int + RDS_FREE_MR: int + RDS_GET_MR: int + RDS_GET_MR_FOR_DEST: int + RDS_RDMA_DONTWAIT: int + RDS_RDMA_FENCE: int + RDS_RDMA_INVALIDATE: int + RDS_RDMA_NOTIFY_ME: int + RDS_RDMA_READWRITE: int + RDS_RDMA_SILENT: int + RDS_RDMA_USE_ONCE: int + RDS_RECVERR: int + +if sys.version_info >= (3, 4): + CAN_BCM: int + CAN_BCM_TX_SETUP: int + CAN_BCM_TX_DELETE: int + CAN_BCM_TX_READ: int + CAN_BCM_TX_SEND: int + CAN_BCM_RX_SETUP: int + CAN_BCM_RX_DELETE: int + CAN_BCM_RX_READ: int + CAN_BCM_TX_STATUS: int + CAN_BCM_TX_EXPIRED: int + CAN_BCM_RX_STATUS: int + CAN_BCM_RX_TIMEOUT: int + CAN_BCM_RX_CHANGED: int + AF_LINK: AddressFamily + +if sys.version_info >= (3, 5): + CAN_RAW_FD_FRAMES: int + +if sys.version_info >= (3, 6): + SO_DOMAIN: int + SO_PROTOCOL: int + SO_PEERSEC: int + SO_PASSSEC: int + TCP_USER_TIMEOUT: int + TCP_CONGESTION: int + AF_ALG: AddressFamily + SOL_ALG: int + ALG_SET_KEY: int + ALG_SET_IV: int + ALG_SET_OP: int + ALG_SET_AEAD_ASSOCLEN: int + ALG_SET_AEAD_AUTHSIZE: int + ALG_SET_PUBKEY: int + ALG_OP_DECRYPT: int + ALG_OP_ENCRYPT: int + ALG_OP_SIGN: int + ALG_OP_VERIFY: int + +if sys.platform == 'win32': + SIO_RCVALL: int + SIO_KEEPALIVE_VALS: int + RCVALL_IPLEVEL: int + RCVALL_MAX: int + RCVALL_OFF: int + RCVALL_ON: int + RCVALL_SOCKETLEVELONLY: int + + if sys.version_info >= (3, 6): + SIO_LOOPBACK_FAST_PATH: int + +# enum versions of above flags py 3.4+ +if sys.version_info >= (3, 4): + from enum import IntEnum + + class AddressFamily(IntEnum): + AF_UNIX = ... + AF_INET = ... + AF_INET6 = ... + AF_APPLETALK = ... + AF_ASH = ... + AF_ATMPVC = ... + AF_ATMSVC = ... + AF_AX25 = ... + AF_BLUETOOTH = ... + AF_BRIDGE = ... + AF_DECnet = ... + AF_ECONET = ... + AF_IPX = ... + AF_IRDA = ... + AF_KEY = ... + AF_LLC = ... + AF_NETBEUI = ... + AF_NETLINK = ... + AF_NETROM = ... + AF_PACKET = ... + AF_PPPOX = ... + AF_ROSE = ... + AF_ROUTE = ... + AF_SECURITY = ... + AF_SNA = ... + AF_TIPC = ... + AF_UNSPEC = ... + AF_WANPIPE = ... + AF_X25 = ... + AF_LINK = ... + + class SocketKind(IntEnum): + SOCK_STREAM = ... + SOCK_DGRAM = ... + SOCK_RAW = ... + SOCK_RDM = ... + SOCK_SEQPACKET = ... + SOCK_CLOEXEC = ... + SOCK_NONBLOCK = ... +else: + AddressFamily = int + SocketKind = int + +if sys.version_info >= (3, 6): + from enum import IntFlag + + class AddressInfo(IntFlag): + AI_ADDRCONFIG = ... + AI_ALL = ... + AI_CANONNAME = ... + AI_NUMERICHOST = ... + AI_NUMERICSERV = ... + AI_PASSIVE = ... + AI_V4MAPPED = ... + + class MsgFlag(IntFlag): + MSG_CTRUNC = ... + MSG_DONTROUTE = ... + MSG_DONTWAIT = ... + MSG_EOR = ... + MSG_OOB = ... + MSG_PEEK = ... + MSG_TRUNC = ... + MSG_WAITALL = ... +else: + AddressInfo = int + MsgFlag = int + + +# ----- exceptions ----- +class error(IOError): + ... + +class herror(error): + def __init__(self, herror: int, string: str) -> None: ... + +class gaierror(error): + def __init__(self, error: int, string: str) -> None: ... + +class timeout(error): + ... + + +# Addresses can be either tuples of varying lengths (AF_INET, AF_INET6, +# AF_NETLINK, AF_TIPC) or strings (AF_UNIX). + +_Address = Union[tuple, str] +_RetAddress = Any + +# TODO AF_PACKET and AF_BLUETOOTH address objects + +_CMSG = Tuple[int, int, bytes] +_SelfT = TypeVar('_SelfT', bound=socket) + +# ----- classes ----- +class socket: + family: int + type: int + proto: int + + if sys.version_info < (3,): + def __init__(self, family: int = ..., type: int = ..., proto: int = ...) -> None: ... + else: + def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: Optional[int] = ...) -> None: ... + + if sys.version_info >= (3, 2): + def __enter__(self: _SelfT) -> _SelfT: ... + def __exit__(self, *args: Any) -> None: ... + + # --- methods --- + def accept(self) -> Tuple[socket, _RetAddress]: ... + def bind(self, address: Union[_Address, bytes]) -> None: ... + def close(self) -> None: ... + def connect(self, address: Union[_Address, bytes]) -> None: ... + def connect_ex(self, address: Union[_Address, bytes]) -> int: ... + def detach(self) -> int: ... + def fileno(self) -> int: ... + + def getpeername(self) -> _RetAddress: ... + def getsockname(self) -> _RetAddress: ... + + @overload + def getsockopt(self, level: int, optname: int) -> int: ... + @overload + def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... + + def gettimeout(self) -> Optional[float]: ... + def ioctl(self, control: object, + option: Tuple[int, int, int]) -> None: ... + if sys.version_info < (3, 5): + def listen(self, backlog: int) -> None: ... + else: + def listen(self, backlog: int = ...) -> None: ... + # TODO the return value may be BinaryIO or TextIO, depending on mode + def makefile(self, mode: str = ..., buffering: int = ..., + encoding: str = ..., errors: str = ..., + newline: str = ...) -> Any: + ... + def recv(self, bufsize: int, flags: int = ...) -> bytes: ... + + def recvfrom(self, bufsize: int, flags: int = ...) -> Tuple[bytes, _RetAddress]: ... + def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int, + flags: int = ...) -> Tuple[int, _RetAddress]: ... + def recv_into(self, buffer: _WriteBuffer, nbytes: int, + flags: int = ...) -> int: ... + def send(self, data: bytes, flags: int = ...) -> int: ... + def sendall(self, data: bytes, flags: int = ...) -> None: + ... # return type: None on success + @overload + def sendto(self, data: bytes, address: _Address) -> int: ... + @overload + def sendto(self, data: bytes, flags: int, address: _Address) -> int: ... + def setblocking(self, flag: bool) -> None: ... + def settimeout(self, value: Optional[float]) -> None: ... + def setsockopt(self, level: int, optname: int, value: Union[int, bytes]) -> None: ... + def shutdown(self, how: int) -> None: ... + + if sys.version_info >= (3, 3): + def recvmsg(self, __bufsize: int, __ancbufsize: int = ..., + __flags: int = ...) -> Tuple[bytes, List[_CMSG], int, Any]: ... + def recvmsg_into(self, __buffers: Iterable[_WriteBuffer], __ancbufsize: int = ..., + __flags: int = ...) -> Tuple[int, List[_CMSG], int, Any]: ... + def sendmsg(self, __buffers: Iterable[bytes], __ancdata: Iterable[_CMSG] = ..., + __flags: int = ..., __address: _Address = ...) -> int: ... + + +# ----- functions ----- +def create_connection(address: Tuple[Optional[str], int], + timeout: Optional[float] = ..., + source_address: Tuple[Union[bytearray, bytes, Text], int] = ...) -> socket: ... + +# the 5th tuple item is an address +# TODO the "Tuple[Any, ...]" should be "Union[Tuple[str, int], Tuple[str, int, int, int]]" but that triggers +# https://github.com/python/mypy/issues/2509 +def getaddrinfo( + host: Optional[Union[bytearray, bytes, Text]], port: Union[str, int, None], family: int = ..., + socktype: int = ..., proto: int = ..., + flags: int = ...) -> List[Tuple[int, int, int, str, Tuple[Any, ...]]]: + ... + +def getfqdn(name: str = ...) -> str: ... +def gethostbyname(hostname: str) -> str: ... +def gethostbyname_ex(hostname: str) -> Tuple[str, List[str], List[str]]: ... +def gethostname() -> str: ... +def gethostbyaddr(ip_address: str) -> Tuple[str, List[str], List[str]]: ... +def getnameinfo(sockaddr: tuple, flags: int) -> Tuple[str, int]: ... +def getprotobyname(protocolname: str) -> int: ... +def getservbyname(servicename: str, protocolname: str = ...) -> int: ... +def getservbyport(port: int, protocolname: str = ...) -> str: ... +def socketpair(family: int = ..., + type: int = ..., + proto: int = ...) -> Tuple[socket, socket]: ... +def fromfd(fd: int, family: int, type: int, proto: int = ...) -> socket: ... +def ntohl(x: int) -> int: ... # param & ret val are 32-bit ints +def ntohs(x: int) -> int: ... # param & ret val are 16-bit ints +def htonl(x: int) -> int: ... # param & ret val are 32-bit ints +def htons(x: int) -> int: ... # param & ret val are 16-bit ints +def inet_aton(ip_string: str) -> bytes: ... # ret val 4 bytes in length +def inet_ntoa(packed_ip: bytes) -> str: ... +def inet_pton(address_family: int, ip_string: str) -> bytes: ... +def inet_ntop(address_family: int, packed_ip: bytes) -> str: ... +def getdefaulttimeout() -> Optional[float]: ... +def setdefaulttimeout(timeout: Optional[float]) -> None: ... + +if sys.version_info >= (3, 3): + def CMSG_LEN(length: int) -> int: ... + def CMSG_SPACE(length: int) -> int: ... + def sethostname(name: str) -> None: ... + def if_nameindex() -> List[Tuple[int, str]]: ... + def if_nametoindex(name: str) -> int: ... + def if_indextoname(index: int) -> str: ... diff --git a/client/typeshed-fallback/stdlib/2and3/sqlite3/__init__.pyi b/client/typeshed-fallback/stdlib/2and3/sqlite3/__init__.pyi new file mode 100644 index 000000000..d5d20d67b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/sqlite3/__init__.pyi @@ -0,0 +1 @@ +from sqlite3.dbapi2 import * # noqa: F403 diff --git a/client/typeshed-fallback/stdlib/2and3/sqlite3/dbapi2.pyi b/client/typeshed-fallback/stdlib/2and3/sqlite3/dbapi2.pyi new file mode 100644 index 000000000..71bd15568 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/sqlite3/dbapi2.pyi @@ -0,0 +1,289 @@ +# Filip Hron +# based heavily on Andrey Vlasovskikh's python-skeletons https://github.com/JetBrains/python-skeletons/blob/master/sqlite3.py + +import os +import sys +from typing import Any, Callable, Iterable, Iterator, List, Optional, Text, Tuple, Type, TypeVar, Union +from datetime import date, time, datetime + +_T = TypeVar('_T') + +paramstyle: str +threadsafety: int +apilevel: str +Date = date +Time = time +Timestamp = datetime + +def DateFromTicks(ticks): ... +def TimeFromTicks(ticks): ... +def TimestampFromTicks(ticks): ... + +version_info: str +sqlite_version_info: Tuple[int, int, int] +if sys.version_info >= (3,): + Binary = memoryview +else: + Binary = buffer + +def register_adapters_and_converters(): ... + +# The remaining definitions are imported from _sqlite3. + +PARSE_COLNAMES = ... # type: int +PARSE_DECLTYPES = ... # type: int +SQLITE_ALTER_TABLE = ... # type: int +SQLITE_ANALYZE = ... # type: int +SQLITE_ATTACH = ... # type: int +SQLITE_CREATE_INDEX = ... # type: int +SQLITE_CREATE_TABLE = ... # type: int +SQLITE_CREATE_TEMP_INDEX = ... # type: int +SQLITE_CREATE_TEMP_TABLE = ... # type: int +SQLITE_CREATE_TEMP_TRIGGER = ... # type: int +SQLITE_CREATE_TEMP_VIEW = ... # type: int +SQLITE_CREATE_TRIGGER = ... # type: int +SQLITE_CREATE_VIEW = ... # type: int +SQLITE_DELETE = ... # type: int +SQLITE_DENY = ... # type: int +SQLITE_DETACH = ... # type: int +SQLITE_DROP_INDEX = ... # type: int +SQLITE_DROP_TABLE = ... # type: int +SQLITE_DROP_TEMP_INDEX = ... # type: int +SQLITE_DROP_TEMP_TABLE = ... # type: int +SQLITE_DROP_TEMP_TRIGGER = ... # type: int +SQLITE_DROP_TEMP_VIEW = ... # type: int +SQLITE_DROP_TRIGGER = ... # type: int +SQLITE_DROP_VIEW = ... # type: int +SQLITE_IGNORE = ... # type: int +SQLITE_INSERT = ... # type: int +SQLITE_OK = ... # type: int +SQLITE_PRAGMA = ... # type: int +SQLITE_READ = ... # type: int +SQLITE_REINDEX = ... # type: int +SQLITE_SELECT = ... # type: int +SQLITE_TRANSACTION = ... # type: int +SQLITE_UPDATE = ... # type: int +adapters = ... # type: Any +converters = ... # type: Any +sqlite_version = ... # type: str +version = ... # type: str + +# TODO: adapt needs to get probed +def adapt(obj, protocol, alternate): ... +def complete_statement(sql: str) -> bool: ... +if sys.version_info >= (3, 7): + def connect(database: Union[bytes, Text, os.PathLike[Text]], + timeout: float = ..., + detect_types: int = ..., + isolation_level: Optional[str] = ..., + check_same_thread: bool = ..., + factory: Optional[Type[Connection]] = ..., + cached_statements: int = ..., + uri: bool = ...) -> Connection: ... +elif sys.version_info >= (3, 4): + def connect(database: Union[bytes, Text], + timeout: float = ..., + detect_types: int = ..., + isolation_level: Optional[str] = ..., + check_same_thread: bool = ..., + factory: Optional[Type[Connection]] = ..., + cached_statements: int = ..., + uri: bool = ...) -> Connection: ... +else: + def connect(database: Union[bytes, Text], + timeout: float = ..., + detect_types: int = ..., + isolation_level: Optional[str] = ..., + check_same_thread: bool = ..., + factory: Optional[Type[Connection]] = ..., + cached_statements: int = ...) -> Connection: ... +def enable_callback_tracebacks(flag: bool) -> None: ... +def enable_shared_cache(do_enable: int) -> None: ... +def register_adapter(type: Type[_T], callable: Callable[[_T], Union[int, float, str, bytes]]) -> None: ... +def register_converter(typename: str, callable: Callable[[bytes], Any]) -> None: ... + +class Cache(object): + def __init__(self, *args, **kwargs) -> None: ... + def display(self, *args, **kwargs) -> None: ... + def get(self, *args, **kwargs) -> None: ... + +class Connection(object): + DataError = ... # type: Any + DatabaseError = ... # type: Any + Error = ... # type: Any + IntegrityError = ... # type: Any + InterfaceError = ... # type: Any + InternalError = ... # type: Any + NotSupportedError = ... # type: Any + OperationalError = ... # type: Any + ProgrammingError = ... # type: Any + Warning = ... # type: Any + in_transaction = ... # type: Any + isolation_level = ... # type: Any + row_factory = ... # type: Any + text_factory = ... # type: Any + total_changes = ... # type: Any + def __init__(self, *args, **kwargs): ... + def close(self) -> None: ... + def commit(self) -> None: ... + def create_aggregate(self, name: str, num_params: int, aggregate_class: type) -> None: ... + def create_collation(self, name: str, callable: Any) -> None: ... + def create_function(self, name: str, num_params: int, func: Any) -> None: ... + def cursor(self, cursorClass: Optional[type] = ...) -> Cursor: ... + def execute(self, sql: str, parameters: Iterable = ...) -> Cursor: ... + # TODO: please check in executemany() if seq_of_parameters type is possible like this + def executemany(self, sql: str, seq_of_parameters: Iterable[Iterable]) -> Cursor: ... + def executescript(self, sql_script: Union[bytes, Text]) -> Cursor: ... + def interrupt(self, *args, **kwargs) -> None: ... + def iterdump(self, *args, **kwargs) -> None: ... + def rollback(self, *args, **kwargs) -> None: ... + # TODO: set_authorizer(authorzer_callback) + # see https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.set_authorizer + # returns [SQLITE_OK, SQLITE_DENY, SQLITE_IGNORE] so perhaps int + def set_authorizer(self, *args, **kwargs) -> None: ... + # set_progress_handler(handler, n) -> see https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.set_progress_handler + def set_progress_handler(self, *args, **kwargs) -> None: ... + def set_trace_callback(self, *args, **kwargs): ... + # enable_load_extension and load_extension is not available on python distributions compiled + # without sqlite3 loadable extension support. see footnotes https://docs.python.org/3/library/sqlite3.html#f1 + def enable_load_extension(self, enabled: bool) -> None: ... + def load_extension(self, path: str) -> None: ... + if sys.version_info >= (3, 7): + def backup(self, target: Connection, *, pages: int = ..., + progress: Optional[Callable[[int, int, int], object]] = ..., name: str = ..., + sleep: float = ...) -> None: ... + def __call__(self, *args, **kwargs): ... + def __enter__(self, *args, **kwargs): ... + def __exit__(self, *args, **kwargs): ... + +class Cursor(Iterator[Any]): + arraysize = ... # type: Any + connection = ... # type: Any + description = ... # type: Any + lastrowid = ... # type: Any + row_factory = ... # type: Any + rowcount = ... # type: Any + # TODO: Cursor class accepts exactly 1 argument + # required type is sqlite3.Connection (which is imported as _Connection) + # however, the name of the __init__ variable is unknown + def __init__(self, *args, **kwargs) -> None: ... + def close(self, *args, **kwargs) -> None: ... + def execute(self, sql: str, parameters: Iterable = ...) -> Cursor: ... + def executemany(self, sql: str, seq_of_parameters: Iterable[Iterable]) -> Cursor: ... + def executescript(self, sql_script: Union[bytes, Text]) -> Cursor: ... + def fetchall(self) -> List[Any]: ... + def fetchmany(self, size: Optional[int] = ...) -> List[Any]: ... + def fetchone(self) -> Any: ... + def setinputsizes(self, *args, **kwargs) -> None: ... + def setoutputsize(self, *args, **kwargs) -> None: ... + def __iter__(self) -> Cursor: ... + if sys.version_info >= (3, 0): + def __next__(self) -> Any: ... + else: + def next(self) -> Any: ... + + +class DataError(DatabaseError): ... + +class DatabaseError(Error): ... + +class Error(Exception): ... + +class IntegrityError(DatabaseError): ... + +class InterfaceError(Error): ... + +class InternalError(DatabaseError): ... + +class NotSupportedError(DatabaseError): ... + +class OperationalError(DatabaseError): ... + +class OptimizedUnicode(object): + maketrans = ... # type: Any + def __init__(self, *args, **kwargs): ... + def capitalize(self, *args, **kwargs): ... + def casefold(self, *args, **kwargs): ... + def center(self, *args, **kwargs): ... + def count(self, *args, **kwargs): ... + def encode(self, *args, **kwargs): ... + def endswith(self, *args, **kwargs): ... + def expandtabs(self, *args, **kwargs): ... + def find(self, *args, **kwargs): ... + def format(self, *args, **kwargs): ... + def format_map(self, *args, **kwargs): ... + def index(self, *args, **kwargs): ... + def isalnum(self, *args, **kwargs): ... + def isalpha(self, *args, **kwargs): ... + def isdecimal(self, *args, **kwargs): ... + def isdigit(self, *args, **kwargs): ... + def isidentifier(self, *args, **kwargs): ... + def islower(self, *args, **kwargs): ... + def isnumeric(self, *args, **kwargs): ... + def isprintable(self, *args, **kwargs): ... + def isspace(self, *args, **kwargs): ... + def istitle(self, *args, **kwargs): ... + def isupper(self, *args, **kwargs): ... + def join(self, *args, **kwargs): ... + def ljust(self, *args, **kwargs): ... + def lower(self, *args, **kwargs): ... + def lstrip(self, *args, **kwargs): ... + def partition(self, *args, **kwargs): ... + def replace(self, *args, **kwargs): ... + def rfind(self, *args, **kwargs): ... + def rindex(self, *args, **kwargs): ... + def rjust(self, *args, **kwargs): ... + def rpartition(self, *args, **kwargs): ... + def rsplit(self, *args, **kwargs): ... + def rstrip(self, *args, **kwargs): ... + def split(self, *args, **kwargs): ... + def splitlines(self, *args, **kwargs): ... + def startswith(self, *args, **kwargs): ... + def strip(self, *args, **kwargs): ... + def swapcase(self, *args, **kwargs): ... + def title(self, *args, **kwargs): ... + def translate(self, *args, **kwargs): ... + def upper(self, *args, **kwargs): ... + def zfill(self, *args, **kwargs): ... + def __add__(self, other): ... + def __contains__(self, *args, **kwargs): ... + def __eq__(self, other): ... + def __format__(self, *args, **kwargs): ... + def __ge__(self, other): ... + def __getitem__(self, index): ... + def __getnewargs__(self, *args, **kwargs): ... + def __gt__(self, other): ... + def __hash__(self): ... + def __iter__(self): ... + def __le__(self, other): ... + def __len__(self, *args, **kwargs): ... + def __lt__(self, other): ... + def __mod__(self, other): ... + def __mul__(self, other): ... + def __ne__(self, other): ... + def __rmod__(self, other): ... + def __rmul__(self, other): ... + +class PrepareProtocol(object): + def __init__(self, *args, **kwargs): ... + +class ProgrammingError(DatabaseError): ... + +class Row(object): + def __init__(self, *args, **kwargs): ... + def keys(self, *args, **kwargs): ... + def __eq__(self, other): ... + def __ge__(self, other): ... + def __getitem__(self, index): ... + def __gt__(self, other): ... + def __hash__(self): ... + def __iter__(self): ... + def __le__(self, other): ... + def __len__(self, *args, **kwargs): ... + def __lt__(self, other): ... + def __ne__(self, other): ... + +class Statement(object): + def __init__(self, *args, **kwargs): ... + +class Warning(Exception): ... diff --git a/client/typeshed-fallback/stdlib/2and3/sre_compile.pyi b/client/typeshed-fallback/stdlib/2and3/sre_compile.pyi new file mode 100644 index 000000000..c74bd85f3 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/sre_compile.pyi @@ -0,0 +1,18 @@ +# Source: https://hg.python.org/cpython/file/2.7/Lib/sre_compile.py +# and https://github.com/python/cpython/blob/master/Lib/sre_compile.py + +import sys +from sre_parse import SubPattern +from typing import Any, List, Pattern, Tuple, Type, TypeVar, Union + +MAXCODE = ... # type: int +if sys.version_info < (3, 0): + STRING_TYPES: Tuple[Type[str], Type[unicode]] + _IsStringType = int +else: + from sre_constants import _NamedIntConstant + def dis(code: List[_NamedIntConstant]) -> None: ... + _IsStringType = bool + +def isstring(obj: Any) -> _IsStringType: ... +def compile(p: Union[str, bytes, SubPattern], flags: int = ...) -> Pattern: ... diff --git a/client/typeshed-fallback/stdlib/2and3/ssl.pyi b/client/typeshed-fallback/stdlib/2and3/ssl.pyi new file mode 100644 index 000000000..4b51e409f --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/ssl.pyi @@ -0,0 +1,313 @@ +# Stubs for ssl + +from typing import ( + Any, Dict, Callable, List, NamedTuple, Optional, Set, Tuple, Union, +) +import socket +import sys + +_PCTRTT = Tuple[Tuple[str, str], ...] +_PCTRTTT = Tuple[_PCTRTT, ...] +_PeerCertRetDictType = Dict[str, Union[str, _PCTRTTT, _PCTRTT]] +_PeerCertRetType = Union[_PeerCertRetDictType, bytes, None] +_EnumRetType = List[Tuple[bytes, str, Union[Set[str], bool]]] +_PasswordType = Union[Callable[[], Union[str, bytes]], str, bytes] + +if sys.version_info >= (3, 5): + _SC1ArgT = Union[SSLSocket, SSLObject] +else: + _SC1ArgT = SSLSocket +_SrvnmeCbType = Callable[[_SC1ArgT, Optional[str], SSLSocket], Optional[int]] + +class SSLError(OSError): + library: str + reason: str +class SSLZeroReturnError(SSLError): ... +class SSLWantReadError(SSLError): ... +class SSLWantWriteError(SSLError): ... +class SSLSyscallError(SSLError): ... +class SSLEOFError(SSLError): ... + +if sys.version_info >= (3, 7): + class SSLCertVerificationError(SSLError, ValueError): + verify_code: int + verify_message: str + + CertificateError = SSLCertVerificationError +else: + class CertificateError(ValueError): ... + + +def wrap_socket(sock: socket.socket, keyfile: Optional[str] = ..., + certfile: Optional[str] = ..., server_side: bool = ..., + cert_reqs: int = ..., ssl_version: int = ..., + ca_certs: Optional[str] = ..., + do_handshake_on_connect: bool = ..., + suppress_ragged_eofs: bool = ..., + ciphers: Optional[str] = ...) -> SSLSocket: ... + + +if sys.version_info < (3,) or sys.version_info >= (3, 4): + def create_default_context(purpose: Any = ..., *, + cafile: Optional[str] = ..., + capath: Optional[str] = ..., + cadata: Optional[str] = ...) -> SSLContext: ... + +if sys.version_info >= (3, 4): + def _create_unverified_context(protocol: int = ..., *, + cert_reqs: int = ..., + check_hostname: bool = ..., + purpose: Any = ..., + certfile: Optional[str] = ..., + keyfile: Optional[str] = ..., + cafile: Optional[str] = ..., + capath: Optional[str] = ..., + cadata: Optional[str] = ...) -> SSLContext: ... + _create_default_https_context: Callable[..., SSLContext] + +if sys.version_info >= (3, 3): + def RAND_bytes(num: int) -> bytes: ... + def RAND_pseudo_bytes(num: int) -> Tuple[bytes, bool]: ... +def RAND_status() -> bool: ... +def RAND_egd(path: str) -> None: ... +def RAND_add(bytes: bytes, entropy: float) -> None: ... + + +def match_hostname(cert: _PeerCertRetType, hostname: str) -> None: ... +def cert_time_to_seconds(cert_time: str) -> int: ... +def get_server_certificate(addr: Tuple[str, int], ssl_version: int = ..., + ca_certs: Optional[str] = ...) -> str: ... +def DER_cert_to_PEM_cert(der_cert_bytes: bytes) -> str: ... +def PEM_cert_to_DER_cert(pem_cert_string: str) -> bytes: ... +if sys.version_info < (3,) or sys.version_info >= (3, 4): + DefaultVerifyPaths = NamedTuple('DefaultVerifyPaths', + [('cafile', str), ('capath', str), + ('openssl_cafile_env', str), + ('openssl_cafile', str), + ('openssl_capath_env', str), + ('openssl_capath', str)]) + def get_default_verify_paths() -> DefaultVerifyPaths: ... + +if sys.platform == 'win32': + if sys.version_info < (3,) or sys.version_info >= (3, 4): + def enum_certificates(store_name: str) -> _EnumRetType: ... + def enum_crls(store_name: str) -> _EnumRetType: ... + + +CERT_NONE: int +CERT_OPTIONAL: int +CERT_REQUIRED: int + +if sys.version_info < (3,) or sys.version_info >= (3, 4): + VERIFY_DEFAULT: int + VERIFY_CRL_CHECK_LEAF: int + VERIFY_CRL_CHECK_CHAIN: int + VERIFY_X509_STRICT: int + VERIFY_X509_TRUSTED_FIRST: int + +PROTOCOL_SSLv23: int +PROTOCOL_SSLv2: int +PROTOCOL_SSLv3: int +PROTOCOL_TLSv1: int +if sys.version_info < (3,) or sys.version_info >= (3, 4): + PROTOCOL_TLSv1_1: int + PROTOCOL_TLSv1_2: int +if sys.version_info >= (3, 5): + PROTOCOL_TLS: int +if sys.version_info >= (3, 6): + PROTOCOL_TLS_CLIENT: int + PROTOCOL_TLS_SERVER: int + +OP_ALL: int +OP_NO_SSLv2: int +OP_NO_SSLv3: int +OP_NO_TLSv1: int +if sys.version_info < (3,) or sys.version_info >= (3, 4): + OP_NO_TLSv1_1: int + OP_NO_TLSv1_2: int +OP_CIPHER_SERVER_PREFERENCE: int +OP_SINGLE_DH_USE: int +OP_SINGLE_ECDH_USE: int +OP_NO_COMPRESSION: int +if sys.version_info >= (3, 6): + OP_NO_TICKET: int + +if sys.version_info < (3,) or sys.version_info >= (3, 5): + HAS_ALPN: int +HAS_ECDH: bool +HAS_SNI: bool +HAS_NPN: bool +CHANNEL_BINDING_TYPES: List[str] + +OPENSSL_VERSION: str +OPENSSL_VERSION_INFO: Tuple[int, int, int, int, int] +OPENSSL_VERSION_NUMBER: int + +if sys.version_info < (3,) or sys.version_info >= (3, 4): + ALERT_DESCRIPTION_HANDSHAKE_FAILURE: int + ALERT_DESCRIPTION_INTERNAL_ERROR: int + ALERT_DESCRIPTION_ACCESS_DENIED: int + ALERT_DESCRIPTION_BAD_CERTIFICATE: int + ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE: int + ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE: int + ALERT_DESCRIPTION_BAD_RECORD_MAC: int + ALERT_DESCRIPTION_CERTIFICATE_EXPIRED: int + ALERT_DESCRIPTION_CERTIFICATE_REVOKED: int + ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: int + ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE: int + ALERT_DESCRIPTION_CLOSE_NOTIFY: int + ALERT_DESCRIPTION_DECODE_ERROR: int + ALERT_DESCRIPTION_DECOMPRESSION_FAILURE: int + ALERT_DESCRIPTION_DECRYPT_ERROR: int + ALERT_DESCRIPTION_ILLEGAL_PARAMETER: int + ALERT_DESCRIPTION_INSUFFICIENT_SECURITY: int + ALERT_DESCRIPTION_NO_RENEGOTIATION: int + ALERT_DESCRIPTION_PROTOCOL_VERSION: int + ALERT_DESCRIPTION_RECORD_OVERFLOW: int + ALERT_DESCRIPTION_UNEXPECTED_MESSAGE: int + ALERT_DESCRIPTION_UNKNOWN_CA: int + ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY: int + ALERT_DESCRIPTION_UNRECOGNIZED_NAME: int + ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: int + ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: int + ALERT_DESCRIPTION_USER_CANCELLED: int + +if sys.version_info < (3,) or sys.version_info >= (3, 4): + _PurposeType = NamedTuple('_PurposeType', [('nid', int), ('shortname', str), ('longname', str), ('oid', str)]) + class Purpose: + SERVER_AUTH: _PurposeType + CLIENT_AUTH: _PurposeType + + +class SSLSocket(socket.socket): + context: SSLContext + server_side: bool + server_hostname: Optional[str] + if sys.version_info >= (3, 6): + session: Optional[SSLSession] + session_reused: Optional[bool] + + def read(self, len: int = ..., + buffer: Optional[bytearray] = ...) -> bytes: ... + def write(self, buf: bytes) -> int: ... + def do_handshake(self) -> None: ... + def getpeercert(self, binary_form: bool = ...) -> _PeerCertRetType: ... + def cipher(self) -> Tuple[str, int, int]: ... + if sys.version_info >= (3, 5): + def shared_cipher(self) -> Optional[List[Tuple[str, int, int]]]: ... + def compression(self) -> Optional[str]: ... + def get_channel_binding(self, cb_type: str = ...) -> Optional[bytes]: ... + if sys.version_info < (3,) or sys.version_info >= (3, 5): + def selected_alpn_protocol(self) -> Optional[str]: ... + def selected_npn_protocol(self) -> Optional[str]: ... + def unwrap(self) -> socket.socket: ... + if sys.version_info < (3,) or sys.version_info >= (3, 5): + def version(self) -> Optional[str]: ... + def pending(self) -> int: ... + + +class SSLContext: + if sys.version_info < (3,) or sys.version_info >= (3, 4): + check_hostname: bool + options: int + @property + def protocol(self) -> int: ... + if sys.version_info < (3,) or sys.version_info >= (3, 4): + verify_flags: int + verify_mode: int + if sys.version_info >= (3, 5): + def __init__(self, protocol: int = ...) -> None: ... + else: + def __init__(self, protocol: int) -> None: ... + if sys.version_info < (3,) or sys.version_info >= (3, 4): + def cert_store_stats(self) -> Dict[str, int]: ... + def load_cert_chain(self, certfile: str, keyfile: Optional[str] = ..., + password: _PasswordType = ...) -> None: ... + if sys.version_info < (3,) or sys.version_info >= (3, 4): + def load_default_certs(self, purpose: _PurposeType = ...) -> None: ... + def load_verify_locations(self, cafile: Optional[str] = ..., + capath: Optional[str] = ..., + cadata: Union[str, bytes, None] = ...) -> None: ... + def get_ca_certs(self, + binary_form: bool = ...) -> Union[List[_PeerCertRetDictType], List[bytes]]: ... + else: + def load_verify_locations(self, + cafile: Optional[str] = ..., + capath: Optional[str] = ...) -> None: ... + def set_default_verify_paths(self) -> None: ... + def set_ciphers(self, ciphers: str) -> None: ... + if sys.version_info < (3,) or sys.version_info >= (3, 5): + def set_alpn_protocols(self, protocols: List[str]) -> None: ... + def set_npn_protocols(self, protocols: List[str]) -> None: ... + def set_servername_callback(self, + server_name_callback: Optional[_SrvnmeCbType]) -> None: ... + def load_dh_params(self, dhfile: str) -> None: ... + def set_ecdh_curve(self, curve_name: str) -> None: ... + def wrap_socket(self, sock: socket.socket, server_side: bool = ..., + do_handshake_on_connect: bool = ..., + suppress_ragged_eofs: bool = ..., + server_hostname: Optional[str] = ...) -> SSLSocket: ... + if sys.version_info >= (3, 5): + def wrap_bio(self, incoming: MemoryBIO, outgoing: MemoryBIO, + server_side: bool = ..., + server_hostname: Optional[str] = ...) -> SSLObject: ... + def session_stats(self) -> Dict[str, int]: ... + + +if sys.version_info >= (3, 5): + class SSLObject: + context: SSLContext + server_side: bool + server_hostname: Optional[str] + if sys.version_info >= (3, 6): + session: Optional[SSLSession] + session_reused: bool + def read(self, len: int = ..., + buffer: Optional[bytearray] = ...) -> bytes: ... + def write(self, buf: bytes) -> int: ... + def getpeercert(self, binary_form: bool = ...) -> _PeerCertRetType: ... + def selected_npn_protocol(self) -> Optional[str]: ... + def cipher(self) -> Tuple[str, int, int]: ... + def shared_cipher(self) -> Optional[List[Tuple[str, int, int]]]: ... + def compression(self) -> Optional[str]: ... + def pending(self) -> int: ... + def do_handshake(self) -> None: ... + def unwrap(self) -> None: ... + def get_channel_binding(self, cb_type: str = ...) -> Optional[bytes]: ... + + class MemoryBIO: + pending: int + eof: bool + def read(self, n: int = ...) -> bytes: ... + def write(self, buf: bytes) -> int: ... + def write_eof(self) -> None: ... + +if sys.version_info >= (3, 6): + class SSLSession: + id: bytes + time: int + timeout: int + ticket_lifetime_hint: int + has_ticket: bool + + +# TODO below documented in cpython but not in docs.python.org +# taken from python 3.4 +SSL_ERROR_EOF: int +SSL_ERROR_INVALID_ERROR_CODE: int +SSL_ERROR_SSL: int +SSL_ERROR_SYSCALL: int +SSL_ERROR_WANT_CONNECT: int +SSL_ERROR_WANT_READ: int +SSL_ERROR_WANT_WRITE: int +SSL_ERROR_WANT_X509_LOOKUP: int +SSL_ERROR_ZERO_RETURN: int + +def get_protocol_name(protocol_code: int) -> str: ... + +AF_INET: int +PEM_FOOTER: str +PEM_HEADER: str +SOCK_STREAM: int +SOL_SOCKET: int +SO_TYPE: int diff --git a/client/typeshed-fallback/stdlib/2and3/stringprep.pyi b/client/typeshed-fallback/stdlib/2and3/stringprep.pyi new file mode 100644 index 000000000..e3b7e9dc2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/stringprep.pyi @@ -0,0 +1,23 @@ +# Stubs for stringprep (Python 2 and 3) + +from typing import Text + +def in_table_a1(code: Text) -> bool: ... +def in_table_b1(code: Text) -> bool: ... +def map_table_b3(code: Text) -> Text: ... +def map_table_b2(a: Text) -> Text: ... +def in_table_c11(code: Text) -> bool: ... +def in_table_c12(code: Text) -> bool: ... +def in_table_c11_c12(code: Text) -> bool: ... +def in_table_c21(code: Text) -> bool: ... +def in_table_c22(code: Text) -> bool: ... +def in_table_c21_c22(code: Text) -> bool: ... +def in_table_c3(code: Text) -> bool: ... +def in_table_c4(code: Text) -> bool: ... +def in_table_c5(code: Text) -> bool: ... +def in_table_c6(code: Text) -> bool: ... +def in_table_c7(code: Text) -> bool: ... +def in_table_c8(code: Text) -> bool: ... +def in_table_c9(code: Text) -> bool: ... +def in_table_d1(code: Text) -> bool: ... +def in_table_d2(code: Text) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/2and3/struct.pyi b/client/typeshed-fallback/stdlib/2and3/struct.pyi new file mode 100644 index 000000000..c3e616d20 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/struct.pyi @@ -0,0 +1,43 @@ +# Stubs for struct + +# Based on http://docs.python.org/3.2/library/struct.html +# Based on http://docs.python.org/2/library/struct.html + +import sys +from typing import Any, Tuple, Text, Union, Iterator +from array import array + +class error(Exception): ... + +_FmtType = Union[bytes, Text] +if sys.version_info >= (3,): + _BufferType = Union[array[int], bytes, bytearray, memoryview] + _WriteBufferType = Union[array, bytearray, memoryview] +else: + _BufferType = Union[array[int], bytes, bytearray, buffer, memoryview] + _WriteBufferType = Union[array[Any], bytearray, buffer, memoryview] + +def pack(fmt: _FmtType, *v: Any) -> bytes: ... +def pack_into(fmt: _FmtType, buffer: _WriteBufferType, offset: int, *v: Any) -> None: ... +def unpack(fmt: _FmtType, buffer: _BufferType) -> Tuple[Any, ...]: ... +def unpack_from(fmt: _FmtType, buffer: _BufferType, offset: int = ...) -> Tuple[Any, ...]: ... +if sys.version_info >= (3, 4): + def iter_unpack(fmt: _FmtType, buffer: _BufferType) -> Iterator[Tuple[Any, ...]]: ... + +def calcsize(fmt: _FmtType) -> int: ... + +class Struct: + if sys.version_info >= (3, 7): + format: str + else: + format: bytes + size = ... # type: int + + def __init__(self, format: _FmtType) -> None: ... + + def pack(self, *v: Any) -> bytes: ... + def pack_into(self, buffer: _WriteBufferType, offset: int, *v: Any) -> None: ... + def unpack(self, buffer: _BufferType) -> Tuple[Any, ...]: ... + def unpack_from(self, buffer: _BufferType, offset: int = ...) -> Tuple[Any, ...]: ... + if sys.version_info >= (3, 4): + def iter_unpack(self, buffer: _BufferType) -> Iterator[Tuple[Any, ...]]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/sunau.pyi b/client/typeshed-fallback/stdlib/2and3/sunau.pyi new file mode 100644 index 000000000..829fbe6db --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/sunau.pyi @@ -0,0 +1,87 @@ +# Stubs for sunau (Python 2 and 3) + +import sys +from typing import Any, NamedTuple, NoReturn, Optional, Text, IO, Union, Tuple + +_File = Union[Text, IO[bytes]] + +class Error(Exception): ... + +AUDIO_FILE_MAGIC = ... # type: int +AUDIO_FILE_ENCODING_MULAW_8 = ... # type: int +AUDIO_FILE_ENCODING_LINEAR_8 = ... # type: int +AUDIO_FILE_ENCODING_LINEAR_16 = ... # type: int +AUDIO_FILE_ENCODING_LINEAR_24 = ... # type: int +AUDIO_FILE_ENCODING_LINEAR_32 = ... # type: int +AUDIO_FILE_ENCODING_FLOAT = ... # type: int +AUDIO_FILE_ENCODING_DOUBLE = ... # type: int +AUDIO_FILE_ENCODING_ADPCM_G721 = ... # type: int +AUDIO_FILE_ENCODING_ADPCM_G722 = ... # type: int +AUDIO_FILE_ENCODING_ADPCM_G723_3 = ... # type: int +AUDIO_FILE_ENCODING_ADPCM_G723_5 = ... # type: int +AUDIO_FILE_ENCODING_ALAW_8 = ... # type: int +AUDIO_UNKNOWN_SIZE = ... # type: int + +if sys.version_info < (3, 0): + _sunau_params = Tuple[int, int, int, int, str, str] +else: + _sunau_params = NamedTuple('_sunau_params', [ + ('nchannels', int), + ('sampwidth', int), + ('framerate', int), + ('nframes', int), + ('comptype', str), + ('compname', str), + ]) + +class Au_read: + def __init__(self, f: _File) -> None: ... + if sys.version_info >= (3, 3): + def __enter__(self) -> Au_read: ... + def __exit__(self, *args: Any) -> None: ... + def getfp(self) -> Optional[IO[bytes]]: ... + def rewind(self) -> None: ... + def close(self) -> None: ... + def tell(self) -> int: ... + def getnchannels(self) -> int: ... + def getnframes(self) -> int: ... + def getsampwidth(self) -> int: ... + def getframerate(self) -> int: ... + def getcomptype(self) -> str: ... + def getcompname(self) -> str: ... + def getparams(self) -> _sunau_params: ... + def getmarkers(self) -> None: ... + def getmark(self, id: Any) -> NoReturn: ... + def setpos(self, pos: int) -> None: ... + def readframes(self, nframes: int) -> Optional[bytes]: ... + +class Au_write: + def __init__(self, f: _File) -> None: ... + if sys.version_info >= (3, 3): + def __enter__(self) -> Au_write: ... + def __exit__(self, *args: Any) -> None: ... + def setnchannels(self, nchannels: int) -> None: ... + def getnchannels(self) -> int: ... + def setsampwidth(self, sampwidth: int) -> None: ... + def getsampwidth(self) -> int: ... + def setframerate(self, framerate: float) -> None: ... + def getframerate(self) -> int: ... + def setnframes(self, nframes: int) -> None: ... + def getnframes(self) -> int: ... + def setcomptype(self, comptype: str, compname: str) -> None: ... + def getcomptype(self) -> str: ... + def getcompname(self) -> str: ... + def setparams(self, params: _sunau_params) -> None: ... + def getparams(self) -> _sunau_params: ... + def setmark(self, id: Any, pos: Any, name: Any) -> NoReturn: ... + def getmark(self, id: Any) -> NoReturn: ... + def getmarkers(self) -> None: ... + def tell(self) -> int: ... + # should be any bytes-like object after 3.4, but we don't have a type for that + def writeframesraw(self, data: bytes) -> None: ... + def writeframes(self, data: bytes) -> None: ... + def close(self) -> None: ... + +# Returns a Au_read if mode is rb and Au_write if mode is wb +def open(f: _File, mode: Optional[str] = ...) -> Any: ... +openfp = open diff --git a/client/typeshed-fallback/stdlib/2and3/symtable.pyi b/client/typeshed-fallback/stdlib/2and3/symtable.pyi new file mode 100644 index 000000000..fd8b9ad79 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/symtable.pyi @@ -0,0 +1,45 @@ +import sys +from typing import List, Sequence, Tuple, Text + +def symtable(code: Text, filename: Text, compile_type: Text) -> SymbolTable: ... + +class SymbolTable(object): + def get_type(self) -> str: ... + def get_id(self) -> int: ... + def get_name(self) -> str: ... + def get_lineno(self) -> int: ... + def is_optimized(self) -> bool: ... + def is_nested(self) -> bool: ... + def has_children(self) -> bool: ... + def has_exec(self) -> bool: ... + if sys.version_info < (3, 0): + def has_import_star(self) -> bool: ... + def get_identifiers(self) -> Sequence[str]: ... + def lookup(self, name: str) -> Symbol: ... + def get_symbols(self) -> List[Symbol]: ... + def get_children(self) -> List[SymbolTable]: ... + +class Function(SymbolTable): + def get_parameters(self) -> Tuple[str, ...]: ... + def get_locals(self) -> Tuple[str, ...]: ... + def get_globals(self) -> Tuple[str, ...]: ... + def get_frees(self) -> Tuple[str, ...]: ... + +class Class(SymbolTable): + def get_methods(self) -> Tuple[str, ...]: ... + +class Symbol(object): + def get_name(self) -> str: ... + def is_referenced(self) -> bool: ... + def is_parameter(self) -> bool: ... + def is_global(self) -> bool: ... + def is_declared_global(self) -> bool: ... + def is_local(self) -> bool: ... + if sys.version_info >= (3, 6): + def is_annotated(self) -> bool: ... + def is_free(self) -> bool: ... + def is_imported(self) -> bool: ... + def is_assigned(self) -> bool: ... + def is_namespace(self) -> bool: ... + def get_namespaces(self) -> Sequence[SymbolTable]: ... + def get_namespace(self) -> SymbolTable: ... diff --git a/client/typeshed-fallback/stdlib/2and3/sysconfig.pyi b/client/typeshed-fallback/stdlib/2and3/sysconfig.pyi new file mode 100644 index 000000000..5d6c9cb19 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/sysconfig.pyi @@ -0,0 +1,19 @@ +# Stubs for sysconfig + +from typing import overload, Any, Dict, IO, List, Optional, Tuple, Union + +@overload +def get_config_vars() -> Dict[str, Any]: ... +@overload +def get_config_vars(arg: str, *args: str) -> List[Any]: ... +def get_config_var(name: str) -> Optional[str]: ... +def get_scheme_names() -> Tuple[str, ...]: ... +def get_path_names() -> Tuple[str, ...]: ... +def get_path(name: str, scheme: str = ..., vars: Optional[Dict[str, Any]] = ..., expand: bool = ...) -> Optional[str]: ... +def get_paths(scheme: str = ..., vars: Optional[Dict[str, Any]] = ..., expand: bool = ...) -> Dict[str, str]: ... +def get_python_version() -> str: ... +def get_platform() -> str: ... +def is_python_build() -> bool: ... +def parse_config_h(fp: IO[Any], vars: Optional[Dict[str, Any]]) -> Dict[str, Any]: ... +def get_config_h_filename() -> str: ... +def get_makefile_filename() -> str: ... diff --git a/client/typeshed-fallback/stdlib/2and3/syslog.pyi b/client/typeshed-fallback/stdlib/2and3/syslog.pyi new file mode 100644 index 000000000..15534e7cb --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/syslog.pyi @@ -0,0 +1,44 @@ +from typing import overload + +LOG_ALERT = ... # type: int +LOG_AUTH = ... # type: int +LOG_CONS = ... # type: int +LOG_CRIT = ... # type: int +LOG_CRON = ... # type: int +LOG_DAEMON = ... # type: int +LOG_DEBUG = ... # type: int +LOG_EMERG = ... # type: int +LOG_ERR = ... # type: int +LOG_INFO = ... # type: int +LOG_KERN = ... # type: int +LOG_LOCAL0 = ... # type: int +LOG_LOCAL1 = ... # type: int +LOG_LOCAL2 = ... # type: int +LOG_LOCAL3 = ... # type: int +LOG_LOCAL4 = ... # type: int +LOG_LOCAL5 = ... # type: int +LOG_LOCAL6 = ... # type: int +LOG_LOCAL7 = ... # type: int +LOG_LPR = ... # type: int +LOG_MAIL = ... # type: int +LOG_NDELAY = ... # type: int +LOG_NEWS = ... # type: int +LOG_NOTICE = ... # type: int +LOG_NOWAIT = ... # type: int +LOG_PERROR = ... # type: int +LOG_PID = ... # type: int +LOG_SYSLOG = ... # type: int +LOG_USER = ... # type: int +LOG_UUCP = ... # type: int +LOG_WARNING = ... # type: int + +def LOG_MASK(a: int) -> int: ... +def LOG_UPTO(a: int) -> int: ... +def closelog() -> None: ... +def openlog(ident: str = ..., logoption: int = ..., facility: int = ...) -> None: ... +def setlogmask(x: int) -> int: ... + +@overload +def syslog(priority: int, message: str) -> None: ... +@overload +def syslog(message: str) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/tabnanny.pyi b/client/typeshed-fallback/stdlib/2and3/tabnanny.pyi new file mode 100644 index 000000000..5209ef8f4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/tabnanny.pyi @@ -0,0 +1,22 @@ +# Stubs for tabnanny (Python 2 and 3) + +import os +import sys +from typing import Iterable, Tuple, Union + +if sys.version_info >= (3, 6): + _Path = Union[str, bytes, os.PathLike] +else: + _Path = Union[str, bytes] + +verbose = ... # type: int +filename_only = ... # type: int + +class NannyNag(Exception): + def __init__(self, lineno: int, msg: str, line: str) -> None: ... + def get_lineno(self) -> int: ... + def get_msg(self) -> str: ... + def get_line(self) -> str: ... + +def check(file: _Path) -> None: ... +def process_tokens(tokens: Iterable[Tuple[int, str, Tuple[int, int], Tuple[int, int], str]]) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/tarfile.pyi b/client/typeshed-fallback/stdlib/2and3/tarfile.pyi new file mode 100644 index 000000000..820aa373b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/tarfile.pyi @@ -0,0 +1,192 @@ +# Stubs for tarfile + +from typing import ( + Callable, IO, Iterable, Iterator, List, Mapping, Optional, Type, + Union, +) +import os +import sys +from types import TracebackType + + +if sys.version_info >= (3, 6): + _Path = Union[bytes, str, os.PathLike] +elif sys.version_info >= (3,): + _Path = Union[bytes, str] +else: + _Path = Union[str, unicode] + +ENCODING = ... # type: str + +USTAR_FORMAT = ... # type: int +GNU_FORMAT = ... # type: int +PAX_FORMAT = ... # type: int +DEFAULT_FORMAT = ... # type: int + +REGTYPE = ... # type: bytes +AREGTYPE = ... # type: bytes +LNKTYPE = ... # type: bytes +SYMTYPE = ... # type: bytes +DIRTYPE = ... # type: bytes +FIFOTYPE = ... # type: bytes +CONTTYPE = ... # type: bytes +CHRTYPE = ... # type: bytes +BLKTYPE = ... # type: bytes +GNUTYPE_SPARSE = ... # type: bytes + +if sys.version_info < (3,): + TAR_PLAIN = ... # type: int + TAR_GZIPPED = ... # type: int + +def open(name: Optional[_Path] = ..., mode: str = ..., + fileobj: Optional[IO[bytes]] = ..., bufsize: int = ..., + *, format: Optional[int] = ..., tarinfo: Optional[TarInfo] = ..., + dereference: Optional[bool] = ..., + ignore_zeros: Optional[bool] = ..., + encoding: Optional[str] = ..., errors: str = ..., + pax_headers: Optional[Mapping[str, str]] = ..., + debug: Optional[int] = ..., + errorlevel: Optional[int] = ..., + compresslevel: Optional[int] = ...) -> TarFile: ... + + +class TarFile(Iterable[TarInfo]): + name = ... # type: Optional[_Path] + mode = ... # type: str + fileobj = ... # type: Optional[IO[bytes]] + format = ... # type: Optional[int] + tarinfo = ... # type: Optional[TarInfo] + dereference = ... # type: Optional[bool] + ignore_zeros = ... # type: Optional[bool] + encoding = ... # type: Optional[str] + errors = ... # type: str + pax_headers = ... # type: Optional[Mapping[str, str]] + debug = ... # type: Optional[int] + errorlevel = ... # type: Optional[int] + if sys.version_info < (3,): + posix = ... # type: bool + def __init__(self, name: Optional[_Path] = ..., mode: str = ..., + fileobj: Optional[IO[bytes]] = ..., + format: Optional[int] = ..., tarinfo: Optional[TarInfo] = ..., + dereference: Optional[bool] = ..., + ignore_zeros: Optional[bool] = ..., + encoding: Optional[str] = ..., errors: str = ..., + pax_headers: Optional[Mapping[str, str]] = ..., + debug: Optional[int] = ..., + errorlevel: Optional[int] = ..., + compresslevel: Optional[int] = ...) -> None: ... + def __enter__(self) -> TarFile: ... + def __exit__(self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType]) -> bool: ... + def __iter__(self) -> Iterator[TarInfo]: ... + @classmethod + def open(cls, name: Optional[_Path] = ..., mode: str = ..., + fileobj: Optional[IO[bytes]] = ..., bufsize: int = ..., + *, format: Optional[int] = ..., tarinfo: Optional[TarInfo] = ..., + dereference: Optional[bool] = ..., + ignore_zeros: Optional[bool] = ..., + encoding: Optional[str] = ..., errors: str = ..., + pax_headers: Optional[Mapping[str, str]] = ..., + debug: Optional[int] = ..., + errorlevel: Optional[int] = ...) -> TarFile: ... + def getmember(self, name: str) -> TarInfo: ... + def getmembers(self) -> List[TarInfo]: ... + def getnames(self) -> List[str]: ... + if sys.version_info >= (3, 5): + def list(self, verbose: bool = ..., + *, members: Optional[List[TarInfo]] = ...) -> None: ... + else: + def list(self, verbose: bool = ...) -> None: ... + def next(self) -> Optional[TarInfo]: ... + if sys.version_info >= (3, 5): + def extractall(self, path: _Path = ..., + members: Optional[List[TarInfo]] = ..., + *, numeric_owner: bool = ...) -> None: ... + else: + def extractall(self, path: _Path = ..., + members: Optional[List[TarInfo]] = ...) -> None: ... + if sys.version_info >= (3, 5): + def extract(self, member: Union[str, TarInfo], path: _Path = ..., + set_attrs: bool = ..., + *, numeric_owner: bool = ...) -> None: ... + elif sys.version_info >= (3,): + def extract(self, member: Union[str, TarInfo], path: _Path = ..., + set_attrs: bool = ...) -> None: ... + else: + def extract(self, member: Union[str, TarInfo], + path: _Path = ...) -> None: ... + def extractfile(self, + member: Union[str, TarInfo]) -> Optional[IO[bytes]]: ... + if sys.version_info >= (3, 7): + def add(self, name: str, arcname: Optional[str] = ..., + recursive: bool = ..., *, + filter: Optional[Callable[[TarInfo], Optional[TarInfo]]] = ...) -> None: ... + elif sys.version_info >= (3,): + def add(self, name: str, arcname: Optional[str] = ..., + recursive: bool = ..., + exclude: Optional[Callable[[str], bool]] = ..., *, + filter: Optional[Callable[[TarInfo], Optional[TarInfo]]] = ...) -> None: ... + else: + def add(self, name: str, arcname: Optional[str] = ..., + recursive: bool = ..., + exclude: Optional[Callable[[str], bool]] = ..., + filter: Optional[Callable[[TarInfo], Optional[TarInfo]]] = ...) -> None: ... + def addfile(self, tarinfo: TarInfo, + fileobj: Optional[IO[bytes]] = ...) -> None: ... + def gettarinfo(self, name: Optional[str] = ..., + arcname: Optional[str] = ..., + fileobj: Optional[IO[bytes]] = ...) -> TarInfo: ... + def close(self) -> None: ... + + +def is_tarfile(name: str) -> bool: ... + + +if sys.version_info < (3,): + class TarFileCompat: + def __init__(self, filename: str, mode: str = ..., + compression: int = ...) -> None: ... + + +class TarError(Exception): ... +class ReadError(TarError): ... +class CompressionError(TarError): ... +class StreamError(TarError): ... +class ExtractError(TarError): ... +class HeaderError(TarError): ... + + +class TarInfo: + name = ... # type: str + size = ... # type: int + mtime = ... # type: int + mode = ... # type: int + type = ... # type: bytes + linkname = ... # type: str + uid = ... # type: int + gid = ... # type: int + uname = ... # type: str + gname = ... # type: str + pax_headers = ... # type: Mapping[str, str] + def __init__(self, name: str = ...) -> None: ... + if sys.version_info >= (3,): + @classmethod + def frombuf(cls, buf: bytes, encoding: str, errors: str) -> TarInfo: ... + else: + @classmethod + def frombuf(cls, buf: bytes) -> TarInfo: ... + @classmethod + def fromtarfile(cls, tarfile: TarFile) -> TarInfo: ... + def tobuf(self, format: Optional[int] = ..., + encoding: Optional[str] = ..., errors: str = ...) -> bytes: ... + def isfile(self) -> bool: ... + def isreg(self) -> bool: ... + def isdir(self) -> bool: ... + def issym(self) -> bool: ... + def islnk(self) -> bool: ... + def ischr(self) -> bool: ... + def isblk(self) -> bool: ... + def isfifo(self) -> bool: ... + def isdev(self) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/2and3/telnetlib.pyi b/client/typeshed-fallback/stdlib/2and3/telnetlib.pyi new file mode 100644 index 000000000..e4e5dea26 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/telnetlib.pyi @@ -0,0 +1,115 @@ +# Stubs for telnetlib (Python 2 and 3) + +import socket +import sys +from typing import Any, Callable, Match, Optional, Pattern, Sequence, Tuple, Union + +DEBUGLEVEL = ... # type: int +TELNET_PORT = ... # type: int + +IAC = ... # type: bytes +DONT = ... # type: bytes +DO = ... # type: bytes +WONT = ... # type: bytes +WILL = ... # type: bytes +theNULL = ... # type: bytes + +SE = ... # type: bytes +NOP = ... # type: bytes +DM = ... # type: bytes +BRK = ... # type: bytes +IP = ... # type: bytes +AO = ... # type: bytes +AYT = ... # type: bytes +EC = ... # type: bytes +EL = ... # type: bytes +GA = ... # type: bytes +SB = ... # type: bytes + +BINARY = ... # type: bytes +ECHO = ... # type: bytes +RCP = ... # type: bytes +SGA = ... # type: bytes +NAMS = ... # type: bytes +STATUS = ... # type: bytes +TM = ... # type: bytes +RCTE = ... # type: bytes +NAOL = ... # type: bytes +NAOP = ... # type: bytes +NAOCRD = ... # type: bytes +NAOHTS = ... # type: bytes +NAOHTD = ... # type: bytes +NAOFFD = ... # type: bytes +NAOVTS = ... # type: bytes +NAOVTD = ... # type: bytes +NAOLFD = ... # type: bytes +XASCII = ... # type: bytes +LOGOUT = ... # type: bytes +BM = ... # type: bytes +DET = ... # type: bytes +SUPDUP = ... # type: bytes +SUPDUPOUTPUT = ... # type: bytes +SNDLOC = ... # type: bytes +TTYPE = ... # type: bytes +EOR = ... # type: bytes +TUID = ... # type: bytes +OUTMRK = ... # type: bytes +TTYLOC = ... # type: bytes +VT3270REGIME = ... # type: bytes +X3PAD = ... # type: bytes +NAWS = ... # type: bytes +TSPEED = ... # type: bytes +LFLOW = ... # type: bytes +LINEMODE = ... # type: bytes +XDISPLOC = ... # type: bytes +OLD_ENVIRON = ... # type: bytes +AUTHENTICATION = ... # type: bytes +ENCRYPT = ... # type: bytes +NEW_ENVIRON = ... # type: bytes + +TN3270E = ... # type: bytes +XAUTH = ... # type: bytes +CHARSET = ... # type: bytes +RSP = ... # type: bytes +COM_PORT_OPTION = ... # type: bytes +SUPPRESS_LOCAL_ECHO = ... # type: bytes +TLS = ... # type: bytes +KERMIT = ... # type: bytes +SEND_URL = ... # type: bytes +FORWARD_X = ... # type: bytes +PRAGMA_LOGON = ... # type: bytes +SSPI_LOGON = ... # type: bytes +PRAGMA_HEARTBEAT = ... # type: bytes +EXOPL = ... # type: bytes +NOOPT = ... # type: bytes + +class Telnet: + def __init__(self, host: Optional[str] = ..., port: int = ..., + timeout: int = ...) -> None: ... + def open(self, host: str, port: int = ..., timeout: int = ...) -> None: ... + def msg(self, msg: str, *args: Any) -> None: ... + def set_debuglevel(self, debuglevel: int) -> None: ... + def close(self) -> None: ... + def get_socket(self) -> socket.socket: ... + def fileno(self) -> int: ... + def write(self, buffer: bytes) -> None: ... + def read_until(self, match: bytes, timeout: Optional[int] = ...) -> bytes: ... + def read_all(self) -> bytes: ... + def read_some(self) -> bytes: ... + def read_very_eager(self) -> bytes: ... + def read_eager(self) -> bytes: ... + def read_lazy(self) -> bytes: ... + def read_very_lazy(self) -> bytes: ... + def read_sb_data(self) -> bytes: ... + def set_option_negotiation_callback(self, callback: Optional[Callable[[socket.socket, bytes, bytes], Any]]) -> None: ... + def process_rawq(self) -> None: ... + def rawq_getchar(self) -> bytes: ... + def fill_rawq(self) -> None: ... + def sock_avail(self) -> bool: ... + def interact(self) -> None: ... + def mt_interact(self) -> None: ... + def listener(self) -> None: ... + def expect(self, list: Sequence[Union[Pattern[bytes], bytes]], timeout: Optional[int] = ...) -> Tuple[int, Optional[Match[bytes]], bytes]: ... + if sys.version_info >= (3, 6): + def __enter__(self) -> Telnet: ... + def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/termios.pyi b/client/typeshed-fallback/stdlib/2and3/termios.pyi new file mode 100644 index 000000000..2e800d4fd --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/termios.pyi @@ -0,0 +1,246 @@ +# Stubs for termios + +from typing import IO, List, Union + +_FD = Union[int, IO[str]] +_Attr = List[Union[int, List[bytes]]] + +# TODO constants not really documented +B0 = ... # type: int +B1000000 = ... # type: int +B110 = ... # type: int +B115200 = ... # type: int +B1152000 = ... # type: int +B1200 = ... # type: int +B134 = ... # type: int +B150 = ... # type: int +B1500000 = ... # type: int +B1800 = ... # type: int +B19200 = ... # type: int +B200 = ... # type: int +B2000000 = ... # type: int +B230400 = ... # type: int +B2400 = ... # type: int +B2500000 = ... # type: int +B300 = ... # type: int +B3000000 = ... # type: int +B3500000 = ... # type: int +B38400 = ... # type: int +B4000000 = ... # type: int +B460800 = ... # type: int +B4800 = ... # type: int +B50 = ... # type: int +B500000 = ... # type: int +B57600 = ... # type: int +B576000 = ... # type: int +B600 = ... # type: int +B75 = ... # type: int +B921600 = ... # type: int +B9600 = ... # type: int +BRKINT = ... # type: int +BS0 = ... # type: int +BS1 = ... # type: int +BSDLY = ... # type: int +CBAUD = ... # type: int +CBAUDEX = ... # type: int +CDSUSP = ... # type: int +CEOF = ... # type: int +CEOL = ... # type: int +CEOT = ... # type: int +CERASE = ... # type: int +CFLUSH = ... # type: int +CIBAUD = ... # type: int +CINTR = ... # type: int +CKILL = ... # type: int +CLNEXT = ... # type: int +CLOCAL = ... # type: int +CQUIT = ... # type: int +CR0 = ... # type: int +CR1 = ... # type: int +CR2 = ... # type: int +CR3 = ... # type: int +CRDLY = ... # type: int +CREAD = ... # type: int +CRPRNT = ... # type: int +CRTSCTS = ... # type: int +CS5 = ... # type: int +CS6 = ... # type: int +CS7 = ... # type: int +CS8 = ... # type: int +CSIZE = ... # type: int +CSTART = ... # type: int +CSTOP = ... # type: int +CSTOPB = ... # type: int +CSUSP = ... # type: int +CWERASE = ... # type: int +ECHO = ... # type: int +ECHOCTL = ... # type: int +ECHOE = ... # type: int +ECHOK = ... # type: int +ECHOKE = ... # type: int +ECHONL = ... # type: int +ECHOPRT = ... # type: int +EXTA = ... # type: int +EXTB = ... # type: int +FF0 = ... # type: int +FF1 = ... # type: int +FFDLY = ... # type: int +FIOASYNC = ... # type: int +FIOCLEX = ... # type: int +FIONBIO = ... # type: int +FIONCLEX = ... # type: int +FIONREAD = ... # type: int +FLUSHO = ... # type: int +HUPCL = ... # type: int +ICANON = ... # type: int +ICRNL = ... # type: int +IEXTEN = ... # type: int +IGNBRK = ... # type: int +IGNCR = ... # type: int +IGNPAR = ... # type: int +IMAXBEL = ... # type: int +INLCR = ... # type: int +INPCK = ... # type: int +IOCSIZE_MASK = ... # type: int +IOCSIZE_SHIFT = ... # type: int +ISIG = ... # type: int +ISTRIP = ... # type: int +IUCLC = ... # type: int +IXANY = ... # type: int +IXOFF = ... # type: int +IXON = ... # type: int +NCC = ... # type: int +NCCS = ... # type: int +NL0 = ... # type: int +NL1 = ... # type: int +NLDLY = ... # type: int +NOFLSH = ... # type: int +N_MOUSE = ... # type: int +N_PPP = ... # type: int +N_SLIP = ... # type: int +N_STRIP = ... # type: int +N_TTY = ... # type: int +OCRNL = ... # type: int +OFDEL = ... # type: int +OFILL = ... # type: int +OLCUC = ... # type: int +ONLCR = ... # type: int +ONLRET = ... # type: int +ONOCR = ... # type: int +OPOST = ... # type: int +PARENB = ... # type: int +PARMRK = ... # type: int +PARODD = ... # type: int +PENDIN = ... # type: int +TAB0 = ... # type: int +TAB1 = ... # type: int +TAB2 = ... # type: int +TAB3 = ... # type: int +TABDLY = ... # type: int +TCFLSH = ... # type: int +TCGETA = ... # type: int +TCGETS = ... # type: int +TCIFLUSH = ... # type: int +TCIOFF = ... # type: int +TCIOFLUSH = ... # type: int +TCION = ... # type: int +TCOFLUSH = ... # type: int +TCOOFF = ... # type: int +TCOON = ... # type: int +TCSADRAIN = ... # type: int +TCSAFLUSH = ... # type: int +TCSANOW = ... # type: int +TCSBRK = ... # type: int +TCSBRKP = ... # type: int +TCSETA = ... # type: int +TCSETAF = ... # type: int +TCSETAW = ... # type: int +TCSETS = ... # type: int +TCSETSF = ... # type: int +TCSETSW = ... # type: int +TCXONC = ... # type: int +TIOCCONS = ... # type: int +TIOCEXCL = ... # type: int +TIOCGETD = ... # type: int +TIOCGICOUNT = ... # type: int +TIOCGLCKTRMIOS = ... # type: int +TIOCGPGRP = ... # type: int +TIOCGSERIAL = ... # type: int +TIOCGSOFTCAR = ... # type: int +TIOCGWINSZ = ... # type: int +TIOCINQ = ... # type: int +TIOCLINUX = ... # type: int +TIOCMBIC = ... # type: int +TIOCMBIS = ... # type: int +TIOCMGET = ... # type: int +TIOCMIWAIT = ... # type: int +TIOCMSET = ... # type: int +TIOCM_CAR = ... # type: int +TIOCM_CD = ... # type: int +TIOCM_CTS = ... # type: int +TIOCM_DSR = ... # type: int +TIOCM_DTR = ... # type: int +TIOCM_LE = ... # type: int +TIOCM_RI = ... # type: int +TIOCM_RNG = ... # type: int +TIOCM_RTS = ... # type: int +TIOCM_SR = ... # type: int +TIOCM_ST = ... # type: int +TIOCNOTTY = ... # type: int +TIOCNXCL = ... # type: int +TIOCOUTQ = ... # type: int +TIOCPKT = ... # type: int +TIOCPKT_DATA = ... # type: int +TIOCPKT_DOSTOP = ... # type: int +TIOCPKT_FLUSHREAD = ... # type: int +TIOCPKT_FLUSHWRITE = ... # type: int +TIOCPKT_NOSTOP = ... # type: int +TIOCPKT_START = ... # type: int +TIOCPKT_STOP = ... # type: int +TIOCSCTTY = ... # type: int +TIOCSERCONFIG = ... # type: int +TIOCSERGETLSR = ... # type: int +TIOCSERGETMULTI = ... # type: int +TIOCSERGSTRUCT = ... # type: int +TIOCSERGWILD = ... # type: int +TIOCSERSETMULTI = ... # type: int +TIOCSERSWILD = ... # type: int +TIOCSER_TEMT = ... # type: int +TIOCSETD = ... # type: int +TIOCSLCKTRMIOS = ... # type: int +TIOCSPGRP = ... # type: int +TIOCSSERIAL = ... # type: int +TIOCSSOFTCAR = ... # type: int +TIOCSTI = ... # type: int +TIOCSWINSZ = ... # type: int +TOSTOP = ... # type: int +VDISCARD = ... # type: int +VEOF = ... # type: int +VEOL = ... # type: int +VEOL2 = ... # type: int +VERASE = ... # type: int +VINTR = ... # type: int +VKILL = ... # type: int +VLNEXT = ... # type: int +VMIN = ... # type: int +VQUIT = ... # type: int +VREPRINT = ... # type: int +VSTART = ... # type: int +VSTOP = ... # type: int +VSUSP = ... # type: int +VSWTC = ... # type: int +VSWTCH = ... # type: int +VT0 = ... # type: int +VT1 = ... # type: int +VTDLY = ... # type: int +VTIME = ... # type: int +VWERASE = ... # type: int +XCASE = ... # type: int +XTABS = ... # type: int + +def tcgetattr(fd: _FD) -> _Attr: ... +def tcsetattr(fd: _FD, when: int, attributes: _Attr) -> None: ... +def tcsendbreak(fd: _FD, duration: int) -> None: ... +def tcdrain(fd: _FD) -> None: ... +def tcflush(fd: _FD, queue: int) -> None: ... +def tcflow(fd: _FD, action: int) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/threading.pyi b/client/typeshed-fallback/stdlib/2and3/threading.pyi new file mode 100644 index 000000000..ffd379260 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/threading.pyi @@ -0,0 +1,187 @@ +# Stubs for threading + +from typing import ( + Any, Callable, Iterable, List, Mapping, Optional, Tuple, Type, Union, + TypeVar, +) +from types import FrameType, TracebackType +import sys + +# TODO recursive type +_TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] + +_PF = Callable[[FrameType, str, Any], None] +_T = TypeVar('_T') + + +def active_count() -> int: ... +if sys.version_info < (3,): + def activeCount() -> int: ... + +def current_thread() -> Thread: ... +def currentThread() -> Thread: ... + +if sys.version_info >= (3,): + def get_ident() -> int: ... + +def enumerate() -> List[Thread]: ... + +if sys.version_info >= (3, 4): + def main_thread() -> Thread: ... + +def settrace(func: _TF) -> None: ... +def setprofile(func: _PF) -> None: ... +def stack_size(size: int = ...) -> int: ... + +if sys.version_info >= (3,): + TIMEOUT_MAX = ... # type: float + +class ThreadError(Exception): ... + + +class local(object): + def __getattribute__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __delattr__(self, name: str) -> None: ... + + +class Thread: + name = ... # type: str + ident = ... # type: Optional[int] + daemon = ... # type: bool + if sys.version_info >= (3,): + def __init__(self, group: None = ..., + target: Optional[Callable[..., Any]] = ..., + name: Optional[str] = ..., + args: Iterable = ..., + kwargs: Mapping[str, Any] = ..., + *, daemon: Optional[bool] = ...) -> None: ... + else: + def __init__(self, group: None = ..., + target: Optional[Callable[..., Any]] = ..., + name: Optional[str] = ..., + args: Iterable = ..., + kwargs: Mapping[str, Any] = ...) -> None: ... + def start(self) -> None: ... + def run(self) -> None: ... + def join(self, timeout: Optional[float] = ...) -> None: ... + def getName(self) -> str: ... + def setName(self, name: str) -> None: ... + def is_alive(self) -> bool: ... + def isAlive(self) -> bool: ... + def isDaemon(self) -> bool: ... + def setDaemon(self, daemonic: bool) -> None: ... + + +class _DummyThread(Thread): ... + + +class Lock: + def __init__(self) -> None: ... + def __enter__(self) -> bool: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[Exception], + exc_tb: Optional[TracebackType]) -> bool: ... + if sys.version_info >= (3,): + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... + else: + def acquire(self, blocking: bool = ...) -> bool: ... + def release(self) -> None: ... + def locked(self) -> bool: ... + + +class _RLock: + def __init__(self) -> None: ... + def __enter__(self) -> bool: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[Exception], + exc_tb: Optional[TracebackType]) -> bool: ... + if sys.version_info >= (3,): + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... + else: + def acquire(self, blocking: bool = ...) -> bool: ... + def release(self) -> None: ... + + +RLock = _RLock + + +class Condition: + def __init__(self, lock: Union[Lock, _RLock, None] = ...) -> None: ... + def __enter__(self) -> bool: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[Exception], + exc_tb: Optional[TracebackType]) -> bool: ... + if sys.version_info >= (3,): + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... + else: + def acquire(self, blocking: bool = ...) -> bool: ... + def release(self) -> None: ... + def wait(self, timeout: Optional[float] = ...) -> bool: ... + if sys.version_info >= (3,): + def wait_for(self, predicate: Callable[[], _T], + timeout: Optional[float] = ...) -> _T: ... + def notify(self, n: int = ...) -> None: ... + def notify_all(self) -> None: ... + def notifyAll(self) -> None: ... + + +class Semaphore: + def __init__(self, value: int = ...) -> None: ... + def __enter__(self) -> bool: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[Exception], + exc_tb: Optional[TracebackType]) -> bool: ... + if sys.version_info >= (3,): + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... + else: + def acquire(self, blocking: bool = ...) -> bool: ... + def release(self) -> None: ... + +class BoundedSemaphore: + def __init__(self, value: int = ...) -> None: ... + def __enter__(self) -> bool: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[Exception], + exc_tb: Optional[TracebackType]) -> bool: ... + if sys.version_info >= (3,): + def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... + else: + def acquire(self, blocking: bool = ...) -> bool: ... + def release(self) -> None: ... + + +class Event: + def __init__(self) -> None: ... + def is_set(self) -> bool: ... + if sys.version_info < (3,): + def isSet(self) -> bool: ... + def set(self) -> None: ... + def clear(self) -> None: ... + def wait(self, timeout: Optional[float] = ...) -> bool: ... + + +class Timer(Thread): + if sys.version_info >= (3,): + def __init__(self, interval: float, function: Callable[..., None], + args: Optional[List[Any]] = ..., + kwargs: Optional[Mapping[str, Any]] = ...) -> None: ... + else: + def __init__(self, interval: float, function: Callable[..., None], + args: List[Any] = ..., + kwargs: Mapping[str, Any] = ...) -> None: ... + def cancel(self) -> None: ... + + +if sys.version_info >= (3,): + class Barrier: + parties = ... # type: int + n_waiting = ... # type: int + broken = ... # type: bool + def __init__(self, parties: int, action: Optional[Callable[[], None]] = ..., + timeout: Optional[float] = ...) -> None: ... + def wait(self, timeout: Optional[float] = ...) -> int: ... + def reset(self) -> None: ... + def abort(self) -> None: ... + + class BrokenBarrierError(RuntimeError): ... diff --git a/client/typeshed-fallback/stdlib/2and3/time.pyi b/client/typeshed-fallback/stdlib/2and3/time.pyi new file mode 100644 index 000000000..b04e6164b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/time.pyi @@ -0,0 +1,103 @@ +"""Stub file for the 'time' module.""" +# See https://docs.python.org/3/library/time.html + +import sys +from typing import Any, NamedTuple, Tuple, Union, Optional +if sys.version_info >= (3, 3): + from types import SimpleNamespace + +_TimeTuple = Tuple[int, int, int, int, int, int, int, int, int] + +if sys.version_info < (3, 3): + accept2dyear: bool +altzone: int +daylight: int +timezone: int +tzname: Tuple[str, str] + +if sys.version_info >= (3, 7) and sys.platform != 'win32': + CLOCK_BOOTTIME: int # Linux + CLOCK_PROF: int # FreeBSD, NetBSD, OpenBSD + CLOCK_UPTIME: int # FreeBSD, OpenBSD + +if sys.version_info >= (3, 3) and sys.platform != 'win32': + CLOCK_HIGHRES: int = ... # Solaris only + CLOCK_MONOTONIC: int = ... # Unix only + CLOCK_MONOTONIC_RAW: int = ... # Linux 2.6.28 or later + CLOCK_PROCESS_CPUTIME_ID: int = ... # Unix only + CLOCK_REALTIME: int = ... # Unix only + CLOCK_THREAD_CPUTIME_ID: int = ... # Unix only + + +if sys.version_info >= (3, 3): + class struct_time( + NamedTuple( + '_struct_time', + [('tm_year', int), ('tm_mon', int), ('tm_mday', int), + ('tm_hour', int), ('tm_min', int), ('tm_sec', int), + ('tm_wday', int), ('tm_yday', int), ('tm_isdst', int), + ('tm_zone', str), ('tm_gmtoff', int)] + ) + ): + def __init__( + self, + o: Union[ + Tuple[int, int, int, int, int, int, int, int, int], + Tuple[int, int, int, int, int, int, int, int, int, str], + Tuple[int, int, int, int, int, int, int, int, int, str, int] + ], + _arg: Any = ..., + ) -> None: ... + def __new__( + cls, + o: Union[ + Tuple[int, int, int, int, int, int, int, int, int], + Tuple[int, int, int, int, int, int, int, int, int, str], + Tuple[int, int, int, int, int, int, int, int, int, str, int] + ], + _arg: Any = ..., + ) -> struct_time: ... +else: + class struct_time( + NamedTuple( + '_struct_time', + [('tm_year', int), ('tm_mon', int), ('tm_mday', int), + ('tm_hour', int), ('tm_min', int), ('tm_sec', int), + ('tm_wday', int), ('tm_yday', int), ('tm_isdst', int)] + ) + ): + def __init__(self, o: _TimeTuple, _arg: Any = ...) -> None: ... + def __new__(cls, o: _TimeTuple, _arg: Any = ...) -> struct_time: ... + +def asctime(t: Union[_TimeTuple, struct_time] = ...) -> str: ... +def clock() -> float: ... +def ctime(secs: Optional[float] = ...) -> str: ... +def gmtime(secs: Optional[float] = ...) -> struct_time: ... +def localtime(secs: Optional[float] = ...) -> struct_time: ... +def mktime(t: Union[_TimeTuple, struct_time]) -> float: ... +def sleep(secs: float) -> None: ... +def strftime(format: str, t: Union[_TimeTuple, struct_time] = ...) -> str: ... +def strptime(string: str, format: str = ...) -> struct_time: ... +def time() -> float: ... +if sys.platform != 'win32': + def tzset() -> None: ... # Unix only + +if sys.version_info >= (3, 3): + def get_clock_info(name: str) -> SimpleNamespace: ... + def monotonic() -> float: ... + def perf_counter() -> float: ... + def process_time() -> float: ... + if sys.platform != 'win32': + def clock_getres(clk_id: int) -> float: ... # Unix only + def clock_gettime(clk_id: int) -> float: ... # Unix only + def clock_settime(clk_id: int, time: float) -> None: ... # Unix only + +if sys.version_info >= (3, 7): + def clock_gettime_ns(clock_id: int) -> int: ... + def clock_settime_ns(clock_id: int, time: int) -> int: ... + def monotonic_ns() -> int: ... + def perf_counter_ns() -> int: ... + def process_time_ns() -> int: ... + def time_ns() -> int: ... + def thread_time() -> float: ... + def thread_time_ns() -> int: ... diff --git a/client/typeshed-fallback/stdlib/2and3/timeit.pyi b/client/typeshed-fallback/stdlib/2and3/timeit.pyi new file mode 100644 index 000000000..23a2b10e0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/timeit.pyi @@ -0,0 +1,33 @@ +# Stubs for timeit (Python 2 and 3) + +import sys +from typing import Any, Callable, Dict, IO, List, Optional, Text, Tuple, Union + +_str = Union[str, Text] +_Timer = Callable[[], float] +_stmt = Union[_str, Callable[[], Any]] + +default_timer = ... # type: _Timer + +class Timer: + if sys.version_info >= (3, 5): + def __init__(self, stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., + globals: Optional[Dict[str, Any]] = ...) -> None: ... + else: + def __init__(self, stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ...) -> None: ... + def print_exc(self, file: Optional[IO[str]] = ...) -> None: ... + def timeit(self, number: int = ...) -> float: ... + def repeat(self, repeat: int = ..., number: int = ...) -> List[float]: ... + if sys.version_info >= (3, 6): + def autorange(self, callback: Optional[Callable[[int, float], Any]] = ...) -> Tuple[int, float]: ... + +if sys.version_info >= (3, 5): + def timeit(stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., + number: int = ..., globals: Optional[Dict[str, Any]] = ...) -> float: ... + def repeat(stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., + repeat: int = ..., number: int = ..., globals: Optional[Dict[str, Any]] = ...) -> List[float]: ... +else: + def timeit(stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., + number: int = ...) -> float: ... + def repeat(stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., + repeat: int = ..., number: int = ...) -> List[float]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/token.pyi b/client/typeshed-fallback/stdlib/2and3/token.pyi new file mode 100644 index 000000000..8d044bdc2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/token.pyi @@ -0,0 +1,71 @@ +import sys +from typing import Dict + +ENDMARKER = ... # type: int +NAME = ... # type: int +NUMBER = ... # type: int +STRING = ... # type: int +NEWLINE = ... # type: int +INDENT = ... # type: int +DEDENT = ... # type: int +LPAR = ... # type: int +RPAR = ... # type: int +LSQB = ... # type: int +RSQB = ... # type: int +COLON = ... # type: int +COMMA = ... # type: int +SEMI = ... # type: int +PLUS = ... # type: int +MINUS = ... # type: int +STAR = ... # type: int +SLASH = ... # type: int +VBAR = ... # type: int +AMPER = ... # type: int +LESS = ... # type: int +GREATER = ... # type: int +EQUAL = ... # type: int +DOT = ... # type: int +PERCENT = ... # type: int +if sys.version_info < (3,): + BACKQUOTE = ... # type: int +LBRACE = ... # type: int +RBRACE = ... # type: int +EQEQUAL = ... # type: int +NOTEQUAL = ... # type: int +LESSEQUAL = ... # type: int +GREATEREQUAL = ... # type: int +TILDE = ... # type: int +CIRCUMFLEX = ... # type: int +LEFTSHIFT = ... # type: int +RIGHTSHIFT = ... # type: int +DOUBLESTAR = ... # type: int +PLUSEQUAL = ... # type: int +MINEQUAL = ... # type: int +STAREQUAL = ... # type: int +SLASHEQUAL = ... # type: int +PERCENTEQUAL = ... # type: int +AMPEREQUAL = ... # type: int +VBAREQUAL = ... # type: int +CIRCUMFLEXEQUAL = ... # type: int +LEFTSHIFTEQUAL = ... # type: int +RIGHTSHIFTEQUAL = ... # type: int +DOUBLESTAREQUAL = ... # type: int +DOUBLESLASH = ... # type: int +DOUBLESLASHEQUAL = ... # type: int +AT = ... # type: int +if sys.version_info >= (3,): + RARROW = ... # type: int + ELLIPSIS = ... # type: int +if sys.version_info >= (3, 5): + ATEQUAL = ... # type: int + AWAIT = ... # type: int + ASYNC = ... # type: int +OP = ... # type: int +ERRORTOKEN = ... # type: int +N_TOKENS = ... # type: int +NT_OFFSET = ... # type: int +tok_name = ... # type: Dict[int, str] + +def ISTERMINAL(x: int) -> bool: ... +def ISNONTERMINAL(x: int) -> bool: ... +def ISEOF(x: int) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/2and3/trace.pyi b/client/typeshed-fallback/stdlib/2and3/trace.pyi new file mode 100644 index 000000000..af06d39c0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/trace.pyi @@ -0,0 +1,35 @@ +# Stubs for trace (Python 2 and 3) + +import os +import sys +import types +from typing import Any, Callable, Mapping, Optional, Sequence, Text, Tuple, TypeVar, Union + +_T = TypeVar('_T') +_localtrace = Callable[[types.FrameType, str, Any], Callable[..., Any]] + +if sys.version_info >= (3, 6): + _Path = Union[Text, os.PathLike] +else: + _Path = Text + +class CoverageResults: + def update(self, other: CoverageResults) -> None: ... + def write_results(self, show_missing: bool = ..., summary: bool = ..., coverdir: Optional[_Path] = ...) -> None: ... + def write_results_file(self, path: _Path, lines: Sequence[str], lnotab: Any, lines_hit: Mapping[int, int], encoding: Optional[str] = ...) -> Tuple[int, int]: ... + +class Trace: + def __init__(self, count: int = ..., trace: int = ..., countfuncs: int = ..., countcallers: int = ..., + ignoremods: Sequence[str] = ..., ignoredirs: Sequence[str] = ..., infile: Optional[_Path] = ..., + outfile: Optional[_Path] = ..., timing: bool = ...) -> None: ... + def run(self, cmd: Union[str, types.CodeType]) -> None: ... + def runctx(self, cmd: Union[str, types.CodeType], globals: Optional[Mapping[str, Any]] = ..., locals: Optional[Mapping[str, Any]] = ...) -> None: ... + def runfunc(self, func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... + def file_module_function_of(self, frame: types.FrameType) -> Tuple[str, Optional[str], str]: ... + def globaltrace_trackcallers(self, frame: types.FrameType, why: str, arg: Any) -> None: ... + def globaltrace_countfuncs(self, frame: types.FrameType, why: str, arg: Any) -> None: ... + def globaltrace_lt(self, frame: types.FrameType, why: str, arg: Any) -> None: ... + def localtrace_trace_and_count(self, frame: types.FrameType, why: str, arg: Any) -> _localtrace: ... + def localtrace_trace(self, frame: types.FrameType, why: str, arg: Any) -> _localtrace: ... + def localtrace_count(self, frame: types.FrameType, why: str, arg: Any) -> _localtrace: ... + def results(self) -> CoverageResults: ... diff --git a/client/typeshed-fallback/stdlib/2and3/traceback.pyi b/client/typeshed-fallback/stdlib/2and3/traceback.pyi new file mode 100644 index 000000000..3b77df261 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/traceback.pyi @@ -0,0 +1,116 @@ +# Stubs for traceback + +from typing import Any, Dict, Generator, IO, Iterator, List, Mapping, Optional, Tuple, Type, Iterable +from types import FrameType, TracebackType +import sys + +_PT = Tuple[str, int, str, Optional[str]] + + +def print_tb(tb: Optional[TracebackType], limit: Optional[int] = ..., + file: Optional[IO[str]] = ...) -> None: ... +if sys.version_info >= (3,): + def print_exception(etype: Optional[Type[BaseException]], + value: Optional[BaseException], + tb: Optional[TracebackType], limit: Optional[int] = ..., + file: Optional[IO[str]] = ..., + chain: bool = ...) -> None: ... + def print_exc(limit: Optional[int] = ..., file: Optional[IO[str]] = ..., + chain: bool = ...) -> None: ... + def print_last(limit: Optional[int] = ..., file: Optional[IO[str]] = ..., + chain: bool = ...) -> None: ... +else: + def print_exception(etype: Optional[Type[BaseException]], + value: Optional[BaseException], + tb: Optional[TracebackType], limit: Optional[int] = ..., + file: Optional[IO[str]] = ...) -> None: ... + def print_exc(limit: Optional[int] = ..., + file: Optional[IO[str]] = ...) -> None: ... + def print_last(limit: Optional[int] = ..., + file: Optional[IO[str]] = ...) -> None: ... +def print_stack(f: Optional[FrameType] = ..., limit: Optional[int] = ..., + file: Optional[IO[str]] = ...) -> None: ... + +if sys.version_info >= (3, 5): + def extract_tb(tb: Optional[TracebackType], limit: Optional[int] = ...) -> StackSummary: ... + def extract_stack(f: Optional[FrameType] = ..., + limit: Optional[int] = ...) -> StackSummary: ... + def format_list(extracted_list: List[FrameSummary]) -> List[str]: ... +else: + def extract_tb(tb: Optional[TracebackType], limit: Optional[int] = ...) -> List[_PT]: ... + def extract_stack(f: Optional[FrameType] = ..., + limit: Optional[int] = ...) -> List[_PT]: ... + def format_list(extracted_list: List[_PT]) -> List[str]: ... +def format_exception_only(etype: Optional[Type[BaseException]], + value: Optional[BaseException]) -> List[str]: ... +if sys.version_info >= (3,): + def format_exception(etype: Optional[Type[BaseException]], value: Optional[BaseException], + tb: Optional[TracebackType], limit: Optional[int] = ..., + chain: bool = ...) -> List[str]: ... + def format_exc(limit: Optional[int] = ..., chain: bool = ...) -> str: ... +else: + def format_exception(etype: Optional[Type[BaseException]], + value: Optional[BaseException], + tb: Optional[TracebackType], + limit: Optional[int] = ...) -> List[str]: ... + def format_exc(limit: Optional[int] = ...) -> str: ... +def format_tb(tb: Optional[TracebackType], limit: Optional[int] = ...) -> List[str]: ... +def format_stack(f: Optional[FrameType] = ..., + limit: Optional[int] = ...) -> List[str]: ... +if sys.version_info >= (3, 4): + def clear_frames(tb: TracebackType) -> None: ... +if sys.version_info >= (3, 5): + def walk_stack(f: Optional[FrameType]) -> Iterator[Tuple[FrameType, int]]: ... + def walk_tb(tb: Optional[TracebackType]) -> Iterator[Tuple[FrameType, int]]: ... +if sys.version_info < (3,): + def tb_lineno(tb: TracebackType) -> int: ... + + +if sys.version_info >= (3, 5): + class TracebackException: + __cause__ = ... # type:TracebackException + __context__ = ... # type:TracebackException + __suppress_context__ = ... # type: bool + stack = ... # type: StackSummary + exc_type = ... # type: Type[BaseException] + filename = ... # type: str + lineno = ... # type: int + text = ... # type: str + offset = ... # type: int + msg = ... # type: str + def __init__(self, exc_type: Type[BaseException], + exc_value: BaseException, exc_traceback: TracebackType, + *, limit: Optional[int] = ..., lookup_lines: bool = ..., + capture_locals: bool = ...) -> None: ... + @classmethod + def from_exception(cls, exc: BaseException, + *, limit: Optional[int] = ..., + lookup_lines: bool = ..., + capture_locals: bool = ...) -> TracebackException: ... + def format(self, *, chain: bool = ...) -> Generator[str, None, None]: ... + def format_exception_only(self) -> Generator[str, None, None]: ... + + class FrameSummary(Iterable): + filename: str + lineno: int + name: str + line: str + locals: Optional[Dict[str, str]] + def __init__(self, filename: str, lineno: int, name: str, + lookup_line: bool = ..., + locals: Optional[Mapping[str, str]] = ..., + line: Optional[str] = ...) -> None: ... + # TODO: more precise typing for __getitem__ and __iter__, + # for a namedtuple-like view on (filename, lineno, name, str). + def __getitem__(self, i: int) -> Any: ... + def __iter__(self) -> Iterator[Any]: ... + + class StackSummary(List[FrameSummary]): + @classmethod + def extract(cls, + frame_gen: Generator[Tuple[FrameType, int], None, None], + *, limit: Optional[int] = ..., lookup_lines: bool = ..., + capture_locals: bool = ...) -> StackSummary: ... + @classmethod + def from_list(cls, a_list: List[_PT]) -> StackSummary: ... + def format(self) -> List[str]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/tty.pyi b/client/typeshed-fallback/stdlib/2and3/tty.pyi new file mode 100644 index 000000000..18d8bcc3b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/tty.pyi @@ -0,0 +1,17 @@ +# Stubs for tty (Python 3.6) + +from typing import IO, Union + +_FD = Union[int, IO[str]] + +# XXX: Undocumented integer constants +IFLAG = ... # type: int +OFLAG = ... # type: int +CFLAG = ... # type: int +LFLAG = ... # type: int +ISPEED = ... # type: int +OSPEED = ... # type: int +CC = ... # type: int + +def setraw(fd: _FD, when: int = ...) -> None: ... +def setcbreak(fd: _FD, when: int = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/unicodedata.pyi b/client/typeshed-fallback/stdlib/2and3/unicodedata.pyi new file mode 100644 index 000000000..c8e64610a --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/unicodedata.pyi @@ -0,0 +1,38 @@ +# Stubs for unicodedata (Python 2.7 and 3.4) +from typing import Any, Text, TypeVar, Union + +ucd_3_2_0 = ... # type: UCD +ucnhash_CAPI = ... # type: Any +unidata_version = ... # type: str + +_default = TypeVar('_default') + +def bidirectional(__chr: Text) -> Text: ... +def category(__chr: Text) -> Text: ... +def combining(__chr: Text) -> int: ... +def decimal(__chr: Text, __default: _default = ...) -> Union[int, _default]: ... +def decomposition(__chr: Text) -> Text: ... +def digit(__chr: Text, __default: _default = ...) -> Union[int, _default]: ... +def east_asian_width(__chr: Text) -> Text: ... +def lookup(__name: Union[Text, bytes]) -> Text: ... +def mirrored(__chr: Text) -> int: ... +def name(__chr: Text, __default: _default = ...) -> Union[Text, _default]: ... +def normalize(__form: Text, __unistr: Text) -> Text: ... +def numeric(__chr: Text, __default: _default = ...) -> Union[float, _default]: ... + +class UCD(object): + # The methods below are constructed from the same array in C + # (unicodedata_functions) and hence identical to the methods above. + unidata_version = ... # type: str + def bidirectional(self, __chr: Text) -> str: ... + def category(self, __chr: Text) -> str: ... + def combining(self, __chr: Text) -> int: ... + def decimal(self, __chr: Text, __default: _default = ...) -> Union[int, _default]: ... + def decomposition(self, __chr: Text) -> str: ... + def digit(self, __chr: Text, __default: _default = ...) -> Union[int, _default]: ... + def east_asian_width(self, __chr: Text) -> str: ... + def lookup(self, __name: Union[Text, bytes]) -> Text: ... + def mirrored(self, __chr: Text) -> int: ... + def name(self, __chr: Text, __default: _default = ...) -> Union[Text, _default]: ... + def normalize(self, __form: Text, __unistr: Text) -> Text: ... + def numeric(self, __chr: Text, __default: _default = ...) -> Union[float, _default]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/uu.pyi b/client/typeshed-fallback/stdlib/2and3/uu.pyi new file mode 100644 index 000000000..c926dbba2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/uu.pyi @@ -0,0 +1,13 @@ +# Stubs for uu (Python 2 and 3) +import sys +from typing import BinaryIO, Union, Optional, Text + +_File = Union[Text, BinaryIO] + +class Error(Exception): ... + +if sys.version_info >= (3, 7): + def encode(in_file: _File, out_file: _File, name: Optional[str] = ..., mode: Optional[int] = ..., backtick: bool = ...) -> None: ... +else: + def encode(in_file: _File, out_file: _File, name: Optional[str] = ..., mode: Optional[int] = ...) -> None: ... +def decode(in_file: _File, out_file: Optional[_File] = ..., mode: Optional[int] = ..., quiet: int = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/uuid.pyi b/client/typeshed-fallback/stdlib/2and3/uuid.pyi new file mode 100644 index 000000000..4718f1a98 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/uuid.pyi @@ -0,0 +1,90 @@ +# Stubs for uuid + +import sys +from typing import Tuple, Optional, Any, Text + +# Because UUID has properties called int and bytes we need to rename these temporarily. +_Int = int +_Bytes = bytes +_FieldsType = Tuple[int, int, int, int, int, int] + +class UUID: + def __init__(self, hex: Optional[Text] = ..., + bytes: Optional[_Bytes] = ..., + bytes_le: Optional[_Bytes] = ..., + fields: Optional[_FieldsType] = ..., + int: Optional[_Int] = ..., + version: Optional[_Int] = ...) -> None: ... + @property + def bytes(self) -> _Bytes: ... + @property + def bytes_le(self) -> _Bytes: ... + @property + def clock_seq(self) -> _Int: ... + @property + def clock_seq_hi_variant(self) -> _Int: ... + @property + def clock_seq_low(self) -> _Int: ... + @property + def fields(self) -> _FieldsType: ... + @property + def hex(self) -> str: ... + @property + def int(self) -> _Int: ... + @property + def node(self) -> _Int: ... + @property + def time(self) -> _Int: ... + @property + def time_hi_version(self) -> _Int: ... + @property + def time_low(self) -> _Int: ... + @property + def time_mid(self) -> _Int: ... + @property + def urn(self) -> str: ... + @property + def variant(self) -> str: ... + @property + def version(self) -> Optional[_Int]: ... + + def __int__(self) -> _Int: ... + + if sys.version_info >= (3,): + def __eq__(self, other: Any) -> bool: ... + def __lt__(self, other: Any) -> bool: ... + def __le__(self, other: Any) -> bool: ... + def __gt__(self, other: Any) -> bool: ... + def __ge__(self, other: Any) -> bool: ... + else: + def get_bytes(self) -> _Bytes: ... + def get_bytes_le(self) -> _Bytes: ... + def get_clock_seq(self) -> _Int: ... + def get_clock_seq_hi_variant(self) -> _Int: ... + def get_clock_seq_low(self) -> _Int: ... + def get_fields(self) -> _FieldsType: ... + def get_hex(self) -> str: ... + def get_node(self) -> _Int: ... + def get_time(self) -> _Int: ... + def get_time_hi_version(self) -> _Int: ... + def get_time_low(self) -> _Int: ... + def get_time_mid(self) -> _Int: ... + def get_urn(self) -> str: ... + def get_variant(self) -> str: ... + def get_version(self) -> Optional[_Int]: ... + def __cmp__(self, other: Any) -> _Int: ... + +def getnode() -> int: ... +def uuid1(node: Optional[_Int] = ..., clock_seq: Optional[_Int] = ...) -> UUID: ... +def uuid3(namespace: UUID, name: str) -> UUID: ... +def uuid4() -> UUID: ... +def uuid5(namespace: UUID, name: str) -> UUID: ... + +NAMESPACE_DNS = ... # type: UUID +NAMESPACE_URL = ... # type: UUID +NAMESPACE_OID = ... # type: UUID +NAMESPACE_X500 = ... # type: UUID +RESERVED_NCS = ... # type: str +RFC_4122 = ... # type: str +RESERVED_MICROSOFT = ... # type: str +RESERVED_FUTURE = ... # type: str diff --git a/client/typeshed-fallback/stdlib/2and3/warnings.pyi b/client/typeshed-fallback/stdlib/2and3/warnings.pyi new file mode 100644 index 000000000..676d5b95e --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/warnings.pyi @@ -0,0 +1,38 @@ +# Stubs for warnings + +from typing import Any, Dict, List, NamedTuple, Optional, TextIO, Tuple, Type, Union +from types import ModuleType, TracebackType + +def warn(message: Union[str, Warning], category: Optional[Type[Warning]] = ..., + stacklevel: int = ...) -> None: ... +def warn_explicit(message: Union[str, Warning], category: Type[Warning], + filename: str, lineno: int, module: Optional[str] = ..., + registry: Optional[Dict[Union[str, Tuple[str, Type[Warning], int]], int]] = ..., + module_globals: Optional[Dict[str, Any]] = ...) -> None: ... +def showwarning(message: str, category: Type[Warning], filename: str, + lineno: int, file: Optional[TextIO] = ..., + line: Optional[str] = ...) -> None: ... +def formatwarning(message: str, category: Type[Warning], filename: str, + lineno: int, line: Optional[str] = ...) -> str: ... +def filterwarnings(action: str, message: str = ..., + category: Type[Warning] = ..., module: str = ..., + lineno: int = ..., append: bool = ...) -> None: ... +def simplefilter(action: str, category: Type[Warning] = ..., lineno: int = ..., + append: bool = ...) -> None: ... +def resetwarnings() -> None: ... + +_Record = NamedTuple('_Record', + [('message', str), + ('category', Type[Warning]), + ('filename', str), + ('lineno', int), + ('file', Optional[TextIO]), + ('line', Optional[str])]) + +class catch_warnings: + def __init__(self, *, record: bool = ..., + module: Optional[ModuleType] = ...) -> None: ... + def __enter__(self) -> Optional[List[_Record]]: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[Exception], + exc_tb: Optional[TracebackType]) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/2and3/wave.pyi b/client/typeshed-fallback/stdlib/2and3/wave.pyi new file mode 100644 index 000000000..672e94d29 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/wave.pyi @@ -0,0 +1,76 @@ +# Stubs for wave (Python 2 and 3) + +import sys +from typing import ( + Any, NamedTuple, NoReturn, Optional, Text, BinaryIO, Union, Tuple +) + +_File = Union[Text, BinaryIO] + +class Error(Exception): ... + +WAVE_FORMAT_PCM = ... # type: int + +if sys.version_info < (3, 0): + _wave_params = Tuple[int, int, int, int, str, str] +else: + _wave_params = NamedTuple('_wave_params', [ + ('nchannels', int), + ('sampwidth', int), + ('framerate', int), + ('nframes', int), + ('comptype', str), + ('compname', str), + ]) + +class Wave_read: + def __init__(self, f: _File) -> None: ... + if sys.version_info >= (3, 0): + def __enter__(self) -> Wave_read: ... + def __exit__(self, *args: Any) -> None: ... + def getfp(self) -> Optional[BinaryIO]: ... + def rewind(self) -> None: ... + def close(self) -> None: ... + def tell(self) -> int: ... + def getnchannels(self) -> int: ... + def getnframes(self) -> int: ... + def getsampwidth(self) -> int: ... + def getframerate(self) -> int: ... + def getcomptype(self) -> str: ... + def getcompname(self) -> str: ... + def getparams(self) -> _wave_params: ... + def getmarkers(self) -> None: ... + def getmark(self, id: Any) -> NoReturn: ... + def setpos(self, pos: int) -> None: ... + def readframes(self, nframes: int) -> bytes: ... + +class Wave_write: + def __init__(self, f: _File) -> None: ... + if sys.version_info >= (3, 0): + def __enter__(self) -> Wave_write: ... + def __exit__(self, *args: Any) -> None: ... + def setnchannels(self, nchannels: int) -> None: ... + def getnchannels(self) -> int: ... + def setsampwidth(self, sampwidth: int) -> None: ... + def getsampwidth(self) -> int: ... + def setframerate(self, framerate: float) -> None: ... + def getframerate(self) -> int: ... + def setnframes(self, nframes: int) -> None: ... + def getnframes(self) -> int: ... + def setcomptype(self, comptype: str, compname: str) -> None: ... + def getcomptype(self) -> str: ... + def getcompname(self) -> str: ... + def setparams(self, params: _wave_params) -> None: ... + def getparams(self) -> _wave_params: ... + def setmark(self, id: Any, pos: Any, name: Any) -> NoReturn: ... + def getmark(self, id: Any) -> NoReturn: ... + def getmarkers(self) -> None: ... + def tell(self) -> int: ... + # should be any bytes-like object after 3.4, but we don't have a type for that + def writeframesraw(self, data: bytes) -> None: ... + def writeframes(self, data: bytes) -> None: ... + def close(self) -> None: ... + +# Returns a Wave_read if mode is rb and Wave_write if mode is wb +def open(f: _File, mode: Optional[str] = ...) -> Any: ... +openfp = open diff --git a/client/typeshed-fallback/stdlib/2and3/weakref.pyi b/client/typeshed-fallback/stdlib/2and3/weakref.pyi new file mode 100644 index 000000000..e3ddbf278 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/weakref.pyi @@ -0,0 +1,110 @@ +import sys +import types +from typing import ( + TypeVar, Generic, Any, Callable, overload, Mapping, Iterator, Tuple, + Iterable, Optional, Type, MutableMapping, Union, List, Dict +) + +from _weakref import ( + getweakrefcount as getweakrefcount, + getweakrefs as getweakrefs, + ref as ref, + proxy as proxy, + CallableProxyType as CallableProxyType, + ProxyType as ProxyType, + ReferenceType as ReferenceType) +from _weakrefset import WeakSet as WeakSet + +if sys.version_info < (3, 0): + from exceptions import ReferenceError as ReferenceError + +_S = TypeVar('_S') +_T = TypeVar('_T') +_KT = TypeVar('_KT') +_VT = TypeVar('_VT') + +ProxyTypes: Tuple[Type[Any], ...] + +if sys.version_info >= (3, 4): + class WeakMethod(ref[types.MethodType]): + def __new__(cls, meth: types.MethodType, callback: Optional[Callable[[types.MethodType], Any]] = ...) -> WeakMethod: ... + def __call__(self) -> Optional[types.MethodType]: ... + +class WeakValueDictionary(MutableMapping[_KT, _VT]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, __map: Union[Mapping[_KT, _VT], Iterable[Tuple[_KT, _VT]]], **kwargs: _VT) -> None: ... + + def __len__(self) -> int: ... + def __getitem__(self, k: _KT) -> _VT: ... + def __setitem__(self, k: _KT, v: _VT) -> None: ... + def __delitem__(self, v: _KT) -> None: ... + if sys.version_info < (3, 0): + def has_key(self, key: object) -> bool: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_KT]: ... + def __str__(self) -> str: ... + + def copy(self) -> WeakValueDictionary[_KT, _VT]: ... + + if sys.version_info < (3, 0): + def keys(self) -> List[_KT]: ... + def values(self) -> List[_VT]: ... + def items(self) -> List[Tuple[_KT, _VT]]: ... + def iterkeys(self) -> Iterator[_KT]: ... + def itervalues(self) -> Iterator[_VT]: ... + def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... + else: + # These are incompatible with Mapping + def keys(self) -> Iterator[_KT]: ... # type: ignore + def values(self) -> Iterator[_VT]: ... # type: ignore + def items(self) -> Iterator[Tuple[_KT, _VT]]: ... # type: ignore + def itervaluerefs(self) -> Iterator[KeyedRef[_KT, _VT]]: ... + def valuerefs(self) -> List[KeyedRef[_KT, _VT]]: ... + +class KeyedRef(ref[_T], Generic[_KT, _T]): + key: _KT + def __init__(self, ob: _T, callback: Callable[[_T], Any], key: _KT) -> None: ... + +class WeakKeyDictionary(MutableMapping[_KT, _VT]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, __map: Union[Mapping[_KT, _VT], Iterable[Tuple[_KT, _VT]]], **kwargs: _VT) -> None: ... + + def __len__(self) -> int: ... + def __getitem__(self, k: _KT) -> _VT: ... + def __setitem__(self, k: _KT, v: _VT) -> None: ... + def __delitem__(self, v: _KT) -> None: ... + if sys.version_info < (3, 0): + def has_key(self, key: object) -> bool: ... + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_KT]: ... + def __str__(self) -> str: ... + + def copy(self) -> WeakKeyDictionary[_KT, _VT]: ... + + if sys.version_info < (3, 0): + def keys(self) -> List[_KT]: ... + def values(self) -> List[_VT]: ... + def items(self) -> List[Tuple[_KT, _VT]]: ... + def iterkeys(self) -> Iterator[_KT]: ... + def itervalues(self) -> Iterator[_VT]: ... + def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... + def iterkeyrefs(self) -> Iterator[ref[_KT]]: ... + else: + # These are incompatible with Mapping + def keys(self) -> Iterator[_KT]: ... # type: ignore + def values(self) -> Iterator[_VT]: ... # type: ignore + def items(self) -> Iterator[Tuple[_KT, _VT]]: ... # type: ignore + def keyrefs(self) -> List[ref[_KT]]: ... + +if sys.version_info >= (3, 4): + class finalize: + def __init__(self, obj: _S, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... + def __call__(self, _: Any = ...) -> Optional[_T]: ... + def detach(self) -> Optional[Tuple[_S, _T, Tuple[Any, ...], Dict[str, Any]]]: ... + def peek(self) -> Optional[Tuple[_S, _T, Tuple[Any, ...], Dict[str, Any]]]: ... + alive: bool + atexit: bool diff --git a/client/typeshed-fallback/stdlib/2and3/webbrowser.pyi b/client/typeshed-fallback/stdlib/2and3/webbrowser.pyi new file mode 100644 index 000000000..3d276c8c0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/webbrowser.pyi @@ -0,0 +1,96 @@ +import sys +from typing import Any, Optional, Callable, List, Text, Union, Sequence + +class Error(Exception): ... + +def register(name: Text, klass: Optional[Callable[[], BaseBrowser]], instance: BaseBrowser = ..., update_tryorder: int = ...) -> None: ... +def get(using: Optional[Text] = ...) -> BaseBrowser: ... +def open(url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... +def open_new(url: Text) -> bool: ... +def open_new_tab(url: Text) -> bool: ... + +class BaseBrowser: + args = ... # type: List[str] + name = ... # type: str + basename = ... # type: str + def __init__(self, name: Text = ...) -> None: ... + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + def open_new(self, url: Text) -> bool: ... + def open_new_tab(self, url: Text) -> bool: ... + +class GenericBrowser(BaseBrowser): + args = ... # type: List[str] + name = ... # type: str + basename = ... # type: str + def __init__(self, name: Union[Text, Sequence[Text]]) -> None: ... + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +class BackgroundBrowser(GenericBrowser): + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +class UnixBrowser(BaseBrowser): + raise_opts = ... # type: List[str] + background = ... # type: bool + redirect_stdout = ... # type: bool + remote_args = ... # type: List[str] + remote_action = ... # type: str + remote_action_newwin = ... # type: str + remote_action_newtab = ... # type: str + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +class Mozilla(UnixBrowser): + raise_opts = ... # type: List[str] + remote_args = ... # type: List[str] + remote_action = ... # type: str + remote_action_newwin = ... # type: str + remote_action_newtab = ... # type: str + background = ... # type: bool + +class Galeon(UnixBrowser): + raise_opts = ... # type: List[str] + remote_args = ... # type: List[str] + remote_action = ... # type: str + remote_action_newwin = ... # type: str + background = ... # type: bool + +if sys.version_info[:2] == (2, 7) or sys.version_info >= (3, 3): + class Chrome(UnixBrowser): + remote_args = ... # type: List[str] + remote_action = ... # type: str + remote_action_newwin = ... # type: str + remote_action_newtab = ... # type: str + background = ... # type: bool + +class Opera(UnixBrowser): + raise_opts = ... # type: List[str] + remote_args = ... # type: List[str] + remote_action = ... # type: str + remote_action_newwin = ... # type: str + remote_action_newtab = ... # type: str + background = ... # type: bool + +class Elinks(UnixBrowser): + remote_args = ... # type: List[str] + remote_action = ... # type: str + remote_action_newwin = ... # type: str + remote_action_newtab = ... # type: str + background = ... # type: bool + redirect_stdout = ... # type: bool + +class Konqueror(BaseBrowser): + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +class Grail(BaseBrowser): + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +class WindowsDefault(BaseBrowser): + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +class MacOSX(BaseBrowser): + name = ... # type: str + def __init__(self, name: Text) -> None: ... + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... + +class MacOSXOSAScript(BaseBrowser): + def __init__(self, name: Text) -> None: ... + def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/2and3/wsgiref/__init__.pyi b/client/typeshed-fallback/stdlib/2and3/wsgiref/__init__.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/wsgiref/handlers.pyi b/client/typeshed-fallback/stdlib/2and3/wsgiref/handlers.pyi new file mode 100644 index 000000000..3271c881a --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/wsgiref/handlers.pyi @@ -0,0 +1,87 @@ +import sys +from abc import abstractmethod +from types import TracebackType +from typing import Optional, Dict, MutableMapping, Type, Text, Callable, List, Tuple, IO + +from .headers import Headers +from .types import WSGIApplication, WSGIEnvironment, StartResponse, InputStream, ErrorStream +from .util import FileWrapper, guess_scheme + +_exc_info = Tuple[Optional[Type[BaseException]], + Optional[BaseException], + Optional[TracebackType]] + +def format_date_time(timestamp: Optional[float]) -> str: ... # undocumented +if sys.version_info >= (3, 2): + def read_environ() -> Dict[str, str]: ... + +class BaseHandler: + wsgi_version: Tuple[int, int] # undocumented + wsgi_multithread: bool + wsgi_multiprocess: bool + wsgi_run_once: bool + + origin_server: bool + http_version: str + server_software: Optional[str] + + os_environ: MutableMapping[str, str] + + wsgi_file_wrapper: Optional[Type[FileWrapper]] + headers_class: Type[Headers] # undocumented + + traceback_limit: Optional[int] + error_status: str + error_headers: List[Tuple[Text, Text]] + error_body: bytes + + def run(self, application: WSGIApplication) -> None: ... + + def setup_environ(self) -> None: ... + def finish_response(self) -> None: ... + def get_scheme(self) -> str: ... + def set_content_length(self) -> None: ... + def cleanup_headers(self) -> None: ... + def start_response(self, status: Text, headers: List[Tuple[Text, Text]], exc_info: Optional[_exc_info] = ...) -> Callable[[bytes], None]: ... + def send_preamble(self) -> None: ... + def write(self, data: bytes) -> None: ... + def sendfile(self) -> bool: ... + def finish_content(self) -> None: ... + def close(self) -> None: ... + def send_headers(self) -> None: ... + def result_is_file(self) -> bool: ... + def client_is_modern(self) -> bool: ... + def log_exception(self, exc_info: _exc_info) -> None: ... + def handle_error(self) -> None: ... + def error_output(self, environ: WSGIEnvironment, start_response: StartResponse) -> List[bytes]: ... + + @abstractmethod + def _write(self, data: bytes) -> None: ... + @abstractmethod + def _flush(self) -> None: ... + @abstractmethod + def get_stdin(self) -> InputStream: ... + @abstractmethod + def get_stderr(self) -> ErrorStream: ... + @abstractmethod + def add_cgi_vars(self) -> None: ... + +class SimpleHandler(BaseHandler): + stdin: InputStream + stdout: IO[bytes] + stderr: ErrorStream + base_env: MutableMapping[str, str] + def __init__(self, stdin: InputStream, stdout: IO[bytes], stderr: ErrorStream, environ: MutableMapping[str, str], multithread: bool = ..., multiprocess: bool = ...) -> None: ... + def get_stdin(self) -> InputStream: ... + def get_stderr(self) -> ErrorStream: ... + def add_cgi_vars(self) -> None: ... + def _write(self, data: bytes) -> None: ... + def _flush(self) -> None: ... + +class BaseCGIHandler(SimpleHandler): ... + +class CGIHandler(BaseCGIHandler): + def __init__(self) -> None: ... + +class IISCGIHandler(BaseCGIHandler): + def __init__(self) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/wsgiref/headers.pyi b/client/typeshed-fallback/stdlib/2and3/wsgiref/headers.pyi new file mode 100644 index 000000000..853922527 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/wsgiref/headers.pyi @@ -0,0 +1,31 @@ +import sys +from typing import overload, Pattern, Optional, List, Tuple + +_HeaderList = List[Tuple[str, str]] + +tspecials: Pattern[str] # undocumented + +class Headers: + if sys.version_info < (3, 5): + def __init__(self, headers: _HeaderList) -> None: ... + else: + def __init__(self, headers: Optional[_HeaderList] = ...) -> None: ... + def __len__(self) -> int: ... + def __setitem__(self, name: str, val: str) -> None: ... + def __delitem__(self, name: str) -> None: ... + def __getitem__(self, name: str) -> Optional[str]: ... + if sys.version_info < (3,): + def has_key(self, name: str) -> bool: ... + def __contains__(self, name: str) -> bool: ... + def get_all(self, name: str) -> List[str]: ... + @overload + def get(self, name: str, default: str) -> str: ... + @overload + def get(self, name: str, default: Optional[str] = ...) -> Optional[str]: ... + def keys(self) -> List[str]: ... + def values(self) -> List[str]: ... + def items(self) -> _HeaderList: ... + if sys.version_info >= (3,): + def __bytes__(self) -> bytes: ... + def setdefault(self, name: str, value: str) -> str: ... + def add_header(self, _name: str, _value: Optional[str], **_params: Optional[str]) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/wsgiref/simple_server.pyi b/client/typeshed-fallback/stdlib/2and3/wsgiref/simple_server.pyi new file mode 100644 index 000000000..50b8377e5 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/wsgiref/simple_server.pyi @@ -0,0 +1,40 @@ +import sys +from typing import Optional, List, Type, TypeVar, overload + +from .handlers import SimpleHandler +from .types import WSGIApplication, WSGIEnvironment, StartResponse, ErrorStream + +if sys.version_info < (3,): + from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer +else: + from http.server import HTTPServer, BaseHTTPRequestHandler + +server_version: str # undocumented +sys_version: str # undocumented +software_version: str # undocumented + +class ServerHandler(SimpleHandler): # undocumented + server_software: str + def close(self) -> None: ... + +class WSGIServer(HTTPServer): + application: Optional[WSGIApplication] + base_environ: WSGIEnvironment # only available after call to setup_environ() + def setup_environ(self) -> None: ... + def get_app(self) -> Optional[WSGIApplication]: ... + def set_app(self, application: Optional[WSGIApplication]) -> None: ... + +class WSGIRequestHandler(BaseHTTPRequestHandler): + server_version: str + def get_environ(self) -> WSGIEnvironment: ... + def get_stderr(self) -> ErrorStream: ... + def handle(self) -> None: ... + +def demo_app(environ: WSGIEnvironment, start_response: StartResponse) -> List[bytes]: ... + +_S = TypeVar("_S", bound=WSGIServer) + +@overload +def make_server(host: str, port: int, app: WSGIApplication, *, handler_class: Type[WSGIRequestHandler] = ...) -> WSGIServer: ... +@overload +def make_server(host: str, port: int, app: WSGIApplication, server_class: Type[_S], handler_class: Type[WSGIRequestHandler] = ...) -> _S: ... diff --git a/client/typeshed-fallback/stdlib/2and3/wsgiref/types.pyi b/client/typeshed-fallback/stdlib/2and3/wsgiref/types.pyi new file mode 100644 index 000000000..39a913eea --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/wsgiref/types.pyi @@ -0,0 +1,44 @@ +# Type declaration for a WSGI Function +# +# wsgiref/types.py doesn't exist and neither do the types defined in this +# file. They are provided for type checking purposes. +# +# This means you cannot simply import wsgiref.types in your code. Instead, +# use the `TYPE_CHECKING` flag from the typing module: +# +# from typing import TYPE_CHECKING +# +# if TYPE_CHECKING: +# from wsgiref.types import WSGIApplication +# +# This import is now only taken into account by the type checker. Consequently, +# you need to use 'WSGIApplication' and not simply WSGIApplication when type +# hinting your code. Otherwise Python will raise NameErrors. + +from sys import _OptExcInfo +from typing import Callable, Dict, Iterable, List, Any, Text, Protocol, Tuple, Optional + +class StartResponse(Protocol): + def __call__(self, status: str, headers: List[Tuple[str, str]], exc_info: Optional[_OptExcInfo] = ...) -> Callable[[bytes], Any]: ... + +WSGIEnvironment = Dict[Text, Any] +WSGIApplication = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] + +# WSGI input streams per PEP 3333 +class InputStream(Protocol): + def read(self, size: int = ...) -> bytes: ... + def readline(self, size: int = ...) -> bytes: ... + def readlines(self, hint: int = ...) -> List[bytes]: ... + def __iter__(self) -> Iterable[bytes]: ... + +# WSGI error streams per PEP 3333 +class ErrorStream(Protocol): + def flush(self) -> None: ... + def write(self, s: str) -> None: ... + def writelines(self, seq: List[str]) -> None: ... + +class _Readable(Protocol): + def read(self, size: int = ...) -> bytes: ... +# Optional file wrapper in wsgi.file_wrapper +class FileWrapper(Protocol): + def __call__(self, file: _Readable, block_size: int = ...) -> Iterable[bytes]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/wsgiref/util.pyi b/client/typeshed-fallback/stdlib/2and3/wsgiref/util.pyi new file mode 100644 index 000000000..501ddcd5b --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/wsgiref/util.pyi @@ -0,0 +1,23 @@ +import sys +from typing import IO, Any, Optional + +from .types import WSGIEnvironment + +class FileWrapper: + filelike: IO[bytes] + blksize: int + def __init__(self, filelike: IO[bytes], bklsize: int = ...) -> None: ... + def __getitem__(self, key: Any) -> bytes: ... + def __iter__(self) -> FileWrapper: ... + if sys.version_info < (3,): + def next(self) -> bytes: ... + else: + def __next__(self) -> bytes: ... + def close(self) -> None: ... # only exists if filelike.close exists + +def guess_scheme(environ: WSGIEnvironment) -> str: ... +def application_uri(environ: WSGIEnvironment) -> str: ... +def request_uri(environ: WSGIEnvironment, include_query: bool = ...) -> str: ... +def shift_path_info(environ: WSGIEnvironment) -> Optional[str]: ... +def setup_testing_defaults(environ: WSGIEnvironment) -> None: ... +def is_hop_by_hop(header_name: str) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/2and3/wsgiref/validate.pyi b/client/typeshed-fallback/stdlib/2and3/wsgiref/validate.pyi new file mode 100644 index 000000000..c7fa699fc --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/wsgiref/validate.pyi @@ -0,0 +1,53 @@ +import sys +from typing import Any, Iterable, Iterator, Optional, NoReturn, Callable + +from wsgiref.types import WSGIApplication, InputStream, ErrorStream + +class WSGIWarning(Warning): ... + +def validator(application: WSGIApplication) -> WSGIApplication: ... + +class InputWrapper: + input: InputStream + def __init__(self, wsgi_input: InputStream) -> None: ... + if sys.version_info < (3,): + def read(self, size: int = ...) -> bytes: ... + def readline(self) -> bytes: ... + else: + def read(self, size: int) -> bytes: ... + def readline(self, size: int = ...) -> bytes: ... + def readlines(self, hint: int = ...) -> bytes: ... + def __iter__(self) -> Iterable[bytes]: ... + def close(self) -> NoReturn: ... + +class ErrorWrapper: + errors: ErrorStream + def __init__(self, wsgi_errors: ErrorStream) -> None: ... + def write(self, s: str) -> None: ... + def flush(self) -> None: ... + def writelines(self, seq: Iterable[str]) -> None: ... + def close(self) -> NoReturn: ... + +class WriteWrapper: + writer: Callable[[bytes], Any] + def __init__(self, wsgi_writer: Callable[[bytes], Any]) -> None: ... + def __call__(self, s: bytes) -> None: ... + +class PartialIteratorWrapper: + iterator: Iterator[bytes] + def __init__(self, wsgi_iterator: Iterator[bytes]) -> None: ... + def __iter__(self) -> IteratorWrapper: ... + +class IteratorWrapper: + original_iterator: Iterator[bytes] + iterator: Iterator[bytes] + closed: bool + check_start_response: Optional[bool] + def __init__(self, wsgi_iterator: Iterator[bytes], check_start_response: Optional[bool]) -> None: ... + def __iter__(self) -> IteratorWrapper: ... + if sys.version_info < (3,): + def next(self) -> bytes: ... + else: + def __next__(self) -> bytes: ... + def close(self) -> None: ... + def __del__(self) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/xdrlib.pyi b/client/typeshed-fallback/stdlib/2and3/xdrlib.pyi new file mode 100644 index 000000000..bbdaa5802 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/xdrlib.pyi @@ -0,0 +1,56 @@ +# Structs for xdrlib (Python 2 and 3) +from typing import Callable, List, Sequence, TypeVar + +_T = TypeVar('_T') + +class Error(Exception): + msg = ... # type: str + def __init__(self, msg: str) -> None: ... + +class ConversionError(Error): ... + +class Packer: + def __init__(self) -> None: ... + def reset(self) -> None: ... + def get_buffer(self) -> bytes: ... + def get_buf(self) -> bytes: ... + def pack_uint(self, x: int) -> None: ... + def pack_int(self, x: int) -> None: ... + def pack_enum(self, x: int) -> None: ... + def pack_bool(self, x: bool) -> None: ... + def pack_uhyper(self, x: int) -> None: ... + def pack_hyper(self, x: int) -> None: ... + def pack_float(self, x: float) -> None: ... + def pack_double(self, x: float) -> None: ... + def pack_fstring(self, n: int, s: bytes) -> None: ... + def pack_fopaque(self, n: int, s: bytes) -> None: ... + def pack_string(self, s: bytes) -> None: ... + def pack_opaque(self, s: bytes) -> None: ... + def pack_bytes(self, s: bytes) -> None: ... + def pack_list(self, list: Sequence[_T], pack_item: Callable[[_T], None]) -> None: ... + def pack_farray(self, n: int, list: Sequence[_T], pack_item: Callable[[_T], None]) -> None: ... + def pack_array(self, list: Sequence[_T], pack_item: Callable[[_T], None]) -> None: ... + +class Unpacker: + def __init__(self, data: bytes) -> None: ... + def reset(self, data: bytes) -> None: ... + def get_position(self) -> int: ... + def set_position(self, position: int) -> None: ... + def get_buffer(self) -> bytes: ... + def done(self) -> None: ... + def unpack_uint(self) -> int: ... + def unpack_int(self) -> int: ... + def unpack_enum(self) -> int: ... + def unpack_bool(self) -> bool: ... + def unpack_uhyper(self) -> int: ... + def unpack_hyper(self) -> int: ... + def unpack_float(self) -> float: ... + def unpack_double(self) -> float: ... + def unpack_fstring(self, n: int) -> bytes: ... + def unpack_fopaque(self, n: int) -> bytes: ... + def unpack_string(self) -> bytes: ... + def unpack_opaque(self) -> bytes: ... + def unpack_bytes(self) -> bytes: ... + def unpack_list(self, unpack_item: Callable[[], _T]) -> List[_T]: ... + def unpack_farray(self, n: int, unpack_item: Callable[[], _T]) -> List[_T]: ... + def unpack_array(self, unpack_item: Callable[[], _T]) -> List[_T]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/xml/__init__.pyi b/client/typeshed-fallback/stdlib/2and3/xml/__init__.pyi new file mode 100644 index 000000000..c524ac2b1 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/xml/__init__.pyi @@ -0,0 +1 @@ +import xml.parsers as parsers diff --git a/client/typeshed-fallback/stdlib/2and3/xml/etree/ElementInclude.pyi b/client/typeshed-fallback/stdlib/2and3/xml/etree/ElementInclude.pyi new file mode 100644 index 000000000..9e79e01d1 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/xml/etree/ElementInclude.pyi @@ -0,0 +1,17 @@ +# Stubs for xml.etree.ElementInclude (Python 3.4) + +from typing import Union, Optional, Callable +from xml.etree.ElementTree import Element + +XINCLUDE = ... # type: str +XINCLUDE_INCLUDE = ... # type: str +XINCLUDE_FALLBACK = ... # type: str + +class FatalIncludeError(SyntaxError): ... + +def default_loader(href: Union[str, bytes, int], parse: str, encoding: Optional[str] = ...) -> Union[str, Element]: ... + +# TODO: loader is of type default_loader ie it takes a callable that has the +# same signature as default_loader. But default_loader has a keyword argument +# Which can't be represented using Callable... +def include(elem: Element, loader: Optional[Callable[..., Union[str, Element]]] = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/xml/etree/ElementPath.pyi b/client/typeshed-fallback/stdlib/2and3/xml/etree/ElementPath.pyi new file mode 100644 index 000000000..aa1227100 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/xml/etree/ElementPath.pyi @@ -0,0 +1,33 @@ +# Stubs for xml.etree.ElementPath (Python 3.4) + +from typing import Pattern, Dict, Generator, Tuple, List, Union, TypeVar, Callable, Optional +from xml.etree.ElementTree import Element + +xpath_tokenizer_re = ... # type: Pattern + +_token = Tuple[str, str] +_next = Callable[[], _token] +_callback = Callable[[_SelectorContext, List[Element]], Generator[Element, None, None]] + +def xpath_tokenizer(pattern: str, namespaces: Optional[Dict[str, str]] = ...) -> Generator[_token, None, None]: ... +def get_parent_map(context: _SelectorContext) -> Dict[Element, Element]: ... +def prepare_child(next: _next, token: _token) -> _callback: ... +def prepare_star(next: _next, token: _token) -> _callback: ... +def prepare_self(next: _next, token: _token) -> _callback: ... +def prepare_descendant(next: _next, token: _token) -> _callback: ... +def prepare_parent(next: _next, token: _token) -> _callback: ... +def prepare_predicate(next: _next, token: _token) -> _callback: ... + +ops = ... # type: Dict[str, Callable[[_next, _token], _callback]] + +class _SelectorContext: + parent_map = ... # type: Dict[Element, Element] + root = ... # type: Element + def __init__(self, root: Element) -> None: ... + +_T = TypeVar('_T') + +def iterfind(elem: Element, path: str, namespaces: Optional[Dict[str, str]] = ...) -> List[Element]: ... +def find(elem: Element, path: str, namespaces: Optional[Dict[str, str]] = ...) -> Optional[Element]: ... +def findall(elem: Element, path: str, namespaces: Optional[Dict[str, str]] = ...) -> List[Element]: ... +def findtext(elem: Element, path: str, default: Optional[_T] = ..., namespaces: Optional[Dict[str, str]] = ...) -> Union[_T, str]: ... diff --git a/client/typeshed-fallback/stdlib/2and3/xml/etree/ElementTree.pyi b/client/typeshed-fallback/stdlib/2and3/xml/etree/ElementTree.pyi new file mode 100644 index 000000000..db2df49ca --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/xml/etree/ElementTree.pyi @@ -0,0 +1,167 @@ +# Stubs for xml.etree.ElementTree + +from typing import Any, Callable, Dict, Generator, IO, ItemsView, Iterable, Iterator, KeysView, List, MutableSequence, Optional, overload, Sequence, Text, Tuple, TypeVar, Union +import io +import sys + +VERSION = ... # type: str + +class ParseError(SyntaxError): ... + +def iselement(element: object) -> bool: ... + +_T = TypeVar('_T') + +# Type for parser inputs. Parser will accept any unicode/str/bytes and coerce, +# and this is true in py2 and py3 (even fromstringlist() in python3 can be +# called with a heterogeneous list) +_parser_input_type = Union[bytes, Text] + +# Type for individual tag/attr/ns/text values in args to most functions. +# In py2, the library accepts str or unicode everywhere and coerces +# aggressively. +# In py3, bytes is not coerced to str and so use of bytes is probably an error, +# so we exclude it. (why? the parser never produces bytes when it parses XML, +# so e.g., element.get(b'name') will always return None for parsed XML, even if +# there is a 'name' attribute.) +_str_argument_type = Union[str, Text] + +# Type for return values from individual tag/attr/text values and serialization +if sys.version_info >= (3,): + # note: in python3, everything comes out as str, yay: + _str_result_type = str + # unfortunately, tostring and tostringlist can return either bytes or str + # depending on the value of `encoding` parameter. Client code knows best: + _tostring_result_type = Any +else: + # in python2, if the tag/attribute/text wasn't decode-able as ascii, it + # comes out as a unicode string; otherwise it comes out as str. (see + # _fixtext function in the source). Client code knows best: + _str_result_type = Any + # On the bright side, tostring and tostringlist always return bytes: + _tostring_result_type = bytes + +class Element(MutableSequence[Element]): + tag = ... # type: _str_result_type + attrib = ... # type: Dict[_str_result_type, _str_result_type] + text = ... # type: Optional[_str_result_type] + tail = ... # type: Optional[_str_result_type] + def __init__(self, tag: Union[_str_argument_type, Callable[..., Element]], attrib: Dict[_str_argument_type, _str_argument_type] = ..., **extra: _str_argument_type) -> None: ... + def append(self, subelement: Element) -> None: ... + def clear(self) -> None: ... + def copy(self) -> Element: ... + def extend(self, elements: Iterable[Element]) -> None: ... + def find(self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ...) -> Optional[Element]: ... + def findall(self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ...) -> List[Element]: ... + def findtext(self, path: _str_argument_type, default: Optional[_T] = ..., namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ...) -> Union[_T, _str_result_type]: ... + def get(self, key: _str_argument_type, default: Optional[_T] = ...) -> Union[_str_result_type, _T]: ... + def getchildren(self) -> List[Element]: ... + def getiterator(self, tag: Optional[_str_argument_type] = ...) -> List[Element]: ... + if sys.version_info >= (3, 2): + def insert(self, index: int, subelement: Element) -> None: ... + else: + def insert(self, index: int, element: Element) -> None: ... + def items(self) -> ItemsView[_str_result_type, _str_result_type]: ... + def iter(self, tag: Optional[_str_argument_type] = ...) -> Generator[Element, None, None]: ... + def iterfind(self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ...) -> List[Element]: ... + def itertext(self) -> Generator[_str_result_type, None, None]: ... + def keys(self) -> KeysView[_str_result_type]: ... + def makeelement(self, tag: _str_argument_type, attrib: Dict[_str_argument_type, _str_argument_type]) -> Element: ... + def remove(self, subelement: Element) -> None: ... + def set(self, key: _str_argument_type, value: _str_argument_type) -> None: ... + def __bool__(self) -> bool: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + @overload + def __getitem__(self, i: int) -> Element: ... + @overload + def __getitem__(self, s: slice) -> MutableSequence[Element]: ... + def __len__(self) -> int: ... + @overload + def __setitem__(self, i: int, o: Element) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[Element]) -> None: ... + + +def SubElement(parent: Element, tag: _str_argument_type, attrib: Dict[_str_argument_type, _str_argument_type] = ..., **extra: _str_argument_type) -> Element: ... +def Comment(text: Optional[_str_argument_type] = ...) -> Element: ... +def ProcessingInstruction(target: _str_argument_type, text: Optional[_str_argument_type] = ...) -> Element: ... + +PI = ... # type: Callable[..., Element] + +class QName: + text = ... # type: str + def __init__(self, text_or_uri: _str_argument_type, tag: Optional[_str_argument_type] = ...) -> None: ... + + +_file_or_filename = Union[str, bytes, int, IO[Any]] + +class ElementTree: + def __init__(self, element: Optional[Element] = ..., file: Optional[_file_or_filename] = ...) -> None: ... + def getroot(self) -> Element: ... + def parse(self, source: _file_or_filename, parser: Optional[XMLParser] = ...) -> Element: ... + def iter(self, tag: Optional[_str_argument_type] = ...) -> Generator[Element, None, None]: ... + def getiterator(self, tag: Optional[_str_argument_type] = ...) -> List[Element]: ... + def find(self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ...) -> Optional[Element]: ... + def findtext(self, path: _str_argument_type, default: Optional[_T] = ..., namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ...) -> Union[_T, _str_result_type]: ... + def findall(self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ...) -> List[Element]: ... + def iterfind(self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ...) -> List[Element]: ... + if sys.version_info >= (3, 4): + def write(self, file_or_filename: _file_or_filename, encoding: Optional[str] = ..., xml_declaration: Optional[bool] = ..., default_namespace: Optional[_str_argument_type] = ..., method: Optional[str] = ..., *, short_empty_elements: bool = ...) -> None: ... + else: + def write(self, file_or_filename: _file_or_filename, encoding: Optional[str] = ..., xml_declaration: Optional[bool] = ..., default_namespace: Optional[_str_argument_type] = ..., method: Optional[str] = ...) -> None: ... + def write_c14n(self, file: _file_or_filename) -> None: ... + +def register_namespace(prefix: _str_argument_type, uri: _str_argument_type) -> None: ... +if sys.version_info >= (3, 4): + def tostring(element: Element, encoding: Optional[str] = ..., method: Optional[str] = ..., *, short_empty_elements: bool = ...) -> _tostring_result_type: ... + def tostringlist(element: Element, encoding: Optional[str] = ..., method: Optional[str] = ..., *, short_empty_elements: bool = ...) -> List[_tostring_result_type]: ... +else: + def tostring(element: Element, encoding: Optional[str] = ..., method: Optional[str] = ...) -> _tostring_result_type: ... + def tostringlist(element: Element, encoding: Optional[str] = ..., method: Optional[str] = ...) -> List[_tostring_result_type]: ... +def dump(elem: Element) -> None: ... +def parse(source: _file_or_filename, parser: Optional[XMLParser] = ...) -> ElementTree: ... +def iterparse(source: _file_or_filename, events: Optional[Sequence[str]] = ..., parser: Optional[XMLParser] = ...) -> Iterator[Tuple[str, Any]]: ... + +if sys.version_info >= (3, 4): + class XMLPullParser: + def __init__(self, events: Optional[Sequence[str]] = ..., *, _parser: Optional[XMLParser] = ...) -> None: ... + def feed(self, data: bytes) -> None: ... + def close(self) -> None: ... + def read_events(self) -> Iterator[Tuple[str, Element]]: ... + +def XML(text: _parser_input_type, parser: Optional[XMLParser] = ...) -> Element: ... +def XMLID(text: _parser_input_type, parser: Optional[XMLParser] = ...) -> Tuple[Element, Dict[_str_result_type, Element]]: ... + +# This is aliased to XML in the source. +fromstring = XML + +def fromstringlist(sequence: Sequence[_parser_input_type], parser: Optional[XMLParser] = ...) -> Element: ... + +# This type is both not precise enough and too precise. The TreeBuilder +# requires the elementfactory to accept tag and attrs in its args and produce +# some kind of object that has .text and .tail properties. +# I've chosen to constrain the ElementFactory to always produce an Element +# because that is how almost everyone will use it. +# Unfortunately, the type of the factory arguments is dependent on how +# TreeBuilder is called by client code (they could pass strs, bytes or whatever); +# but we don't want to use a too-broad type, or it would be too hard to write +# elementfactories. +_ElementFactory = Callable[[Any, Dict[Any, Any]], Element] + +class TreeBuilder: + def __init__(self, element_factory: Optional[_ElementFactory] = ...) -> None: ... + def close(self) -> Element: ... + def data(self, data: _parser_input_type) -> None: ... + def start(self, tag: _parser_input_type, attrs: Dict[_parser_input_type, _parser_input_type]) -> Element: ... + def end(self, tag: _parser_input_type) -> Element: ... + +class XMLParser: + parser = ... # type: Any + target = ... # type: TreeBuilder + # TODO-what is entity used for??? + entity = ... # type: Any + version = ... # type: str + def __init__(self, html: int = ..., target: Optional[TreeBuilder] = ..., encoding: Optional[str] = ...) -> None: ... + def doctype(self, name: str, pubid: str, system: str) -> None: ... + def close(self) -> Element: ... + def feed(self, data: _parser_input_type) -> None: ... diff --git a/client/typeshed-fallback/stdlib/2and3/xml/etree/__init__.pyi b/client/typeshed-fallback/stdlib/2and3/xml/etree/__init__.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/2and3/xml/etree/cElementTree.pyi b/client/typeshed-fallback/stdlib/2and3/xml/etree/cElementTree.pyi new file mode 100644 index 000000000..c384968d0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/xml/etree/cElementTree.pyi @@ -0,0 +1,3 @@ +# Stubs for xml.etree.cElementTree (Python 3.4) + +from xml.etree.ElementTree import * # noqa: F403 diff --git a/client/typeshed-fallback/stdlib/2and3/xml/parsers/__init__.pyi b/client/typeshed-fallback/stdlib/2and3/xml/parsers/__init__.pyi new file mode 100644 index 000000000..cac086235 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/xml/parsers/__init__.pyi @@ -0,0 +1 @@ +import xml.parsers.expat as expat diff --git a/client/typeshed-fallback/stdlib/2and3/xml/parsers/expat/__init__.pyi b/client/typeshed-fallback/stdlib/2and3/xml/parsers/expat/__init__.pyi new file mode 100644 index 000000000..73f3758c6 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/xml/parsers/expat/__init__.pyi @@ -0,0 +1 @@ +from pyexpat import * diff --git a/client/typeshed-fallback/stdlib/2and3/xml/parsers/expat/errors.pyi b/client/typeshed-fallback/stdlib/2and3/xml/parsers/expat/errors.pyi new file mode 100644 index 000000000..e22d769ec --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/xml/parsers/expat/errors.pyi @@ -0,0 +1 @@ +from pyexpat.errors import * diff --git a/client/typeshed-fallback/stdlib/2and3/xml/parsers/expat/model.pyi b/client/typeshed-fallback/stdlib/2and3/xml/parsers/expat/model.pyi new file mode 100644 index 000000000..d8f44b47c --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/xml/parsers/expat/model.pyi @@ -0,0 +1 @@ +from pyexpat.model import * diff --git a/client/typeshed-fallback/stdlib/2and3/xml/sax/__init__.pyi b/client/typeshed-fallback/stdlib/2and3/xml/sax/__init__.pyi new file mode 100644 index 000000000..b694b43b8 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/xml/sax/__init__.pyi @@ -0,0 +1,34 @@ +from typing import Any, List, NoReturn, Optional, Text, Union, IO + +import xml.sax +from xml.sax.xmlreader import InputSource, Locator +from xml.sax.handler import ContentHandler, ErrorHandler + +class SAXException(Exception): + def __init__(self, msg: str, exception: Optional[Exception] = ...) -> None: ... + def getMessage(self) -> str: ... + def getException(self) -> Exception: ... + def __getitem__(self, ix: Any) -> NoReturn: ... + +class SAXParseException(SAXException): + def __init__(self, msg: str, exception: Exception, locator: Locator) -> None: ... + def getColumnNumber(self) -> int: ... + def getLineNumber(self) -> int: ... + def getPublicId(self): ... + def getSystemId(self): ... + +class SAXNotRecognizedException(SAXException): ... +class SAXNotSupportedException(SAXException): ... +class SAXReaderNotAvailable(SAXNotSupportedException): ... + +default_parser_list = ... # type: List[str] + +def make_parser(parser_list: List[str] = ...) -> xml.sax.xmlreader.XMLReader: ... + +def parse(source: Union[str, IO[str]], handler: xml.sax.handler.ContentHandler, + errorHandler: xml.sax.handler.ErrorHandler = ...) -> None: ... + +def parseString(string: Union[bytes, Text], handler: xml.sax.handler.ContentHandler, + errorHandler: Optional[xml.sax.handler.ErrorHandler] = ...) -> None: ... + +def _create_parser(parser_name: str) -> xml.sax.xmlreader.XMLReader: ... diff --git a/client/typeshed-fallback/stdlib/2and3/xml/sax/handler.pyi b/client/typeshed-fallback/stdlib/2and3/xml/sax/handler.pyi new file mode 100644 index 000000000..0b549b987 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/xml/sax/handler.pyi @@ -0,0 +1,46 @@ +from typing import Any + +version = ... # type: Any + +class ErrorHandler: + def error(self, exception): ... + def fatalError(self, exception): ... + def warning(self, exception): ... + +class ContentHandler: + def __init__(self) -> None: ... + def setDocumentLocator(self, locator): ... + def startDocument(self): ... + def endDocument(self): ... + def startPrefixMapping(self, prefix, uri): ... + def endPrefixMapping(self, prefix): ... + def startElement(self, name, attrs): ... + def endElement(self, name): ... + def startElementNS(self, name, qname, attrs): ... + def endElementNS(self, name, qname): ... + def characters(self, content): ... + def ignorableWhitespace(self, whitespace): ... + def processingInstruction(self, target, data): ... + def skippedEntity(self, name): ... + +class DTDHandler: + def notationDecl(self, name, publicId, systemId): ... + def unparsedEntityDecl(self, name, publicId, systemId, ndata): ... + +class EntityResolver: + def resolveEntity(self, publicId, systemId): ... + +feature_namespaces = ... # type: Any +feature_namespace_prefixes = ... # type: Any +feature_string_interning = ... # type: Any +feature_validation = ... # type: Any +feature_external_ges = ... # type: Any +feature_external_pes = ... # type: Any +all_features = ... # type: Any +property_lexical_handler = ... # type: Any +property_declaration_handler = ... # type: Any +property_dom_node = ... # type: Any +property_xml_string = ... # type: Any +property_encoding = ... # type: Any +property_interning_dict = ... # type: Any +all_properties = ... # type: Any diff --git a/client/typeshed-fallback/stdlib/2and3/xml/sax/saxutils.pyi b/client/typeshed-fallback/stdlib/2and3/xml/sax/saxutils.pyi new file mode 100644 index 000000000..342d6ed84 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/xml/sax/saxutils.pyi @@ -0,0 +1,58 @@ +import sys +from typing import Mapping, Text + +from xml.sax import handler +from xml.sax import xmlreader + +def escape(data: Text, entities: Mapping[Text, Text] = ...) -> Text: ... +def unescape(data: Text, entities: Mapping[Text, Text] = ...) -> Text: ... +def quoteattr(data: Text, entities: Mapping[Text, Text] = ...) -> Text: ... + +class XMLGenerator(handler.ContentHandler): + if sys.version_info >= (3, 0): + def __init__(self, out=..., encoding=..., short_empty_elements: bool = ...) -> None: ... + else: + def __init__(self, out=..., encoding=...) -> None: ... + def startDocument(self): ... + def endDocument(self): ... + def startPrefixMapping(self, prefix, uri): ... + def endPrefixMapping(self, prefix): ... + def startElement(self, name, attrs): ... + def endElement(self, name): ... + def startElementNS(self, name, qname, attrs): ... + def endElementNS(self, name, qname): ... + def characters(self, content): ... + def ignorableWhitespace(self, content): ... + def processingInstruction(self, target, data): ... + +class XMLFilterBase(xmlreader.XMLReader): + def __init__(self, parent=...) -> None: ... + def error(self, exception): ... + def fatalError(self, exception): ... + def warning(self, exception): ... + def setDocumentLocator(self, locator): ... + def startDocument(self): ... + def endDocument(self): ... + def startPrefixMapping(self, prefix, uri): ... + def endPrefixMapping(self, prefix): ... + def startElement(self, name, attrs): ... + def endElement(self, name): ... + def startElementNS(self, name, qname, attrs): ... + def endElementNS(self, name, qname): ... + def characters(self, content): ... + def ignorableWhitespace(self, chars): ... + def processingInstruction(self, target, data): ... + def skippedEntity(self, name): ... + def notationDecl(self, name, publicId, systemId): ... + def unparsedEntityDecl(self, name, publicId, systemId, ndata): ... + def resolveEntity(self, publicId, systemId): ... + def parse(self, source): ... + def setLocale(self, locale): ... + def getFeature(self, name): ... + def setFeature(self, name, state): ... + def getProperty(self, name): ... + def setProperty(self, name, value): ... + def getParent(self): ... + def setParent(self, parent): ... + +def prepare_input_source(source, base=...): ... diff --git a/client/typeshed-fallback/stdlib/2and3/xml/sax/xmlreader.pyi b/client/typeshed-fallback/stdlib/2and3/xml/sax/xmlreader.pyi new file mode 100644 index 000000000..fbc1ac1ef --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/xml/sax/xmlreader.pyi @@ -0,0 +1,71 @@ +class XMLReader: + def __init__(self) -> None: ... + def parse(self, source): ... + def getContentHandler(self): ... + def setContentHandler(self, handler): ... + def getDTDHandler(self): ... + def setDTDHandler(self, handler): ... + def getEntityResolver(self): ... + def setEntityResolver(self, resolver): ... + def getErrorHandler(self): ... + def setErrorHandler(self, handler): ... + def setLocale(self, locale): ... + def getFeature(self, name): ... + def setFeature(self, name, state): ... + def getProperty(self, name): ... + def setProperty(self, name, value): ... + +class IncrementalParser(XMLReader): + def __init__(self, bufsize=...) -> None: ... + def parse(self, source): ... + def feed(self, data): ... + def prepareParser(self, source): ... + def close(self): ... + def reset(self): ... + +class Locator: + def getColumnNumber(self): ... + def getLineNumber(self): ... + def getPublicId(self): ... + def getSystemId(self): ... + +class InputSource: + def __init__(self, system_id=...) -> None: ... + def setPublicId(self, public_id): ... + def getPublicId(self): ... + def setSystemId(self, system_id): ... + def getSystemId(self): ... + def setEncoding(self, encoding): ... + def getEncoding(self): ... + def setByteStream(self, bytefile): ... + def getByteStream(self): ... + def setCharacterStream(self, charfile): ... + def getCharacterStream(self): ... + +class AttributesImpl: + def __init__(self, attrs) -> None: ... + def getLength(self): ... + def getType(self, name): ... + def getValue(self, name): ... + def getValueByQName(self, name): ... + def getNameByQName(self, name): ... + def getQNameByName(self, name): ... + def getNames(self): ... + def getQNames(self): ... + def __len__(self): ... + def __getitem__(self, name): ... + def keys(self): ... + def has_key(self, name): ... + def __contains__(self, name): ... + def get(self, name, alternative=...): ... + def copy(self): ... + def items(self): ... + def values(self): ... + +class AttributesNSImpl(AttributesImpl): + def __init__(self, attrs, qnames) -> None: ... + def getValueByQName(self, name): ... + def getNameByQName(self, name): ... + def getQNameByName(self, name): ... + def getQNames(self): ... + def copy(self): ... diff --git a/client/typeshed-fallback/stdlib/2and3/zipfile.pyi b/client/typeshed-fallback/stdlib/2and3/zipfile.pyi new file mode 100644 index 000000000..a85d1c5ee --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/zipfile.pyi @@ -0,0 +1,105 @@ +# Stubs for zipfile + +from typing import Callable, Dict, IO, Iterable, List, Optional, Text, Tuple, Type, Union +from types import TracebackType +import os +import sys + + +if sys.version_info >= (3, 6): + _Path = Union[os.PathLike[Text], Text] +else: + _Path = Text +_SZI = Union[Text, ZipInfo] +_DT = Tuple[int, int, int, int, int, int] + + +if sys.version_info >= (3,): + class BadZipFile(Exception): ... + BadZipfile = BadZipFile +else: + class BadZipfile(Exception): ... +error = BadZipfile + +class LargeZipFile(Exception): ... + +class ZipFile: + debug = ... # type: int + comment = ... # type: bytes + filelist = ... # type: List[ZipInfo] + fp = ... # type: IO[bytes] + NameToInfo = ... # type: Dict[Text, ZipInfo] + def __init__(self, file: Union[_Path, IO[bytes]], mode: Text = ..., compression: int = ..., + allowZip64: bool = ...) -> None: ... + def __enter__(self) -> ZipFile: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType]) -> bool: ... + def close(self) -> None: ... + def getinfo(self, name: Text) -> ZipInfo: ... + def infolist(self) -> List[ZipInfo]: ... + def namelist(self) -> List[Text]: ... + def open(self, name: _SZI, mode: Text = ..., + pwd: Optional[bytes] = ...) -> IO[bytes]: ... + def extract(self, member: _SZI, path: Optional[_SZI] = ..., + pwd: bytes = ...) -> str: ... + def extractall(self, path: Optional[_Path] = ..., + members: Optional[Iterable[Text]] = ..., + pwd: Optional[bytes] = ...) -> None: ... + def printdir(self) -> None: ... + def setpassword(self, pwd: bytes) -> None: ... + def read(self, name: _SZI, pwd: Optional[bytes] = ...) -> bytes: ... + def testzip(self) -> Optional[str]: ... + def write(self, filename: _Path, arcname: Optional[_Path] = ..., + compress_type: Optional[int] = ...) -> None: ... + if sys.version_info >= (3,): + def writestr(self, zinfo_or_arcname: _SZI, data: Union[bytes, str], + compress_type: Optional[int] = ...) -> None: ... + else: + def writestr(self, + zinfo_or_arcname: _SZI, bytes: bytes, + compress_type: Optional[int] = ...) -> None: ... + +class PyZipFile(ZipFile): + if sys.version_info >= (3,): + def __init__(self, file: Union[str, IO[bytes]], mode: str = ..., + compression: int = ..., allowZip64: bool = ..., + opimize: int = ...) -> None: ... + def writepy(self, pathname: str, basename: str = ..., + filterfunc: Optional[Callable[[str], bool]] = ...) -> None: ... + else: + def writepy(self, + pathname: Text, basename: Text = ...) -> None: ... + +class ZipInfo: + filename = ... # type: Text + date_time = ... # type: _DT + compress_type = ... # type: int + comment = ... # type: bytes + extra = ... # type: bytes + create_system = ... # type: int + create_version = ... # type: int + extract_version = ... # type: int + reserved = ... # type: int + flag_bits = ... # type: int + volume = ... # type: int + internal_attr = ... # type: int + external_attr = ... # type: int + header_offset = ... # type: int + CRC = ... # type: int + compress_size = ... # type: int + file_size = ... # type: int + def __init__(self, filename: Optional[Text] = ..., + date_time: Optional[_DT] = ...) -> None: ... + if sys.version_info >= (3, 6): + def is_dir(self) -> bool: ... + def FileHeader(self, zip64: Optional[bool] = ...) -> bytes: ... + + +def is_zipfile(filename: Union[_Path, IO[bytes]]) -> bool: ... + +ZIP_STORED = ... # type: int +ZIP_DEFLATED = ... # type: int +if sys.version_info >= (3, 3): + ZIP_BZIP2 = ... # type: int + ZIP_LZMA = ... # type: int diff --git a/client/typeshed-fallback/stdlib/2and3/zipimport.pyi b/client/typeshed-fallback/stdlib/2and3/zipimport.pyi new file mode 100644 index 000000000..eb70eb307 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/zipimport.pyi @@ -0,0 +1,18 @@ +"""Stub file for the 'zipimport' module.""" + +from typing import Optional +from types import CodeType, ModuleType + +class ZipImportError(ImportError): ... + +class zipimporter(object): + archive = ... # type: str + prefix = ... # type: str + def __init__(self, archivepath: str) -> None: ... + def find_module(self, fullname: str, path: str = ...) -> Optional[zipimporter]: ... + def get_code(self, fullname: str) -> CodeType: ... + def get_data(self, pathname: str) -> str: ... + def get_filename(self, fullname: str) -> str: ... + def get_source(self, fullname: str) -> Optional[str]: ... + def is_package(self, fullname: str) -> bool: ... + def load_module(self, fullname: str) -> ModuleType: ... diff --git a/client/typeshed-fallback/stdlib/2and3/zlib.pyi b/client/typeshed-fallback/stdlib/2and3/zlib.pyi new file mode 100644 index 000000000..3300f5166 --- /dev/null +++ b/client/typeshed-fallback/stdlib/2and3/zlib.pyi @@ -0,0 +1,55 @@ +# Stubs for zlib +import sys + +DEFLATED = ... # type: int +DEF_MEM_LEVEL = ... # type: int +MAX_WBITS = ... # type: int +ZLIB_VERSION = ... # type: str +Z_BEST_COMPRESSION = ... # type: int +Z_BEST_SPEED = ... # type: int +Z_DEFAULT_COMPRESSION = ... # type: int +Z_DEFAULT_STRATEGY = ... # type: int +Z_FILTERED = ... # type: int +Z_FINISH = ... # type: int +Z_FULL_FLUSH = ... # type: int +Z_HUFFMAN_ONLY = ... # type: int +Z_NO_FLUSH = ... # type: int +Z_SYNC_FLUSH = ... # type: int +if sys.version_info >= (3,): + DEF_BUF_SIZE = ... # type: int + ZLIB_RUNTIME_VERSION = ... # type: str + +class error(Exception): ... + + +class _Compress: + def compress(self, data: bytes) -> bytes: ... + def flush(self, mode: int = ...) -> bytes: ... + def copy(self) -> _Compress: ... + + +class _Decompress: + unused_data = ... # type: bytes + unconsumed_tail = ... # type: bytes + if sys.version_info >= (3,): + eof = ... # type: bool + def decompress(self, data: bytes, max_length: int = ...) -> bytes: ... + def flush(self, length: int = ...) -> bytes: ... + def copy(self) -> _Decompress: ... + + +def adler32(data: bytes, value: int = ...) -> int: ... +def compress(data: bytes, level: int = ...) -> bytes: ... +if sys.version_info >= (3,): + def compressobj(level: int = ..., method: int = ..., wbits: int = ..., + memLevel: int = ..., strategy: int = ..., + zdict: bytes = ...) -> _Compress: ... +else: + def compressobj(level: int = ..., method: int = ..., wbits: int = ..., + memlevel: int = ..., strategy: int = ...) -> _Compress: ... +def crc32(data: bytes, value: int = ...) -> int: ... +def decompress(data: bytes, wbits: int = ..., bufsize: int = ...) -> bytes: ... +if sys.version_info >= (3,): + def decompressobj(wbits: int = ..., zdict: bytes = ...) -> _Decompress: ... +else: + def decompressobj(wbits: int = ...) -> _Decompress: ... diff --git a/client/typeshed-fallback/stdlib/3.5/zipapp.pyi b/client/typeshed-fallback/stdlib/3.5/zipapp.pyi new file mode 100644 index 000000000..b90b7559c --- /dev/null +++ b/client/typeshed-fallback/stdlib/3.5/zipapp.pyi @@ -0,0 +1,16 @@ +# Stubs for zipapp (Python 3.5+) + +from pathlib import Path +import sys +from typing import BinaryIO, Callable, Optional, Union + +_Path = Union[str, Path, BinaryIO] + +class ZipAppError(Exception): ... + +if sys.version_info >= (3, 7): + def create_archive(source: _Path, target: Optional[_Path] = ..., interpreter: Optional[str] = ..., main: Optional[str] = ..., + filter: Optional[Callable[[Path], bool]] = ..., compressed: bool = ...) -> None: ... +else: + def create_archive(source: _Path, target: Optional[_Path] = ..., interpreter: Optional[str] = ..., main: Optional[str] = ...) -> None: ... +def get_interpreter(archive: _Path) -> str: ... diff --git a/client/typeshed-fallback/stdlib/3.6/secrets.pyi b/client/typeshed-fallback/stdlib/3.6/secrets.pyi new file mode 100644 index 000000000..5069dba25 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3.6/secrets.pyi @@ -0,0 +1,14 @@ +# Stubs for secrets (Python 3.6) + +from typing import Optional, Sequence, TypeVar +from hmac import compare_digest as compare_digest +from random import SystemRandom as SystemRandom + +_T = TypeVar('_T') + +def randbelow(exclusive_upper_bound: int) -> int: ... +def randbits(k: int) -> int: ... +def choice(seq: Sequence[_T]) -> _T: ... +def token_bytes(nbytes: Optional[int] = ...) -> bytes: ... +def token_hex(nbytes: Optional[int] = ...) -> str: ... +def token_urlsafe(nbytes: Optional[int] = ...) -> str: ... diff --git a/client/typeshed-fallback/stdlib/3.7/contextvars.pyi b/client/typeshed-fallback/stdlib/3.7/contextvars.pyi new file mode 100644 index 000000000..ab2ae9e5f --- /dev/null +++ b/client/typeshed-fallback/stdlib/3.7/contextvars.pyi @@ -0,0 +1,30 @@ +from typing import Any, Callable, ClassVar, Generic, Iterator, Mapping, TypeVar, Union + +_T = TypeVar('_T') + +class ContextVar(Generic[_T]): + def __init__(self, name: str, *, default: _T = ...) -> None: ... + @property + def name(self) -> str: ... + def get(self, default: _T = ...) -> _T: ... + def set(self, value: _T) -> Token[_T]: ... + def reset(self, token: Token[_T]) -> None: ... + +class Token(Generic[_T]): + @property + def var(self) -> ContextVar[_T]: ... + @property + def old_value(self) -> Any: ... # returns either _T or MISSING, but that's hard to express + MISSING: ClassVar[object] + +def copy_context() -> Context: ... + +# It doesn't make sense to make this generic, because for most Contexts each ContextVar will have +# a different value. +class Context(Mapping[ContextVar[Any], Any]): + def __init__(self) -> None: ... + def run(self, callable: Callable[..., _T], *args: Any, **kwargs: Any) -> _T: ... + def copy(self) -> Context: ... + def __getitem__(self, key: ContextVar[Any]) -> Any: ... + def __iter__(self) -> Iterator[ContextVar[Any]]: ... + def __len__(self) -> int: ... diff --git a/client/typeshed-fallback/stdlib/3.7/dataclasses.pyi b/client/typeshed-fallback/stdlib/3.7/dataclasses.pyi new file mode 100644 index 000000000..f8bcd5263 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3.7/dataclasses.pyi @@ -0,0 +1,71 @@ +from typing import overload, Any, Callable, Dict, Generic, Iterable, List, Mapping, Optional, Tuple, Type, TypeVar, Union + + +_T = TypeVar('_T') + +class _MISSING_TYPE: ... +MISSING: _MISSING_TYPE + +@overload +def asdict(obj: Any) -> Dict[str, Any]: ... +@overload +def asdict(obj: Any, *, dict_factory: Callable[[List[Tuple[str, Any]]], _T]) -> _T: ... + +@overload +def astuple(obj: Any) -> Tuple[Any, ...]: ... +@overload +def astuple(obj: Any, *, tuple_factory: Callable[[List[Any]], _T]) -> _T: ... + + +@overload +def dataclass(_cls: Type[_T]) -> Type[_T]: ... + +@overload +def dataclass(*, init: bool = ..., repr: bool = ..., eq: bool = ..., order: bool = ..., + unsafe_hash: bool = ..., frozen: bool = ...) -> Callable[[Type[_T]], Type[_T]]: ... + + +class Field(Generic[_T]): + name: str + type: Type[_T] + default: _T + default_factory: Callable[[], _T] + repr: bool + hash: Optional[bool] + init: bool + compare: bool + metadata: Optional[Mapping[str, Any]] + + +# NOTE: Actual return type is 'Field[_T]', but we want to help type checkers +# to understand the magic that happens at runtime. +@overload # `default` and `default_factory` are optional and mutually exclusive. +def field(*, default: _T, + init: bool = ..., repr: bool = ..., hash: Optional[bool] = ..., compare: bool = ..., + metadata: Optional[Mapping[str, Any]] = ...) -> _T: ... + +@overload +def field(*, default_factory: Callable[[], _T], + init: bool = ..., repr: bool = ..., hash: Optional[bool] = ..., compare: bool = ..., + metadata: Optional[Mapping[str, Any]] = ...) -> _T: ... + +@overload +def field(*, + init: bool = ..., repr: bool = ..., hash: Optional[bool] = ..., compare: bool = ..., + metadata: Optional[Mapping[str, Any]] = ...) -> Any: ... + + +def fields(class_or_instance: Any) -> Tuple[Field[Any], ...]: ... + +def is_dataclass(obj: Any) -> bool: ... + +class FrozenInstanceError(AttributeError): ... + +class InitVar(Generic[_T]): ... + +def make_dataclass(cls_name: str, fields: Iterable[Union[str, Tuple[str, type], Tuple[str, type, Field[Any]]]], *, + bases: Tuple[type, ...] = ..., namespace: Optional[Dict[str, Any]] = ..., + init: bool = ..., repr: bool = ..., eq: bool = ..., order: bool = ..., hash: bool = ..., + frozen: bool = ...): ... + +def replace(obj: _T, **changes: Any) -> _T: ... diff --git a/client/typeshed-fallback/stdlib/3/_ast.pyi b/client/typeshed-fallback/stdlib/3/_ast.pyi new file mode 100644 index 000000000..084b6be64 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/_ast.pyi @@ -0,0 +1,378 @@ +import sys +import typing +from typing import Any, Optional, ClassVar + +PyCF_ONLY_AST = ... # type: int + +_identifier = str + +class AST: + _attributes: ClassVar[typing.Tuple[str, ...]] + _fields: ClassVar[typing.Tuple[str, ...]] + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + lineno: int + col_offset: int + +class mod(AST): + ... + +class Module(mod): + body = ... # type: typing.List[stmt] + if sys.version_info >= (3, 7): + docstring: Optional[str] + +class Interactive(mod): + body = ... # type: typing.List[stmt] + +class Expression(mod): + body = ... # type: expr + +class Suite(mod): + body = ... # type: typing.List[stmt] + + +class stmt(AST): ... + +class FunctionDef(stmt): + name = ... # type: _identifier + args = ... # type: arguments + body = ... # type: typing.List[stmt] + decorator_list = ... # type: typing.List[expr] + returns = ... # type: Optional[expr] + if sys.version_info >= (3, 7): + docstring: Optional[str] + +class AsyncFunctionDef(stmt): + name = ... # type: _identifier + args = ... # type: arguments + body = ... # type: typing.List[stmt] + decorator_list = ... # type: typing.List[expr] + returns = ... # type: Optional[expr] + if sys.version_info >= (3, 7): + docstring: Optional[str] + +class ClassDef(stmt): + name = ... # type: _identifier + bases = ... # type: typing.List[expr] + keywords = ... # type: typing.List[keyword] + body = ... # type: typing.List[stmt] + decorator_list = ... # type: typing.List[expr] + if sys.version_info >= (3, 7): + docstring: Optional[str] + +class Return(stmt): + value = ... # type: Optional[expr] + +class Delete(stmt): + targets = ... # type: typing.List[expr] + +class Assign(stmt): + targets = ... # type: typing.List[expr] + value = ... # type: expr + +class AugAssign(stmt): + target = ... # type: expr + op = ... # type: operator + value = ... # type: expr + +if sys.version_info >= (3, 6): + class AnnAssign(stmt): + target = ... # type: expr + annotation = ... # type: expr + value = ... # type: Optional[expr] + simple = ... # type: int + +class For(stmt): + target = ... # type: expr + iter = ... # type: expr + body = ... # type: typing.List[stmt] + orelse = ... # type: typing.List[stmt] + +class AsyncFor(stmt): + target = ... # type: expr + iter = ... # type: expr + body = ... # type: typing.List[stmt] + orelse = ... # type: typing.List[stmt] + +class While(stmt): + test = ... # type: expr + body = ... # type: typing.List[stmt] + orelse = ... # type: typing.List[stmt] + +class If(stmt): + test = ... # type: expr + body = ... # type: typing.List[stmt] + orelse = ... # type: typing.List[stmt] + +class With(stmt): + items = ... # type: typing.List[withitem] + body = ... # type: typing.List[stmt] + +class AsyncWith(stmt): + items = ... # type: typing.List[withitem] + body = ... # type: typing.List[stmt] + +class Raise(stmt): + exc = ... # type: Optional[expr] + cause = ... # type: Optional[expr] + +class Try(stmt): + body = ... # type: typing.List[stmt] + handlers = ... # type: typing.List[ExceptHandler] + orelse = ... # type: typing.List[stmt] + finalbody = ... # type: typing.List[stmt] + +class Assert(stmt): + test = ... # type: expr + msg = ... # type: Optional[expr] + +class Import(stmt): + names = ... # type: typing.List[alias] + +class ImportFrom(stmt): + module = ... # type: Optional[_identifier] + names = ... # type: typing.List[alias] + level = ... # type: int + +class Global(stmt): + names = ... # type: typing.List[_identifier] + +class Nonlocal(stmt): + names = ... # type: typing.List[_identifier] + +class Expr(stmt): + value = ... # type: expr + +class Pass(stmt): ... +class Break(stmt): ... +class Continue(stmt): ... + + +class slice(AST): + ... + +_slice = slice # this lets us type the variable named 'slice' below + +class Slice(slice): + lower = ... # type: Optional[expr] + upper = ... # type: Optional[expr] + step = ... # type: Optional[expr] + +class ExtSlice(slice): + dims = ... # type: typing.List[slice] + +class Index(slice): + value = ... # type: expr + + +class expr(AST): ... + +class BoolOp(expr): + op = ... # type: boolop + values = ... # type: typing.List[expr] + +class BinOp(expr): + left = ... # type: expr + op = ... # type: operator + right = ... # type: expr + +class UnaryOp(expr): + op = ... # type: unaryop + operand = ... # type: expr + +class Lambda(expr): + args = ... # type: arguments + body = ... # type: expr + +class IfExp(expr): + test = ... # type: expr + body = ... # type: expr + orelse = ... # type: expr + +class Dict(expr): + keys = ... # type: typing.List[expr] + values = ... # type: typing.List[expr] + +class Set(expr): + elts = ... # type: typing.List[expr] + +class ListComp(expr): + elt = ... # type: expr + generators = ... # type: typing.List[comprehension] + +class SetComp(expr): + elt = ... # type: expr + generators = ... # type: typing.List[comprehension] + +class DictComp(expr): + key = ... # type: expr + value = ... # type: expr + generators = ... # type: typing.List[comprehension] + +class GeneratorExp(expr): + elt = ... # type: expr + generators = ... # type: typing.List[comprehension] + +class Await(expr): + value = ... # type: expr + +class Yield(expr): + value = ... # type: Optional[expr] + +class YieldFrom(expr): + value = ... # type: expr + +class Compare(expr): + left = ... # type: expr + ops = ... # type: typing.List[cmpop] + comparators = ... # type: typing.List[expr] + +class Call(expr): + func = ... # type: expr + args = ... # type: typing.List[expr] + keywords = ... # type: typing.List[keyword] + +class Num(expr): + n = ... # type: float + +class Str(expr): + s = ... # type: str + +if sys.version_info >= (3, 6): + class FormattedValue(expr): + value = ... # type: expr + conversion = ... # type: Optional[int] + format_spec = ... # type: Optional[expr] + + class JoinedStr(expr): + values = ... # type: typing.List[expr] + +class Bytes(expr): + s = ... # type: bytes + +class NameConstant(expr): + value = ... # type: Any + +class Ellipsis(expr): ... + +class Attribute(expr): + value = ... # type: expr + attr = ... # type: _identifier + ctx = ... # type: expr_context + +class Subscript(expr): + value = ... # type: expr + slice = ... # type: _slice + ctx = ... # type: expr_context + +class Starred(expr): + value = ... # type: expr + ctx = ... # type: expr_context + +class Name(expr): + id = ... # type: _identifier + ctx = ... # type: expr_context + +class List(expr): + elts = ... # type: typing.List[expr] + ctx = ... # type: expr_context + +class Tuple(expr): + elts = ... # type: typing.List[expr] + ctx = ... # type: expr_context + + +class expr_context(AST): + ... + +class AugLoad(expr_context): ... +class AugStore(expr_context): ... +class Del(expr_context): ... +class Load(expr_context): ... +class Param(expr_context): ... +class Store(expr_context): ... + + +class boolop(AST): + ... + +class And(boolop): ... +class Or(boolop): ... + +class operator(AST): + ... + +class Add(operator): ... +class BitAnd(operator): ... +class BitOr(operator): ... +class BitXor(operator): ... +class Div(operator): ... +class FloorDiv(operator): ... +class LShift(operator): ... +class Mod(operator): ... +class Mult(operator): ... +class MatMult(operator): ... +class Pow(operator): ... +class RShift(operator): ... +class Sub(operator): ... + +class unaryop(AST): + ... + +class Invert(unaryop): ... +class Not(unaryop): ... +class UAdd(unaryop): ... +class USub(unaryop): ... + +class cmpop(AST): + ... + +class Eq(cmpop): ... +class Gt(cmpop): ... +class GtE(cmpop): ... +class In(cmpop): ... +class Is(cmpop): ... +class IsNot(cmpop): ... +class Lt(cmpop): ... +class LtE(cmpop): ... +class NotEq(cmpop): ... +class NotIn(cmpop): ... + + +class comprehension(AST): + target = ... # type: expr + iter = ... # type: expr + ifs = ... # type: typing.List[expr] + if sys.version_info >= (3, 6): + is_async = ... # type: int + + +class ExceptHandler(AST): + type = ... # type: Optional[expr] + name = ... # type: Optional[_identifier] + body = ... # type: typing.List[stmt] + + +class arguments(AST): + args = ... # type: typing.List[arg] + vararg = ... # type: Optional[arg] + kwonlyargs = ... # type: typing.List[arg] + kw_defaults = ... # type: typing.List[expr] + kwarg = ... # type: Optional[arg] + defaults = ... # type: typing.List[expr] + +class arg(AST): + arg = ... # type: _identifier + annotation = ... # type: Optional[expr] + +class keyword(AST): + arg = ... # type: Optional[_identifier] + value = ... # type: expr + +class alias(AST): + name = ... # type: _identifier + asname = ... # type: Optional[_identifier] + +class withitem(AST): + context_expr = ... # type: expr + optional_vars = ... # type: Optional[expr] diff --git a/client/typeshed-fallback/stdlib/3/_compression.pyi b/client/typeshed-fallback/stdlib/3/_compression.pyi new file mode 100644 index 000000000..d46efa13b --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/_compression.pyi @@ -0,0 +1,16 @@ +from typing import Any +import io + +BUFFER_SIZE = ... # type: Any + +class BaseStream(io.BufferedIOBase): ... + +class DecompressReader(io.RawIOBase): + def readable(self): ... + def __init__(self, fp, decomp_factory, trailing_error=..., **decomp_args): ... + def close(self): ... + def seekable(self): ... + def readinto(self, b): ... + def read(self, size: int = ...): ... + def seek(self, offset, whence=...): ... + def tell(self): ... diff --git a/client/typeshed-fallback/stdlib/3/_curses.pyi b/client/typeshed-fallback/stdlib/3/_curses.pyi new file mode 100644 index 000000000..11b1474d2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/_curses.pyi @@ -0,0 +1,447 @@ +from typing import Any, BinaryIO, IO, Optional, Tuple, Union, overload + +_chtype = Union[str, bytes, int] + +ALL_MOUSE_EVENTS = ... # type: int +A_ALTCHARSET = ... # type: int +A_ATTRIBUTES = ... # type: int +A_BLINK = ... # type: int +A_BOLD = ... # type: int +A_CHARTEXT = ... # type: int +A_COLOR = ... # type: int +A_DIM = ... # type: int +A_HORIZONTAL = ... # type: int +A_INVIS = ... # type: int +A_LEFT = ... # type: int +A_LOW = ... # type: int +A_NORMAL = ... # type: int +A_PROTECT = ... # type: int +A_REVERSE = ... # type: int +A_RIGHT = ... # type: int +A_STANDOUT = ... # type: int +A_TOP = ... # type: int +A_UNDERLINE = ... # type: int +A_VERTICAL = ... # type: int +BUTTON1_CLICKED = ... # type: int +BUTTON1_DOUBLE_CLICKED = ... # type: int +BUTTON1_PRESSED = ... # type: int +BUTTON1_RELEASED = ... # type: int +BUTTON1_TRIPLE_CLICKED = ... # type: int +BUTTON2_CLICKED = ... # type: int +BUTTON2_DOUBLE_CLICKED = ... # type: int +BUTTON2_PRESSED = ... # type: int +BUTTON2_RELEASED = ... # type: int +BUTTON2_TRIPLE_CLICKED = ... # type: int +BUTTON3_CLICKED = ... # type: int +BUTTON3_DOUBLE_CLICKED = ... # type: int +BUTTON3_PRESSED = ... # type: int +BUTTON3_RELEASED = ... # type: int +BUTTON3_TRIPLE_CLICKED = ... # type: int +BUTTON4_CLICKED = ... # type: int +BUTTON4_DOUBLE_CLICKED = ... # type: int +BUTTON4_PRESSED = ... # type: int +BUTTON4_RELEASED = ... # type: int +BUTTON4_TRIPLE_CLICKED = ... # type: int +BUTTON_ALT = ... # type: int +BUTTON_CTRL = ... # type: int +BUTTON_SHIFT = ... # type: int +COLOR_BLACK = ... # type: int +COLOR_BLUE = ... # type: int +COLOR_CYAN = ... # type: int +COLOR_GREEN = ... # type: int +COLOR_MAGENTA = ... # type: int +COLOR_RED = ... # type: int +COLOR_WHITE = ... # type: int +COLOR_YELLOW = ... # type: int +ERR = ... # type: int +KEY_A1 = ... # type: int +KEY_A3 = ... # type: int +KEY_B2 = ... # type: int +KEY_BACKSPACE = ... # type: int +KEY_BEG = ... # type: int +KEY_BREAK = ... # type: int +KEY_BTAB = ... # type: int +KEY_C1 = ... # type: int +KEY_C3 = ... # type: int +KEY_CANCEL = ... # type: int +KEY_CATAB = ... # type: int +KEY_CLEAR = ... # type: int +KEY_CLOSE = ... # type: int +KEY_COMMAND = ... # type: int +KEY_COPY = ... # type: int +KEY_CREATE = ... # type: int +KEY_CTAB = ... # type: int +KEY_DC = ... # type: int +KEY_DL = ... # type: int +KEY_DOWN = ... # type: int +KEY_EIC = ... # type: int +KEY_END = ... # type: int +KEY_ENTER = ... # type: int +KEY_EOL = ... # type: int +KEY_EOS = ... # type: int +KEY_EXIT = ... # type: int +KEY_F0 = ... # type: int +KEY_F1 = ... # type: int +KEY_F10 = ... # type: int +KEY_F11 = ... # type: int +KEY_F12 = ... # type: int +KEY_F13 = ... # type: int +KEY_F14 = ... # type: int +KEY_F15 = ... # type: int +KEY_F16 = ... # type: int +KEY_F17 = ... # type: int +KEY_F18 = ... # type: int +KEY_F19 = ... # type: int +KEY_F2 = ... # type: int +KEY_F20 = ... # type: int +KEY_F21 = ... # type: int +KEY_F22 = ... # type: int +KEY_F23 = ... # type: int +KEY_F24 = ... # type: int +KEY_F25 = ... # type: int +KEY_F26 = ... # type: int +KEY_F27 = ... # type: int +KEY_F28 = ... # type: int +KEY_F29 = ... # type: int +KEY_F3 = ... # type: int +KEY_F30 = ... # type: int +KEY_F31 = ... # type: int +KEY_F32 = ... # type: int +KEY_F33 = ... # type: int +KEY_F34 = ... # type: int +KEY_F35 = ... # type: int +KEY_F36 = ... # type: int +KEY_F37 = ... # type: int +KEY_F38 = ... # type: int +KEY_F39 = ... # type: int +KEY_F4 = ... # type: int +KEY_F40 = ... # type: int +KEY_F41 = ... # type: int +KEY_F42 = ... # type: int +KEY_F43 = ... # type: int +KEY_F44 = ... # type: int +KEY_F45 = ... # type: int +KEY_F46 = ... # type: int +KEY_F47 = ... # type: int +KEY_F48 = ... # type: int +KEY_F49 = ... # type: int +KEY_F5 = ... # type: int +KEY_F50 = ... # type: int +KEY_F51 = ... # type: int +KEY_F52 = ... # type: int +KEY_F53 = ... # type: int +KEY_F54 = ... # type: int +KEY_F55 = ... # type: int +KEY_F56 = ... # type: int +KEY_F57 = ... # type: int +KEY_F58 = ... # type: int +KEY_F59 = ... # type: int +KEY_F6 = ... # type: int +KEY_F60 = ... # type: int +KEY_F61 = ... # type: int +KEY_F62 = ... # type: int +KEY_F63 = ... # type: int +KEY_F7 = ... # type: int +KEY_F8 = ... # type: int +KEY_F9 = ... # type: int +KEY_FIND = ... # type: int +KEY_HELP = ... # type: int +KEY_HOME = ... # type: int +KEY_IC = ... # type: int +KEY_IL = ... # type: int +KEY_LEFT = ... # type: int +KEY_LL = ... # type: int +KEY_MARK = ... # type: int +KEY_MAX = ... # type: int +KEY_MESSAGE = ... # type: int +KEY_MIN = ... # type: int +KEY_MOUSE = ... # type: int +KEY_MOVE = ... # type: int +KEY_NEXT = ... # type: int +KEY_NPAGE = ... # type: int +KEY_OPEN = ... # type: int +KEY_OPTIONS = ... # type: int +KEY_PPAGE = ... # type: int +KEY_PREVIOUS = ... # type: int +KEY_PRINT = ... # type: int +KEY_REDO = ... # type: int +KEY_REFERENCE = ... # type: int +KEY_REFRESH = ... # type: int +KEY_REPLACE = ... # type: int +KEY_RESET = ... # type: int +KEY_RESIZE = ... # type: int +KEY_RESTART = ... # type: int +KEY_RESUME = ... # type: int +KEY_RIGHT = ... # type: int +KEY_SAVE = ... # type: int +KEY_SBEG = ... # type: int +KEY_SCANCEL = ... # type: int +KEY_SCOMMAND = ... # type: int +KEY_SCOPY = ... # type: int +KEY_SCREATE = ... # type: int +KEY_SDC = ... # type: int +KEY_SDL = ... # type: int +KEY_SELECT = ... # type: int +KEY_SEND = ... # type: int +KEY_SEOL = ... # type: int +KEY_SEXIT = ... # type: int +KEY_SF = ... # type: int +KEY_SFIND = ... # type: int +KEY_SHELP = ... # type: int +KEY_SHOME = ... # type: int +KEY_SIC = ... # type: int +KEY_SLEFT = ... # type: int +KEY_SMESSAGE = ... # type: int +KEY_SMOVE = ... # type: int +KEY_SNEXT = ... # type: int +KEY_SOPTIONS = ... # type: int +KEY_SPREVIOUS = ... # type: int +KEY_SPRINT = ... # type: int +KEY_SR = ... # type: int +KEY_SREDO = ... # type: int +KEY_SREPLACE = ... # type: int +KEY_SRESET = ... # type: int +KEY_SRIGHT = ... # type: int +KEY_SRSUME = ... # type: int +KEY_SSAVE = ... # type: int +KEY_SSUSPEND = ... # type: int +KEY_STAB = ... # type: int +KEY_SUNDO = ... # type: int +KEY_SUSPEND = ... # type: int +KEY_UNDO = ... # type: int +KEY_UP = ... # type: int +OK = ... # type: int +REPORT_MOUSE_POSITION = ... # type: int +_C_API = ... # type: Any +version = ... # type: bytes + +def baudrate() -> int: ... +def beep() -> None: ... +def can_change_color() -> bool: ... +def cbreak(flag: bool = ...) -> None: ... +def color_content(color_number: int) -> Tuple[int, int, int]: ... +def color_pair(color_number: int) -> int: ... +def curs_set(visibility: int) -> int: ... +def def_prog_mode() -> None: ... +def def_shell_mode() -> None: ... +def delay_output(ms: int) -> None: ... +def doupdate() -> None: ... +def echo(flag: bool = ...) -> None: ... +def endwin() -> None: ... +def erasechar() -> bytes: ... +def filter() -> None: ... +def flash() -> None: ... +def flushinp() -> None: ... +def getmouse() -> Tuple[int, int, int, int, int]: ... +def getsyx() -> Tuple[int, int]: ... +def getwin(f: BinaryIO) -> _CursesWindow: ... +def halfdelay(tenths: int) -> None: ... +def has_colors() -> bool: ... +def has_ic() -> bool: ... +def has_il() -> bool: ... +def has_key(ch: int) -> bool: ... +def init_color(color_number: int, r: int, g: int, b: int) -> None: ... +def init_pair(pair_number: int, fg: int, bg: int) -> None: ... +def initscr() -> _CursesWindow: ... +def intrflush(ch: bool) -> None: ... +def is_term_resized(nlines: int, ncols: int) -> bool: ... +def isendwin() -> bool: ... +def keyname(k: int) -> bytes: ... +def killchar() -> bytes: ... +def longname() -> bytes: ... +def meta(yes: bool) -> None: ... +def mouseinterval(interval: int) -> None: ... +def mousemask(mousemask: int) -> Tuple[int, int]: ... +def napms(ms: int) -> int: ... +def newpad(nlines: int, ncols: int) -> _CursesWindow: ... +def newwin(nlines: int, ncols: int, begin_y: int = ..., begin_x: int = ...) -> _CursesWindow: ... +def nl(flag: bool = ...) -> None: ... +def nocbreak() -> None: ... +def noecho() -> None: ... +def nonl() -> None: ... +def noqiflush() -> None: ... +def noraw() -> None: ... +def pair_content(pair_number: int) -> Tuple[int, int]: ... +def pair_number(attr: int) -> int: ... +def putp(string: bytes) -> None: ... +def qiflush(flag: bool = ...) -> None: ... +def raw(flag: bool = ...) -> None: ... +def reset_prog_mode() -> None: ... +def reset_shell_mode() -> None: ... +def resetty() -> None: ... +def resize_term(nlines: int, ncols: int) -> None: ... +def resizeterm(nlines: int, ncols: int) -> None: ... +def savetty() -> None: ... +def setsyx(y: int, x: int) -> None: ... +def setupterm(termstr: str = ..., fd: int = ...) -> None: ... +def start_color() -> None: ... +def termattrs() -> int: ... +def termname() -> bytes: ... +def tigetflag(capname: str) -> int: ... +def tigetnum(capname: str) -> int: ... +def tigetstr(capname: str) -> bytes: ... +def tparm(fmt: bytes, i1: int = ..., i2: int = ..., i3: int = ..., i4: int = ..., i5: int = ..., i6: int = ..., i7: int = ..., i8: int = ..., i9: int = ...) -> bytes: ... +def typeahead(fd: int) -> None: ... +def unctrl(ch: _chtype) -> bytes: ... +def unget_wch(ch: _chtype) -> None: ... +def ungetch(ch: _chtype) -> None: ... +def ungetmouse(id: int, x: int, y: int, z: int, bstate: int) -> None: ... +def update_lines_cols() -> int: ... +def use_default_colors() -> None: ... +def use_env(flag: bool) -> None: ... + +class error(Exception): ... + +class _CursesWindow: + encoding = ... # type: str + @overload + def addch(self, ch: _chtype, attr: int = ...) -> None: ... + @overload + def addch(self, y: int, x: int, ch: _chtype, attr: int = ...) -> None: ... + @overload + def addnstr(self, str: str, n: int, attr: int = ...) -> None: ... + @overload + def addnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... + @overload + def addstr(self, str: str, attr: int = ...) -> None: ... + @overload + def addstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... + def attroff(self, attr: int) -> None: ... + def attron(self, attr: int) -> None: ... + def attrset(self, attr: int) -> None: ... + def bkgd(self, ch: _chtype, attr: int = ...) -> None: ... + def bkgset(self, ch: _chtype, attr: int = ...) -> None: ... + def border(self, ls: _chtype = ..., rs: _chtype = ..., ts: _chtype = ..., bs: _chtype = ..., tl: _chtype = ..., tr: _chtype = ..., bl: _chtype = ..., br: _chtype = ...) -> None: ... + @overload + def box(self) -> None: ... + @overload + def box(self, vertch: _chtype = ..., horch: _chtype = ...) -> None: ... + @overload + def chgat(self, attr: int) -> None: ... + @overload + def chgat(self, num: int, attr: int) -> None: ... + @overload + def chgat(self, y: int, x: int, attr: int) -> None: ... + @overload + def chgat(self, y: int, x: int, num: int, attr: int) -> None: ... + def clear(self) -> None: ... + def clearok(self, yes: int) -> None: ... + def clrtobot(self) -> None: ... + def clrtoeol(self) -> None: ... + def cursyncup(self) -> None: ... + @overload + def delch(self) -> None: ... + @overload + def delch(self, y: int, x: int) -> None: ... + def deleteln(self) -> None: ... + @overload + def derwin(self, begin_y: int, begin_x: int) -> _CursesWindow: ... + @overload + def derwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... + def echochar(self, ch: _chtype, attr: int = ...) -> None: ... + def enclose(self, y: int, x: int) -> bool: ... + def erase(self) -> None: ... + def getbegyx(self) -> Tuple[int, int]: ... + def getbkgd(self) -> Tuple[int, int]: ... + @overload + def getch(self) -> _chtype: ... + @overload + def getch(self, y: int, x: int) -> _chtype: ... + @overload + def get_wch(self) -> _chtype: ... + @overload + def get_wch(self, y: int, x: int) -> _chtype: ... + @overload + def getkey(self) -> str: ... + @overload + def getkey(self, y: int, x: int) -> str: ... + def getmaxyx(self) -> Tuple[int, int]: ... + def getparyx(self) -> Tuple[int, int]: ... + @overload + def getstr(self) -> _chtype: ... + @overload + def getstr(self, n: int) -> _chtype: ... + @overload + def getstr(self, y: int, x: int) -> _chtype: ... + @overload + def getstr(self, y: int, x: int, n: int) -> _chtype: ... + def getyx(self) -> Tuple[int, int]: ... + @overload + def hline(self, ch: _chtype, n: int) -> None: ... + @overload + def hline(self, y: int, x: int, ch: _chtype, n: int) -> None: ... + def idcok(self, flag: bool) -> None: ... + def idlok(self, yes: bool) -> None: ... + def immedok(self, flag: bool) -> None: ... + @overload + def inch(self) -> _chtype: ... + @overload + def inch(self, y: int, x: int) -> _chtype: ... + @overload + def insch(self, ch: _chtype, attr: int = ...) -> None: ... + @overload + def insch(self, y: int, x: int, ch: _chtype, attr: int = ...) -> None: ... + def insdelln(self, nlines: int) -> None: ... + def insertln(self) -> None: ... + @overload + def insnstr(self, str: str, n: int, attr: int = ...) -> None: ... + @overload + def insnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... + @overload + def insstr(self, str: str, attr: int = ...) -> None: ... + @overload + def insstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... + @overload + def instr(self, n: int = ...) -> _chtype: ... + @overload + def instr(self, y: int, x: int, n: int = ...) -> _chtype: ... + def is_linetouched(self, line: int) -> bool: ... + def is_wintouched(self) -> bool: ... + def keypad(self, yes: bool) -> None: ... + def leaveok(self, yes: bool) -> None: ... + def move(self, new_y: int, new_x: int) -> None: ... + def mvderwin(self, y: int, x: int) -> None: ... + def mvwin(self, new_y: int, new_x: int) -> None: ... + def nodelay(self, yes: bool) -> None: ... + def notimeout(self, yes: bool) -> None: ... + def noutrefresh(self) -> None: ... + @overload + def overlay(self, destwin: _CursesWindow) -> None: ... + @overload + def overlay(self, destwin: _CursesWindow, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int) -> None: ... + @overload + def overwrite(self, destwin: _CursesWindow) -> None: ... + @overload + def overwrite(self, destwin: _CursesWindow, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int) -> None: ... + def putwin(self, file: IO[Any]) -> None: ... + def redrawln(self, beg: int, num: int) -> None: ... + def redrawwin(self) -> None: ... + @overload + def refresh(self) -> None: ... + @overload + def refresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ... + def resize(self, nlines: int, ncols: int) -> None: ... + def scroll(self, lines: int = ...) -> None: ... + def scrollok(self, flag: bool) -> None: ... + def setscrreg(self, top: int, bottom: int) -> None: ... + def standend(self) -> None: ... + def standout(self) -> None: ... + @overload + def subpad(self, begin_y: int, begin_x: int) -> _CursesWindow: ... + @overload + def subpad(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... + @overload + def subwin(self, begin_y: int, begin_x: int) -> _CursesWindow: ... + @overload + def subwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... + def syncdown(self) -> None: ... + def syncok(self, flag: bool) -> None: ... + def syncup(self) -> None: ... + def timeout(self, delay: int) -> None: ... + def touchline(self, start: int, count: int, changed: bool = ...) -> None: ... + def touchwin(self) -> None: ... + def untouchwin(self) -> None: ... + @overload + def vline(self, ch: _chtype, n: int) -> None: ... + @overload + def vline(self, y: int, x: int, ch: _chtype, n: int) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/_dummy_thread.pyi b/client/typeshed-fallback/stdlib/3/_dummy_thread.pyi new file mode 100644 index 000000000..1260d42de --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/_dummy_thread.pyi @@ -0,0 +1,21 @@ +from typing import Any, Callable, Dict, NoReturn, Optional, Tuple + +TIMEOUT_MAX: int +error = RuntimeError + +def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: Dict[str, Any] = ...) -> None: ... +def exit() -> NoReturn: ... +def get_ident() -> int: ... +def allocate_lock() -> LockType: ... +def stack_size(size: Optional[int] = ...) -> int: ... + +class LockType(object): + locked_status: bool + def __init__(self) -> None: ... + def acquire(self, waitflag: Optional[bool] = ..., timeout: int = ...) -> bool: ... + def __enter__(self, waitflag: Optional[bool] = ..., timeout: int = ...) -> bool: ... + def __exit__(self, typ: Any, val: Any, tb: Any) -> None: ... + def release(self) -> bool: ... + def locked(self) -> bool: ... + +def interrupt_main() -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/_imp.pyi b/client/typeshed-fallback/stdlib/3/_imp.pyi new file mode 100644 index 000000000..7015b3b0c --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/_imp.pyi @@ -0,0 +1,22 @@ +# Stubs for _imp (Python 3.6) + +import sys +import types +from typing import Any, List + +if sys.version_info >= (3, 5): + from importlib.machinery import ModuleSpec + def create_builtin(spec: ModuleSpec) -> types.ModuleType: ... + def create_dynamic(spec: ModuleSpec, file: Any = ...) -> None: ... + +def acquire_lock() -> None: ... +def exec_builtin(mod: types.ModuleType) -> int: ... +def exec_dynamic(mod: types.ModuleType) -> int: ... +def extension_suffixes() -> List[str]: ... +def get_frozen_object(name: str) -> types.CodeType: ... +def init_frozen(name: str) -> types.ModuleType: ... +def is_builtin(name: str) -> int: ... +def is_frozen(name: str) -> bool: ... +def is_frozen_package(name: str) -> bool: ... +def lock_held() -> bool: ... +def release_lock() -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/_importlib_modulespec.pyi b/client/typeshed-fallback/stdlib/3/_importlib_modulespec.pyi new file mode 100644 index 000000000..eca7a3252 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/_importlib_modulespec.pyi @@ -0,0 +1,45 @@ +# ModuleSpec, ModuleType, Loader are part of a dependency cycle. +# They are officially defined/exported in other places: +# +# - ModuleType in types +# - Loader in importlib.abc +# - ModuleSpec in importlib.machinery (3.4 and later only) +# +# _Loader is the PEP-451-defined interface for a loader type/object. + +from abc import ABCMeta +import sys +from typing import Any, Dict, List, Optional, Protocol + +class _Loader(Protocol): + def load_module(self, fullname: str) -> ModuleType: ... + +class ModuleSpec: + def __init__(self, name: str, loader: Optional[Loader], *, + origin: Optional[str] = ..., loader_state: Any = ..., + is_package: Optional[bool] = ...) -> None: ... + name = ... # type: str + loader = ... # type: Optional[_Loader] + origin = ... # type: Optional[str] + submodule_search_locations = ... # type: Optional[List[str]] + loader_state = ... # type: Any + cached = ... # type: Optional[str] + parent = ... # type: Optional[str] + has_location = ... # type: bool + +class ModuleType: + __name__ = ... # type: str + __file__ = ... # type: str + __dict__ = ... # type: Dict[str, Any] + __loader__ = ... # type: Optional[_Loader] + __package__ = ... # type: Optional[str] + __spec__ = ... # type: Optional[ModuleSpec] + def __init__(self, name: str, doc: Optional[str] = ...) -> None: ... + +class Loader(metaclass=ABCMeta): + def load_module(self, fullname: str) -> ModuleType: ... + def module_repr(self, module: ModuleType) -> str: ... + def create_module(self, spec: ModuleSpec) -> Optional[ModuleType]: ... + # Not defined on the actual class for backwards-compatibility reasons, + # but expected in new code. + def exec_module(self, module: ModuleType) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/_json.pyi b/client/typeshed-fallback/stdlib/3/_json.pyi new file mode 100644 index 000000000..a944ce1e6 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/_json.pyi @@ -0,0 +1,30 @@ +"""Stub file for the '_json' module.""" + +from typing import Any, Tuple + +class make_encoder: + sort_keys = ... # type: Any + skipkeys = ... # type: Any + key_separator = ... # type: Any + indent = ... # type: Any + markers = ... # type: Any + default = ... # type: Any + encoder = ... # type: Any + item_separator = ... # type: Any + def __init__(self, markers, default, encoder, indent, key_separator, + item_separator, sort_keys, skipkeys, allow_nan) -> None: ... + def __call__(self, *args, **kwargs) -> Any: ... + +class make_scanner: + object_hook = ... # type: Any + object_pairs_hook = ... # type: Any + parse_int = ... # type: Any + parse_constant = ... # type: Any + parse_float = ... # type: Any + strict = ... # type: bool + # TODO: 'context' needs the attrs above (ducktype), but not __call__. + def __init__(self, context: make_scanner) -> None: ... + def __call__(self, string: str, index: int) -> Tuple[Any, int]: ... + +def encode_basestring_ascii(s: str) -> str: ... +def scanstring(string: str, end: int, strict: bool = ...) -> Tuple[str, int]: ... diff --git a/client/typeshed-fallback/stdlib/3/_markupbase.pyi b/client/typeshed-fallback/stdlib/3/_markupbase.pyi new file mode 100644 index 000000000..09f69c742 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/_markupbase.pyi @@ -0,0 +1,9 @@ +from typing import Tuple + +class ParserBase: + def __init__(self) -> None: ... + def error(self, message: str) -> None: ... + def reset(self) -> None: ... + def getpos(self) -> Tuple[int, int]: ... + + def unknown_decl(self, data: str) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/_operator.pyi b/client/typeshed-fallback/stdlib/3/_operator.pyi new file mode 100644 index 000000000..6d08cd7ef --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/_operator.pyi @@ -0,0 +1,64 @@ +# Stubs for _operator (Python 3.5) + +import sys +from typing import AnyStr + +# In reality the import is the other way around, but this way we can keep the operator stub in 2and3 +from operator import ( + truth as truth, + contains as contains, + indexOf as indexOf, + countOf as countOf, + is_ as is_, + is_not as is_not, + index as index, + add as add, + sub as sub, + mul as mul, + floordiv as floordiv, + truediv as truediv, + mod as mod, + neg as neg, + pos as pos, + abs as abs, + inv as inv, + invert as invert, + length_hint as length_hint, + lshift as lshift, + rshift as rshift, + not_ as not_, + and_ as and_, + xor as xor, + or_ as or_, + iadd as iadd, + isub as isub, + imul as imul, + ifloordiv as ifloordiv, + itruediv as itruediv, + imod as imod, + ilshift as ilshift, + irshift as irshift, + iand as iand, + ixor as ixor, + ior as ior, + concat as concat, + iconcat as iconcat, + getitem as getitem, + setitem as setitem, + delitem as delitem, + pow as pow, + ipow as ipow, + eq as eq, + ne as ne, + lt as lt, + le as le, + gt as gt, + ge as ge, + itemgetter as itemgetter, + attrgetter as attrgetter, + methodcaller as methodcaller, +) +if sys.version_info >= (3, 5): + from operator import matmul as matmul, imatmul as imatmul + +def _compare_digest(a: AnyStr, b: AnyStr) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/3/_posixsubprocess.pyi b/client/typeshed-fallback/stdlib/3/_posixsubprocess.pyi new file mode 100644 index 000000000..67b7d7cc5 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/_posixsubprocess.pyi @@ -0,0 +1,14 @@ +# Stubs for _posixsubprocess + +# NOTE: These are incomplete! + +from typing import Tuple, Sequence, Callable + +def cloexec_pipe() -> Tuple[int, int]: ... +def fork_exec(args: Sequence[str], + executable_list: Sequence[bytes], close_fds: bool, fds_to_keep: Sequence[int], + cwd: str, env_list: Sequence[bytes], + p2cread: int, p2cwrite: int, c2pred: int, c2pwrite: int, + errread: int, errwrite: int, errpipe_read: int, + errpipe_write: int, restore_signals: int, start_new_session: int, + preexec_fn: Callable[[], None]) -> int: ... diff --git a/client/typeshed-fallback/stdlib/3/_stat.pyi b/client/typeshed-fallback/stdlib/3/_stat.pyi new file mode 100644 index 000000000..867321a49 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/_stat.pyi @@ -0,0 +1,69 @@ +"""Stub file for the '_stat' module.""" + +SF_APPEND = ... # type: int +SF_ARCHIVED = ... # type: int +SF_IMMUTABLE = ... # type: int +SF_NOUNLINK = ... # type: int +SF_SNAPSHOT = ... # type: int +ST_ATIME = ... # type: int +ST_CTIME = ... # type: int +ST_DEV = ... # type: int +ST_GID = ... # type: int +ST_INO = ... # type: int +ST_MODE = ... # type: int +ST_MTIME = ... # type: int +ST_NLINK = ... # type: int +ST_SIZE = ... # type: int +ST_UID = ... # type: int +S_ENFMT = ... # type: int +S_IEXEC = ... # type: int +S_IFBLK = ... # type: int +S_IFCHR = ... # type: int +S_IFDIR = ... # type: int +S_IFDOOR = ... # type: int +S_IFIFO = ... # type: int +S_IFLNK = ... # type: int +S_IFPORT = ... # type: int +S_IFREG = ... # type: int +S_IFSOCK = ... # type: int +S_IFWHT = ... # type: int +S_IREAD = ... # type: int +S_IRGRP = ... # type: int +S_IROTH = ... # type: int +S_IRUSR = ... # type: int +S_IRWXG = ... # type: int +S_IRWXO = ... # type: int +S_IRWXU = ... # type: int +S_ISGID = ... # type: int +S_ISUID = ... # type: int +S_ISVTX = ... # type: int +S_IWGRP = ... # type: int +S_IWOTH = ... # type: int +S_IWRITE = ... # type: int +S_IWUSR = ... # type: int +S_IXGRP = ... # type: int +S_IXOTH = ... # type: int +S_IXUSR = ... # type: int +UF_APPEND = ... # type: int +UF_COMPRESSED = ... # type: int +UF_HIDDEN = ... # type: int +UF_IMMUTABLE = ... # type: int +UF_NODUMP = ... # type: int +UF_NOUNLINK = ... # type: int +UF_OPAQUE = ... # type: int + +def S_IMODE(mode: int) -> int: ... +def S_IFMT(mode: int) -> int: ... + +def S_ISBLK(mode: int) -> bool: ... +def S_ISCHR(mode: int) -> bool: ... +def S_ISDIR(mode: int) -> bool: ... +def S_ISDOOR(mode: int) -> bool: ... +def S_ISFIFO(mode: int) -> bool: ... +def S_ISLNK(mode: int) -> bool: ... +def S_ISPORT(mode: int) -> bool: ... +def S_ISREG(mode: int) -> bool: ... +def S_ISSOCK(mode: int) -> bool: ... +def S_ISWHT(mode: int) -> bool: ... + +def filemode(mode: int) -> str: ... diff --git a/client/typeshed-fallback/stdlib/3/_subprocess.pyi b/client/typeshed-fallback/stdlib/3/_subprocess.pyi new file mode 100644 index 000000000..76967b94b --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/_subprocess.pyi @@ -0,0 +1,38 @@ +# Stubs for _subprocess + +# NOTE: These are incomplete! + +from typing import Mapping, Any, Tuple + +CREATE_NEW_CONSOLE = 0 +CREATE_NEW_PROCESS_GROUP = 0 +STD_INPUT_HANDLE = 0 +STD_OUTPUT_HANDLE = 0 +STD_ERROR_HANDLE = 0 +SW_HIDE = 0 +STARTF_USESTDHANDLES = 0 +STARTF_USESHOWWINDOW = 0 +INFINITE = 0 +DUPLICATE_SAME_ACCESS = 0 +WAIT_OBJECT_0 = 0 + +# TODO not exported by the Python module +class Handle: + def Close(self) -> None: ... + +def GetVersion() -> int: ... +def GetExitCodeProcess(handle: Handle) -> int: ... +def WaitForSingleObject(handle: Handle, timeout: int) -> int: ... +def CreateProcess(executable: str, cmd_line: str, + proc_attrs, thread_attrs, + inherit: int, flags: int, + env_mapping: Mapping[str, str], + curdir: str, + startupinfo: Any) -> Tuple[Any, Handle, int, int]: ... +def GetModuleFileName(module: int) -> str: ... +def GetCurrentProcess() -> Handle: ... +def DuplicateHandle(source_proc: Handle, source: Handle, target_proc: Handle, + target: Any, access: int, inherit: int) -> int: ... +def CreatePipe(pipe_attrs, size: int) -> Tuple[Handle, Handle]: ... +def GetStdHandle(arg: int) -> int: ... +def TerminateProcess(handle: Handle, exit_code: int) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/_thread.pyi b/client/typeshed-fallback/stdlib/3/_thread.pyi new file mode 100644 index 000000000..a8e38a91a --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/_thread.pyi @@ -0,0 +1,15 @@ +# Stubs for _thread + +# NOTE: These are incomplete! + +from typing import Any + +def _count() -> int: ... +_dangling = ... # type: Any + +class LockType: + def acquire(self) -> None: ... + def release(self) -> None: ... + +def allocate_lock() -> LockType: ... +def get_ident() -> int: ... diff --git a/client/typeshed-fallback/stdlib/3/_threading_local.pyi b/client/typeshed-fallback/stdlib/3/_threading_local.pyi new file mode 100644 index 000000000..a286d2dd5 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/_threading_local.pyi @@ -0,0 +1,18 @@ +# Source: https://github.com/python/cpython/blob/master/Lib/_threading_local.py +from typing import Any, Dict, List, Tuple +from weakref import ReferenceType + +__all__: List[str] +localdict = Dict[Any, Any] + +class _localimpl: + key: str + dicts: Dict[int, Tuple[ReferenceType, localdict]] + def __init__(self) -> None: ... + def get_dict(self) -> localdict: ... + def create_dict(self) -> localdict: ... + +class local: + def __getattribute__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __delattr__(self, name: str) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/_tracemalloc.pyi b/client/typeshed-fallback/stdlib/3/_tracemalloc.pyi new file mode 100644 index 000000000..21d00332a --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/_tracemalloc.pyi @@ -0,0 +1,26 @@ +"""Stub file for the '_tracemalloc' module.""" +# This is an autogenerated file. It serves as a starting point +# for a more precise manual annotation of this module. +# Feel free to edit the source below, but remove this header when you do. + +from typing import Any + +def _get_object_traceback(*args, **kwargs) -> Any: ... + +def _get_traces() -> Any: + raise MemoryError() + +def clear_traces() -> None: ... + +def get_traceback_limit() -> int: ... + +def get_traced_memory() -> tuple: ... + +def get_tracemalloc_memory() -> Any: ... + +def is_tracing() -> bool: ... + +def start(*args, **kwargs) -> None: + raise ValueError() + +def stop() -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/_warnings.pyi b/client/typeshed-fallback/stdlib/3/_warnings.pyi new file mode 100644 index 000000000..4d890e51c --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/_warnings.pyi @@ -0,0 +1,11 @@ +from typing import Any, List, Optional, Type + +_defaultaction = ... # type: str +_onceregistry = ... # type: dict +filters = ... # type: List[tuple] + +def warn(message: Warning, category: Optional[Type[Warning]] = ..., stacklevel: int = ...) -> None: ... +def warn_explicit(message: Warning, category: Optional[Type[Warning]], + filename: str, lineno: int, + module: Any = ..., registry: dict = ..., + module_globals: dict = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/_winapi.pyi b/client/typeshed-fallback/stdlib/3/_winapi.pyi new file mode 100644 index 000000000..af6c9231b --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/_winapi.pyi @@ -0,0 +1,96 @@ +from typing import Any, Union, Tuple, Optional, overload, Dict, NoReturn, Sequence + +CREATE_NEW_CONSOLE: int +CREATE_NEW_PROCESS_GROUP: int +DUPLICATE_CLOSE_SOURCE: int +DUPLICATE_SAME_ACCESS: int +ERROR_ALREADY_EXISTS: int +ERROR_BROKEN_PIPE: int +ERROR_IO_PENDING: int +ERROR_MORE_DATA: int +ERROR_NETNAME_DELETED: int +ERROR_NO_DATA: int +ERROR_NO_SYSTEM_RESOURCES: int +ERROR_OPERATION_ABORTED: int +ERROR_PIPE_BUSY: int +ERROR_PIPE_CONNECTED: int +ERROR_SEM_TIMEOUT: int +FILE_FLAG_FIRST_PIPE_INSTANCE: int +FILE_FLAG_OVERLAPPED: int +FILE_GENERIC_READ: int +FILE_GENERIC_WRITE: int +GENERIC_READ: int +GENERIC_WRITE: int +INFINITE: int +NMPWAIT_WAIT_FOREVER: int +NULL: int +OPEN_EXISTING: int +PIPE_ACCESS_DUPLEX: int +PIPE_ACCESS_INBOUND: int +PIPE_READMODE_MESSAGE: int +PIPE_TYPE_MESSAGE: int +PIPE_UNLIMITED_INSTANCES: int +PIPE_WAIT: int +PROCESS_ALL_ACCESS: int +PROCESS_DUP_HANDLE: int +STARTF_USESHOWWINDOW: int +STARTF_USESTDHANDLES: int +STD_ERROR_HANDLE: int +STD_INPUT_HANDLE: int +STD_OUTPUT_HANDLE: int +STILL_ACTIVE: int +SW_HIDE: int +WAIT_ABANDONED_0: int +WAIT_OBJECT_0: int +WAIT_TIMEOUT: int + +def CloseHandle(handle: int) -> None: ... + +# TODO: once literal types are supported, overload with Literal[True/False] +@overload +def ConnectNamedPipe(handle: int, overlapped: Union[int, bool]) -> Any: ... +@overload +def ConnectNamedPipe(handle: int) -> None: ... + +def CreateFile(file_name: str, desired_access: int, share_mode: int, security_attributes: int, creation_disposition: int, flags_and_attributes: int, template_file: int) -> int: ... +def CreateJunction(src_path: str, dest_path: str) -> None: ... +def CreateNamedPipe(name: str, open_mode: int, pipe_mode: int, max_instances: int, out_buffer_size: int, in_buffer_size: int, default_timeout: int, security_attributes: int) -> int: ... +def CreatePipe(pipe_attrs: Any, size: int) -> Tuple[int, int]: ... +def CreateProcess(application_name: Optional[str], command_line: Optional[str], proc_attrs: Any, thread_attrs: Any, inherit_handles: bool, creation_flags: int, env_mapping: Dict[str, str], cwd: Optional[str], startup_info: Any) -> Tuple[int, int, int, int]: ... +def DuplicateHandle(source_process_handle: int, source_handle: int, target_process_handle: int, desired_access: int, inherit_handle: bool, options: int = ...) -> int: ... +def ExitProcess(ExitCode: int) -> NoReturn: ... +def GetACP() -> int: ... +def GetFileType(handle: int) -> int: ... +def GetCurrentProcess() -> int: ... +def GetExitCodeProcess(process: int) -> int: ... +def GetLastError() -> int: ... +def GetModuleFileName(module_handle: int) -> str: ... +def GetStdHandle(std_handle: int) -> int: ... +def GetVersion() -> int: ... +def OpenProcess(desired_access: int, inherit_handle: bool, process_id: int) -> int: ... +def PeekNamedPipe(handle: int, size: int = ...) -> Union[Tuple[int, int], Tuple[bytes, int, int]]: ... + +# TODO: once literal types are supported, overload with Literal[True/False] +@overload +def ReadFile(handle: int, size: int, overlapped: Union[int, bool]) -> Any: ... +@overload +def ReadFile(handle: int, size: int) -> Tuple[int, int]: ... + +def SetNamedPipeHandleState(named_pipe: int, mode: Optional[int], max_collection_count: Optional[int], collect_data_timeout: Optional[int]) -> None: ... +def TerminateProcess(handle: int, exit_code: int) -> None: ... +def WaitForMultipleObjects(handle_seq: Sequence[int], wait_flag: bool, milliseconds: int = ...) -> int: ... +def WaitForSingleObject(handle: int, milliseconds: int) -> int: ... +def WaitNamedPipe(name: str, timeout: int) -> None: ... + +# TODO: once literal types are supported, overload with Literal[True/False] +@overload +def WriteFile(handle: int, buffer: bytes, overlapped: Union[int, bool]) -> Any: ... +@overload +def WriteFile(handle: int, buffer: bytes) -> Tuple[bytes, int]: ... + + +class Overlapped: + event: int = ... + def GetOverlappedResult(self, wait: bool) -> Tuple[int, int]: ... + def cancel(self) -> None: ... + def getbuffer(self) -> Optional[bytes]: ... diff --git a/client/typeshed-fallback/stdlib/3/abc.pyi b/client/typeshed-fallback/stdlib/3/abc.pyi new file mode 100644 index 000000000..e9c530d20 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/abc.pyi @@ -0,0 +1,19 @@ +from typing import Any, Callable, Type, TypeVar +# Stubs for abc. + +_T = TypeVar('_T') +_FuncT = TypeVar('_FuncT', bound=Callable[..., Any]) + +# Thesee definitions have special processing in mypy +class ABCMeta(type): + def register(cls: ABCMeta, subclass: Type[_T]) -> Type[_T]: ... + +def abstractmethod(callable: _FuncT) -> _FuncT: ... +class abstractproperty(property): ... +# These two are deprecated and not supported by mypy +def abstractstaticmethod(callable: _FuncT) -> _FuncT: ... +def abstractclassmethod(callable: _FuncT) -> _FuncT: ... + +class ABC(metaclass=ABCMeta): ... + +def get_cache_token() -> object: ... diff --git a/client/typeshed-fallback/stdlib/3/ast.pyi b/client/typeshed-fallback/stdlib/3/ast.pyi new file mode 100644 index 000000000..7f2f33583 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/ast.pyi @@ -0,0 +1,29 @@ +# Python 3.5 ast + +# Rename typing to _typing, as not to conflict with typing imported +# from _ast below when loaded in an unorthodox way by the Dropbox +# internal Bazel integration. +import typing as _typing +from typing import Any, Iterator, Optional, Union, TypeVar + +from _ast import * + +class NodeVisitor(): + def visit(self, node: AST) -> Any: ... + def generic_visit(self, node: AST) -> Any: ... + +class NodeTransformer(NodeVisitor): + def generic_visit(self, node: AST) -> Optional[AST]: ... + +_T = TypeVar('_T', bound=AST) + +def parse(source: Union[str, bytes], filename: Union[str, bytes] = ..., mode: str = ...) -> Module: ... +def copy_location(new_node: _T, old_node: AST) -> _T: ... +def dump(node: AST, annotate_fields: bool = ..., include_attributes: bool = ...) -> str: ... +def fix_missing_locations(node: _T) -> _T: ... +def get_docstring(node: AST, clean: bool = ...) -> str: ... +def increment_lineno(node: _T, n: int = ...) -> _T: ... +def iter_child_nodes(node: AST) -> Iterator[AST]: ... +def iter_fields(node: AST) -> Iterator[_typing.Tuple[str, Any]]: ... +def literal_eval(node_or_string: Union[str, AST]) -> Any: ... +def walk(node: AST) -> Iterator[AST]: ... diff --git a/client/typeshed-fallback/stdlib/3/asyncio/__init__.pyi b/client/typeshed-fallback/stdlib/3/asyncio/__init__.pyi new file mode 100644 index 000000000..6053f6b73 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/asyncio/__init__.pyi @@ -0,0 +1,124 @@ +import sys +from typing import List, Type + +from asyncio.coroutines import ( + coroutine as coroutine, + iscoroutinefunction as iscoroutinefunction, + iscoroutine as iscoroutine, +) +from asyncio.protocols import ( + BaseProtocol as BaseProtocol, + Protocol as Protocol, + DatagramProtocol as DatagramProtocol, + SubprocessProtocol as SubprocessProtocol, +) +from asyncio.streams import ( + StreamReader as StreamReader, + StreamWriter as StreamWriter, + StreamReaderProtocol as StreamReaderProtocol, + open_connection as open_connection, + start_server as start_server, + IncompleteReadError as IncompleteReadError, + LimitOverrunError as LimitOverrunError, +) +from asyncio.subprocess import ( + create_subprocess_exec as create_subprocess_exec, + create_subprocess_shell as create_subprocess_shell, +) +from asyncio.transports import ( + BaseTransport as BaseTransport, + ReadTransport as ReadTransport, + WriteTransport as WriteTransport, + Transport as Transport, + DatagramTransport as DatagramTransport, + SubprocessTransport as SubprocessTransport, +) +from asyncio.futures import ( + Future as Future, + CancelledError as CancelledError, + TimeoutError as TimeoutError, + InvalidStateError as InvalidStateError, + wrap_future as wrap_future, +) +from asyncio.tasks import ( + FIRST_COMPLETED as FIRST_COMPLETED, + FIRST_EXCEPTION as FIRST_EXCEPTION, + ALL_COMPLETED as ALL_COMPLETED, + as_completed as as_completed, + ensure_future as ensure_future, + gather as gather, + run_coroutine_threadsafe as run_coroutine_threadsafe, + shield as shield, + sleep as sleep, + wait as wait, + wait_for as wait_for, + Task as Task, +) +from asyncio.events import ( + AbstractEventLoopPolicy as AbstractEventLoopPolicy, + AbstractEventLoop as AbstractEventLoop, + AbstractServer as AbstractServer, + Handle as Handle, + TimerHandle as TimerHandle, + get_event_loop_policy as get_event_loop_policy, + set_event_loop_policy as set_event_loop_policy, + get_event_loop as get_event_loop, + set_event_loop as set_event_loop, + new_event_loop as new_event_loop, + get_child_watcher as get_child_watcher, + set_child_watcher as set_child_watcher, +) +from asyncio.queues import ( + Queue as Queue, + PriorityQueue as PriorityQueue, + LifoQueue as LifoQueue, + QueueFull as QueueFull, + QueueEmpty as QueueEmpty, +) +from asyncio.locks import ( + Lock as Lock, + Event as Event, + Condition as Condition, + Semaphore as Semaphore, + BoundedSemaphore as BoundedSemaphore, +) + +if sys.version_info < (3, 5): + from asyncio.queues import JoinableQueue as JoinableQueue +else: + from asyncio.futures import isfuture as isfuture + from asyncio.events import ( + _set_running_loop as _set_running_loop, + _get_running_loop as _get_running_loop, + ) +if sys.platform != 'win32': + from asyncio.streams import ( + open_unix_connection as open_unix_connection, + start_unix_server as start_unix_server, + ) + +if sys.version_info >= (3, 7): + from asyncio.events import ( + get_running_loop as get_running_loop, + ) + from asyncio.tasks import ( + all_tasks as all_tasks, + create_task as create_task, + current_task as current_task, + ) + from asyncio.runners import ( + run as run, + ) + + +# TODO: It should be possible to instantiate these classes, but mypy +# currently disallows this. +# See https://github.com/python/mypy/issues/1843 +SelectorEventLoop = ... # type: Type[AbstractEventLoop] +if sys.platform == 'win32': + ProactorEventLoop = ... # type: Type[AbstractEventLoop] +DefaultEventLoopPolicy = ... # type: Type[AbstractEventLoopPolicy] + +# TODO: AbstractChildWatcher (UNIX only) + +__all__: List[str] diff --git a/client/typeshed-fallback/stdlib/3/asyncio/coroutines.pyi b/client/typeshed-fallback/stdlib/3/asyncio/coroutines.pyi new file mode 100644 index 000000000..981ccd5a0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/asyncio/coroutines.pyi @@ -0,0 +1,9 @@ +from typing import Any, Callable, Generator, List, TypeVar + +__all__: List[str] + +_F = TypeVar('_F', bound=Callable[..., Any]) + +def coroutine(func: _F) -> _F: ... +def iscoroutinefunction(func: Callable[..., Any]) -> bool: ... +def iscoroutine(obj: Any) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/3/asyncio/events.pyi b/client/typeshed-fallback/stdlib/3/asyncio/events.pyi new file mode 100644 index 000000000..a2f88dcf8 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/asyncio/events.pyi @@ -0,0 +1,246 @@ +import selectors +from socket import socket +import ssl +import sys +from typing import Any, Awaitable, Callable, Dict, Generator, List, Optional, Sequence, Tuple, TypeVar, Union, overload +from abc import ABCMeta, abstractmethod +from asyncio.futures import Future +from asyncio.coroutines import coroutine +from asyncio.protocols import BaseProtocol +from asyncio.tasks import Task +from asyncio.transports import BaseTransport + +__all__: List[str] + +_T = TypeVar('_T') +_Context = Dict[str, Any] +_ExceptionHandler = Callable[[AbstractEventLoop, _Context], Any] +_ProtocolFactory = Callable[[], BaseProtocol] +_SSLContext = Union[bool, None, ssl.SSLContext] +_TransProtPair = Tuple[BaseTransport, BaseProtocol] + +class Handle: + _cancelled = False + _args = ... # type: List[Any] + def __init__(self, callback: Callable[..., Any], args: List[Any], loop: AbstractEventLoop) -> None: ... + def __repr__(self) -> str: ... + def cancel(self) -> None: ... + def _run(self) -> None: ... + +class TimerHandle(Handle): + def __init__(self, when: float, callback: Callable[..., Any], args: List[Any], + loop: AbstractEventLoop) -> None: ... + def __hash__(self) -> int: ... + +class AbstractServer: + sockets: Optional[List[socket]] + def close(self) -> None: ... + @coroutine + def wait_closed(self) -> Generator[Any, None, None]: ... + +class AbstractEventLoop(metaclass=ABCMeta): + slow_callback_duration: float = ... + @abstractmethod + def run_forever(self) -> None: ... + + # Can't use a union, see mypy issue # 1873. + @overload + @abstractmethod + def run_until_complete(self, future: Generator[Any, None, _T]) -> _T: ... + @overload + @abstractmethod + def run_until_complete(self, future: Awaitable[_T]) -> _T: ... + + @abstractmethod + def stop(self) -> None: ... + @abstractmethod + def is_running(self) -> bool: ... + @abstractmethod + def is_closed(self) -> bool: ... + @abstractmethod + def close(self) -> None: ... + if sys.version_info >= (3, 6): + @abstractmethod + @coroutine + def shutdown_asyncgens(self) -> Generator[Any, None, None]: ... + # Methods scheduling callbacks. All these return Handles. + @abstractmethod + def call_soon(self, callback: Callable[..., Any], *args: Any) -> Handle: ... + @abstractmethod + def call_later(self, delay: float, callback: Callable[..., Any], *args: Any) -> TimerHandle: ... + @abstractmethod + def call_at(self, when: float, callback: Callable[..., Any], *args: Any) -> TimerHandle: ... + @abstractmethod + def time(self) -> float: ... + # Future methods + if sys.version_info >= (3, 5): + @abstractmethod + def create_future(self) -> Future[Any]: ... + # Tasks methods + @abstractmethod + def create_task(self, coro: Union[Awaitable[_T], Generator[Any, None, _T]]) -> Task[_T]: ... + @abstractmethod + def set_task_factory(self, factory: Optional[Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]]]) -> None: ... + @abstractmethod + def get_task_factory(self) -> Optional[Callable[[AbstractEventLoop, Generator[Any, None, _T]], Future[_T]]]: ... + # Methods for interacting with threads + @abstractmethod + def call_soon_threadsafe(self, callback: Callable[..., Any], *args: Any) -> Handle: ... + @abstractmethod + @coroutine + def run_in_executor(self, executor: Any, + func: Callable[..., _T], *args: Any) -> Generator[Any, None, _T]: ... + @abstractmethod + def set_default_executor(self, executor: Any) -> None: ... + # Network I/O methods returning Futures. + @abstractmethod + @coroutine + # TODO the "Tuple[Any, ...]" should be "Union[Tuple[str, int], Tuple[str, int, int, int]]" but that triggers + # https://github.com/python/mypy/issues/2509 + def getaddrinfo(self, host: Optional[str], port: Union[str, int, None], *, + family: int = ..., type: int = ..., proto: int = ..., + flags: int = ...) -> Generator[Any, None, List[Tuple[int, int, int, str, Tuple[Any, ...]]]]: ... + @abstractmethod + @coroutine + def getnameinfo(self, sockaddr: tuple, flags: int = ...) -> Generator[Any, None, Tuple[str, int]]: ... + @overload + @abstractmethod + @coroutine + def create_connection(self, protocol_factory: _ProtocolFactory, host: str = ..., port: int = ..., *, + ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., sock: None = ..., + local_addr: Optional[str] = ..., server_hostname: Optional[str] = ...) -> Generator[Any, None, _TransProtPair]: ... + @overload + @abstractmethod + @coroutine + def create_connection(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, + ssl: _SSLContext = ..., family: int = ..., proto: int = ..., flags: int = ..., sock: socket, + local_addr: None = ..., server_hostname: Optional[str] = ...) -> Generator[Any, None, _TransProtPair]: ... + @overload + @abstractmethod + @coroutine + def create_server(self, protocol_factory: _ProtocolFactory, host: Optional[Union[str, Sequence[str]]] = ..., port: int = ..., *, + family: int = ..., flags: int = ..., + sock: None = ..., backlog: int = ..., ssl: _SSLContext = ..., + reuse_address: Optional[bool] = ..., + reuse_port: Optional[bool] = ...) -> Generator[Any, None, AbstractServer]: ... + @overload + @abstractmethod + @coroutine + def create_server(self, protocol_factory: _ProtocolFactory, host: None = ..., port: None = ..., *, + family: int = ..., flags: int = ..., + sock: socket, backlog: int = ..., ssl: _SSLContext = ..., + reuse_address: Optional[bool] = ..., + reuse_port: Optional[bool] = ...) -> Generator[Any, None, AbstractServer]: ... + @abstractmethod + @coroutine + def create_unix_connection(self, protocol_factory: _ProtocolFactory, path: str, *, + ssl: _SSLContext = ..., sock: Optional[socket] = ..., + server_hostname: str = ...) -> Generator[Any, None, _TransProtPair]: ... + @abstractmethod + @coroutine + def create_unix_server(self, protocol_factory: _ProtocolFactory, path: str, *, + sock: Optional[socket] = ..., backlog: int = ..., ssl: _SSLContext = ...) -> Generator[Any, None, AbstractServer]: ... + @abstractmethod + @coroutine + def create_datagram_endpoint(self, protocol_factory: _ProtocolFactory, + local_addr: Optional[Tuple[str, int]] = ..., remote_addr: Optional[Tuple[str, int]] = ..., *, + family: int = ..., proto: int = ..., flags: int = ..., + reuse_address: Optional[bool] = ..., reuse_port: Optional[bool] = ..., + allow_broadcast: Optional[bool] = ..., + sock: Optional[socket] = ...) -> Generator[Any, None, _TransProtPair]: ... + @abstractmethod + @coroutine + def connect_accepted_socket(self, protocol_factory: _ProtocolFactory, sock: socket, *, ssl: _SSLContext = ...) -> Generator[Any, None, _TransProtPair]: ... + # Pipes and subprocesses. + @abstractmethod + @coroutine + def connect_read_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> Generator[Any, None, _TransProtPair]: ... + @abstractmethod + @coroutine + def connect_write_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> Generator[Any, None, _TransProtPair]: ... + @abstractmethod + @coroutine + def subprocess_shell(self, protocol_factory: _ProtocolFactory, cmd: Union[bytes, str], *, stdin: Any = ..., + stdout: Any = ..., stderr: Any = ..., + **kwargs: Any) -> Generator[Any, None, _TransProtPair]: ... + @abstractmethod + @coroutine + def subprocess_exec(self, protocol_factory: _ProtocolFactory, *args: Any, stdin: Any = ..., + stdout: Any = ..., stderr: Any = ..., + **kwargs: Any) -> Generator[Any, None, _TransProtPair]: ... + @abstractmethod + def add_reader(self, fd: selectors._FileObject, callback: Callable[..., Any], *args: Any) -> None: ... + @abstractmethod + def remove_reader(self, fd: selectors._FileObject) -> None: ... + @abstractmethod + def add_writer(self, fd: selectors._FileObject, callback: Callable[..., Any], *args: Any) -> None: ... + @abstractmethod + def remove_writer(self, fd: selectors._FileObject) -> None: ... + # Completion based I/O methods returning Futures. + @abstractmethod + @coroutine + def sock_recv(self, sock: socket, nbytes: int) -> Generator[Any, None, bytes]: ... + @abstractmethod + @coroutine + def sock_sendall(self, sock: socket, data: bytes) -> Generator[Any, None, None]: ... + @abstractmethod + @coroutine + def sock_connect(self, sock: socket, address: str) -> Generator[Any, None, None]: ... + @abstractmethod + @coroutine + def sock_accept(self, sock: socket) -> Generator[Any, None, Tuple[socket, Any]]: ... + # Signal handling. + @abstractmethod + def add_signal_handler(self, sig: int, callback: Callable[..., Any], *args: Any) -> None: ... + @abstractmethod + def remove_signal_handler(self, sig: int) -> None: ... + # Error handlers. + @abstractmethod + def set_exception_handler(self, handler: Optional[_ExceptionHandler]) -> None: ... + if sys.version_info >= (3, 5): + @abstractmethod + def get_exception_handler(self) -> Optional[_ExceptionHandler]: ... + @abstractmethod + def default_exception_handler(self, context: _Context) -> None: ... + @abstractmethod + def call_exception_handler(self, context: _Context) -> None: ... + # Debug flag management. + @abstractmethod + def get_debug(self) -> bool: ... + @abstractmethod + def set_debug(self, enabled: bool) -> None: ... + +class AbstractEventLoopPolicy(metaclass=ABCMeta): + @abstractmethod + def get_event_loop(self) -> AbstractEventLoop: ... + @abstractmethod + def set_event_loop(self, loop: Optional[AbstractEventLoop]) -> None: ... + @abstractmethod + def new_event_loop(self) -> AbstractEventLoop: ... + # Child processes handling (Unix only). + @abstractmethod + def get_child_watcher(self) -> Any: ... # TODO: unix_events.AbstractChildWatcher + @abstractmethod + def set_child_watcher(self, watcher: Any) -> None: ... # TODO: unix_events.AbstractChildWatcher + +class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy, metaclass=ABCMeta): + def __init__(self) -> None: ... + def get_event_loop(self) -> AbstractEventLoop: ... + def set_event_loop(self, loop: Optional[AbstractEventLoop]) -> None: ... + def new_event_loop(self) -> AbstractEventLoop: ... + +def get_event_loop_policy() -> AbstractEventLoopPolicy: ... +def set_event_loop_policy(policy: AbstractEventLoopPolicy) -> None: ... + +def get_event_loop() -> AbstractEventLoop: ... +def set_event_loop(loop: Optional[AbstractEventLoop]) -> None: ... +def new_event_loop() -> AbstractEventLoop: ... + +def get_child_watcher() -> Any: ... # TODO: unix_events.AbstractChildWatcher +def set_child_watcher(watcher: Any) -> None: ... # TODO: unix_events.AbstractChildWatcher + +def _set_running_loop(loop: AbstractEventLoop) -> None: ... +def _get_running_loop() -> AbstractEventLoop: ... + +if sys.version_info >= (3, 7): + def get_running_loop() -> AbstractEventLoop: ... diff --git a/client/typeshed-fallback/stdlib/3/asyncio/futures.pyi b/client/typeshed-fallback/stdlib/3/asyncio/futures.pyi new file mode 100644 index 000000000..4ceaa84f9 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/asyncio/futures.pyi @@ -0,0 +1,54 @@ +import sys +from typing import Any, Union, Callable, TypeVar, Type, List, Generic, Iterable, Generator, Awaitable +from .events import AbstractEventLoop +from concurrent.futures import ( + CancelledError as CancelledError, + TimeoutError as TimeoutError, + Future as _ConcurrentFuture, + Error, +) + +__all__: List[str] + +_T = TypeVar('_T') +_S = TypeVar('_S', bound=Future) + +class InvalidStateError(Error): ... + +class _TracebackLogger: + exc = ... # type: BaseException + tb = ... # type: List[str] + def __init__(self, exc: Any, loop: AbstractEventLoop) -> None: ... + def activate(self) -> None: ... + def clear(self) -> None: ... + def __del__(self) -> None: ... + +if sys.version_info >= (3, 5): + def isfuture(obj: object) -> bool: ... + +class Future(Awaitable[_T], Iterable[_T]): + _state = ... # type: str + _exception = ... # type: BaseException + _blocking = False + _log_traceback = False + _tb_logger = ... # type: Type[_TracebackLogger] + def __init__(self, *, loop: AbstractEventLoop = ...) -> None: ... + def __repr__(self) -> str: ... + def __del__(self) -> None: ... + if sys.version_info >= (3, 7): + def get_loop(self) -> AbstractEventLoop: ... + def cancel(self) -> bool: ... + def _schedule_callbacks(self) -> None: ... + def cancelled(self) -> bool: ... + def done(self) -> bool: ... + def result(self) -> _T: ... + def exception(self) -> BaseException: ... + def add_done_callback(self: _S, fn: Callable[[_S], Any]) -> None: ... + def remove_done_callback(self: _S, fn: Callable[[_S], Any]) -> int: ... + def set_result(self, result: _T) -> None: ... + def set_exception(self, exception: Union[type, BaseException]) -> None: ... + def _copy_state(self, other: Any) -> None: ... + def __iter__(self) -> Generator[Any, None, _T]: ... + def __await__(self) -> Generator[Any, None, _T]: ... + +def wrap_future(f: Union[_ConcurrentFuture[_T], Future[_T]]) -> Future[_T]: ... diff --git a/client/typeshed-fallback/stdlib/3/asyncio/locks.pyi b/client/typeshed-fallback/stdlib/3/asyncio/locks.pyi new file mode 100644 index 000000000..56b8a6727 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/asyncio/locks.pyi @@ -0,0 +1,60 @@ +from typing import Any, Callable, Generator, Iterable, Iterator, List, Type, TypeVar, Union, Optional, Awaitable + +from .coroutines import coroutine +from .events import AbstractEventLoop +from .futures import Future +from types import TracebackType + +_T = TypeVar('_T') + +__all__: List[str] + +class _ContextManager: + def __init__(self, lock: Union[Lock, Semaphore]) -> None: ... + def __enter__(self) -> object: ... + def __exit__(self, *args: Any) -> None: ... + +class _ContextManagerMixin(Future[_ContextManager]): + # Apparently this exists to *prohibit* use as a context manager. + def __enter__(self) -> object: ... + def __exit__(self, *args: Any) -> None: ... + def __aenter__(self) -> Awaitable[None]: ... + def __aexit__(self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType]) -> Awaitable[None]: ... + +class Lock(_ContextManagerMixin): + def __init__(self, *, loop: Optional[AbstractEventLoop] = ...) -> None: ... + def locked(self) -> bool: ... + @coroutine + def acquire(self) -> Generator[Any, None, bool]: ... + def release(self) -> None: ... + +class Event: + def __init__(self, *, loop: Optional[AbstractEventLoop] = ...) -> None: ... + def is_set(self) -> bool: ... + def set(self) -> None: ... + def clear(self) -> None: ... + @coroutine + def wait(self) -> Generator[Any, None, bool]: ... + +class Condition(_ContextManagerMixin): + def __init__(self, lock: Optional[Lock] = ..., *, loop: Optional[AbstractEventLoop] = ...) -> None: ... + def locked(self) -> bool: ... + @coroutine + def acquire(self) -> Generator[Any, None, bool]: ... + def release(self) -> None: ... + @coroutine + def wait(self) -> Generator[Any, None, bool]: ... + @coroutine + def wait_for(self, predicate: Callable[[], _T]) -> Generator[Any, None, _T]: ... + def notify(self, n: int = ...) -> None: ... + def notify_all(self) -> None: ... + +class Semaphore(_ContextManagerMixin): + def __init__(self, value: int = ..., *, loop: Optional[AbstractEventLoop] = ...) -> None: ... + def locked(self) -> bool: ... + @coroutine + def acquire(self) -> Generator[Any, None, bool]: ... + def release(self) -> None: ... + +class BoundedSemaphore(Semaphore): + def __init__(self, value: int = ..., *, loop: Optional[AbstractEventLoop] = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/asyncio/protocols.pyi b/client/typeshed-fallback/stdlib/3/asyncio/protocols.pyi new file mode 100644 index 000000000..bb258e119 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/asyncio/protocols.pyi @@ -0,0 +1,24 @@ +from asyncio import transports +from typing import List, Optional, Text, Tuple, Union + +__all__: List[str] + + +class BaseProtocol: + def connection_made(self, transport: transports.BaseTransport) -> None: ... + def connection_lost(self, exc: Optional[Exception]) -> None: ... + def pause_writing(self) -> None: ... + def resume_writing(self) -> None: ... + +class Protocol(BaseProtocol): + def data_received(self, data: bytes) -> None: ... + def eof_received(self) -> Optional[bool]: ... + +class DatagramProtocol(BaseProtocol): + def datagram_received(self, data: Union[bytes, Text], addr: Tuple[str, int]) -> None: ... + def error_received(self, exc: Exception) -> None: ... + +class SubprocessProtocol(BaseProtocol): + def pipe_data_received(self, fd: int, data: Union[bytes, Text]) -> None: ... + def pipe_connection_lost(self, fd: int, exc: Optional[Exception]) -> None: ... + def process_exited(self) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/asyncio/queues.pyi b/client/typeshed-fallback/stdlib/3/asyncio/queues.pyi new file mode 100644 index 000000000..4575943df --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/asyncio/queues.pyi @@ -0,0 +1,50 @@ +import sys +from asyncio.events import AbstractEventLoop +from .coroutines import coroutine +from .futures import Future +from typing import Any, Generator, Generic, List, TypeVar + +__all__: List[str] + + +class QueueEmpty(Exception): ... +class QueueFull(Exception): ... + +_T = TypeVar('_T') + +class Queue(Generic[_T]): + def __init__(self, maxsize: int = ..., *, loop: AbstractEventLoop = ...) -> None: ... + def _init(self, maxsize: int) -> None: ... + def _get(self) -> _T: ... + def _put(self, item: _T) -> None: ... + def __repr__(self) -> str: ... + def __str__(self) -> str: ... + def _format(self) -> str: ... + def _consume_done_getters(self) -> None: ... + def _consume_done_putters(self) -> None: ... + def qsize(self) -> int: ... + @property + def maxsize(self) -> int: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + @coroutine + def put(self, item: _T) -> Generator[Any, None, None]: ... + def put_nowait(self, item: _T) -> None: ... + @coroutine + def get(self) -> Generator[Any, None, _T]: ... + def get_nowait(self) -> _T: ... + @coroutine + def join(self) -> Generator[Any, None, bool]: ... + def task_done(self) -> None: ... + + +class PriorityQueue(Queue[_T]): ... + + +class LifoQueue(Queue[_T]): ... + +if sys.version_info < (3, 5): + class JoinableQueue(Queue[_T]): + def task_done(self) -> None: ... + @coroutine + def join(self) -> Generator[Any, None, bool]: ... diff --git a/client/typeshed-fallback/stdlib/3/asyncio/runners.pyi b/client/typeshed-fallback/stdlib/3/asyncio/runners.pyi new file mode 100644 index 000000000..7d8c28c0d --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/asyncio/runners.pyi @@ -0,0 +1,9 @@ +import sys + + +if sys.version_info >= (3, 7): + from typing import Awaitable, TypeVar + + _T = TypeVar('_T') + + def run(main: Awaitable[_T], *, debug: bool = ...) -> _T: ... diff --git a/client/typeshed-fallback/stdlib/3/asyncio/streams.pyi b/client/typeshed-fallback/stdlib/3/asyncio/streams.pyi new file mode 100644 index 000000000..8ca741259 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/asyncio/streams.pyi @@ -0,0 +1,109 @@ +import sys +from typing import Any, Awaitable, Callable, Generator, Iterable, List, Optional, Tuple, Union + +from . import coroutines +from . import events +from . import protocols +from . import transports + +_ClientConnectedCallback = Callable[[StreamReader, StreamWriter], Optional[Awaitable[None]]] + + +__all__: List[str] + +class IncompleteReadError(EOFError): + expected = ... # type: Optional[int] + partial = ... # type: bytes + def __init__(self, partial: bytes, expected: Optional[int]) -> None: ... + +class LimitOverrunError(Exception): + consumed = ... # type: int + def __init__(self, message: str, consumed: int) -> None: ... + +@coroutines.coroutine +def open_connection( + host: str = ..., + port: Union[int, str] = ..., + *, + loop: Optional[events.AbstractEventLoop] = ..., + limit: int = ..., + **kwds: Any +) -> Generator[Any, None, Tuple[StreamReader, StreamWriter]]: ... + +@coroutines.coroutine +def start_server( + client_connected_cb: _ClientConnectedCallback, + host: Optional[str] = ..., + port: Optional[Union[int, str]] = ..., + *, + loop: Optional[events.AbstractEventLoop] = ..., + limit: int = ..., + **kwds: Any +) -> Generator[Any, None, events.AbstractServer]: ... + +if sys.platform != 'win32': + @coroutines.coroutine + def open_unix_connection( + path: str = ..., + *, + loop: Optional[events.AbstractEventLoop] = ..., + limit: int = ..., + **kwds: Any + ) -> Generator[Any, None, Tuple[StreamReader, StreamWriter]]: ... + + @coroutines.coroutine + def start_unix_server( + client_connected_cb: _ClientConnectedCallback, + path: str = ..., + *, + loop: Optional[events.AbstractEventLoop] = ..., + limit: int = ..., + **kwds: Any) -> Generator[Any, None, events.AbstractServer]: ... + +class FlowControlMixin(protocols.Protocol): ... + +class StreamReaderProtocol(FlowControlMixin, protocols.Protocol): + def __init__(self, + stream_reader: StreamReader, + client_connected_cb: _ClientConnectedCallback = ..., + loop: Optional[events.AbstractEventLoop] = ...) -> None: ... + def connection_made(self, transport: transports.BaseTransport) -> None: ... + def connection_lost(self, exc: Optional[Exception]) -> None: ... + def data_received(self, data: bytes) -> None: ... + def eof_received(self) -> bool: ... + +class StreamWriter: + def __init__(self, + transport: transports.BaseTransport, + protocol: protocols.BaseProtocol, + reader: Optional[StreamReader], + loop: events.AbstractEventLoop) -> None: ... + @property + def transport(self) -> transports.BaseTransport: ... + def write(self, data: bytes) -> None: ... + def writelines(self, data: Iterable[bytes]) -> None: ... + def write_eof(self) -> None: ... + def can_write_eof(self) -> bool: ... + def close(self) -> None: ... + def get_extra_info(self, name: str, default: Any = ...) -> Any: ... + @coroutines.coroutine + def drain(self) -> Generator[Any, None, None]: ... + +class StreamReader: + def __init__(self, + limit: int = ..., + loop: Optional[events.AbstractEventLoop] = ...) -> None: ... + def exception(self) -> Exception: ... + def set_exception(self, exc: Exception) -> None: ... + def set_transport(self, transport: transports.BaseTransport) -> None: ... + def feed_eof(self) -> None: ... + def at_eof(self) -> bool: ... + def feed_data(self, data: bytes) -> None: ... + @coroutines.coroutine + def readline(self) -> Generator[Any, None, bytes]: ... + @coroutines.coroutine + def readuntil(self, separator: bytes = ...) -> Generator[Any, None, bytes]: ... + @coroutines.coroutine + def read(self, n: int = ...) -> Generator[Any, None, bytes]: ... + @coroutines.coroutine + def readexactly(self, n: int) -> Generator[Any, None, bytes]: ... diff --git a/client/typeshed-fallback/stdlib/3/asyncio/subprocess.pyi b/client/typeshed-fallback/stdlib/3/asyncio/subprocess.pyi new file mode 100644 index 000000000..776a3d16e --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/asyncio/subprocess.pyi @@ -0,0 +1,67 @@ +from asyncio import events +from asyncio import protocols +from asyncio import streams +from asyncio import transports +from asyncio.coroutines import coroutine +from typing import Any, Generator, List, Optional, Text, Tuple, Union, IO + +__all__: List[str] + +PIPE = ... # type: int +STDOUT = ... # type: int +DEVNULL = ... # type: int + +class SubprocessStreamProtocol(streams.FlowControlMixin, + protocols.SubprocessProtocol): + stdin = ... # type: Optional[streams.StreamWriter] + stdout = ... # type: Optional[streams.StreamReader] + stderr = ... # type: Optional[streams.StreamReader] + def __init__(self, limit: int, loop: events.AbstractEventLoop) -> None: ... + def connection_made(self, transport: transports.BaseTransport) -> None: ... + def pipe_data_received(self, fd: int, data: Union[bytes, Text]) -> None: ... + def pipe_connection_lost(self, fd: int, exc: Optional[Exception]) -> None: ... + def process_exited(self) -> None: ... + + +class Process: + stdin = ... # type: Optional[streams.StreamWriter] + stdout = ... # type: Optional[streams.StreamReader] + stderr = ... # type: Optional[streams.StreamReader] + pid = ... # type: int + def __init__(self, + transport: transports.BaseTransport, + protocol: protocols.BaseProtocol, + loop: events.AbstractEventLoop) -> None: ... + @property + def returncode(self) -> int: ... + @coroutine + def wait(self) -> Generator[Any, None, int]: ... + def send_signal(self, signal: int) -> None: ... + def terminate(self) -> None: ... + def kill(self) -> None: ... + @coroutine + def communicate(self, input: Optional[bytes] = ...) -> Generator[Any, None, Tuple[bytes, bytes]]: ... + + +@coroutine +def create_subprocess_shell( + *Args: Union[str, bytes], # Union used instead of AnyStr due to mypy issue #1236 + stdin: Union[int, IO[Any], None] = ..., + stdout: Union[int, IO[Any], None] = ..., + stderr: Union[int, IO[Any], None] = ..., + loop: events.AbstractEventLoop = ..., + limit: int = ..., + **kwds: Any +) -> Generator[Any, None, Process]: ... + +@coroutine +def create_subprocess_exec( + program: Union[str, bytes], # Union used instead of AnyStr due to mypy issue #1236 + *args: Any, + stdin: Union[int, IO[Any], None] = ..., + stdout: Union[int, IO[Any], None] = ..., + stderr: Union[int, IO[Any], None] = ..., + loop: events.AbstractEventLoop = ..., + limit: int = ..., + **kwds: Any +) -> Generator[Any, None, Process]: ... diff --git a/client/typeshed-fallback/stdlib/3/asyncio/tasks.pyi b/client/typeshed-fallback/stdlib/3/asyncio/tasks.pyi new file mode 100644 index 000000000..6fe13f57e --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/asyncio/tasks.pyi @@ -0,0 +1,77 @@ +import concurrent.futures +import sys +from typing import (Any, TypeVar, Set, Dict, List, TextIO, Union, Tuple, Generic, Callable, + Coroutine, Generator, Iterable, Awaitable, overload, Sequence, Iterator, + Optional) +from types import FrameType +from .events import AbstractEventLoop +from .futures import Future + +__all__: List[str] + +_T = TypeVar('_T') +_T1 = TypeVar('_T1') +_T2 = TypeVar('_T2') +_T3 = TypeVar('_T3') +_T4 = TypeVar('_T4') +_T5 = TypeVar('_T5') +_FutureT = Union[Future[_T], Generator[Any, None, _T], Awaitable[_T]] + +FIRST_EXCEPTION: str +FIRST_COMPLETED: str +ALL_COMPLETED: str + +def as_completed(fs: Sequence[_FutureT[_T]], *, loop: AbstractEventLoop = ..., + timeout: Optional[float] = ...) -> Iterator[Future[_T]]: ... +def ensure_future(coro_or_future: _FutureT[_T], + *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... +# Prior to Python 3.7 'async' was an alias for 'ensure_future'. +# It became a keyword in 3.7. +@overload +def gather(coro_or_future1: _FutureT[_T1], + *, loop: AbstractEventLoop = ..., return_exceptions: bool = ...) -> Future[Tuple[_T1]]: ... +@overload +def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], + *, loop: AbstractEventLoop = ..., return_exceptions: bool = ...) -> Future[Tuple[_T1, _T2]]: ... +@overload +def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], + *, loop: AbstractEventLoop = ..., return_exceptions: bool = ...) -> Future[Tuple[_T1, _T2, _T3]]: ... +@overload +def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], + coro_or_future4: _FutureT[_T4], + *, loop: AbstractEventLoop = ..., return_exceptions: bool = ...) -> Future[Tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def gather(coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], coro_or_future3: _FutureT[_T3], + coro_or_future4: _FutureT[_T4], coro_or_future5: _FutureT[_T5], + *, loop: AbstractEventLoop = ..., return_exceptions: bool = ...) -> Future[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def gather(coro_or_future1: _FutureT[Any], coro_or_future2: _FutureT[Any], coro_or_future3: _FutureT[Any], + coro_or_future4: _FutureT[Any], coro_or_future5: _FutureT[Any], coro_or_future6: _FutureT[Any], + *coros_or_futures: _FutureT[Any], + loop: AbstractEventLoop = ..., return_exceptions: bool = ...) -> Future[Tuple[Any, ...]]: ... +def run_coroutine_threadsafe(coro: _FutureT[_T], + loop: AbstractEventLoop) -> concurrent.futures.Future[_T]: ... +def shield(arg: _FutureT[_T], *, loop: AbstractEventLoop = ...) -> Future[_T]: ... +def sleep(delay: float, result: _T = ..., loop: AbstractEventLoop = ...) -> Future[_T]: ... +def wait(fs: Iterable[_FutureT[_T]], *, loop: AbstractEventLoop = ..., timeout: Optional[float] = ..., + return_when: str = ...) -> Future[Tuple[Set[Future[_T]], Set[Future[_T]]]]: ... +def wait_for(fut: _FutureT[_T], timeout: Optional[float], + *, loop: AbstractEventLoop = ...) -> Future[_T]: ... + +class Task(Future[_T], Generic[_T]): + @classmethod + def current_task(cls, loop: Optional[AbstractEventLoop] = ...) -> Task: ... + @classmethod + def all_tasks(cls, loop: Optional[AbstractEventLoop] = ...) -> Set[Task]: ... + def __init__(self, coro: Union[Generator[Any, None, _T], Awaitable[_T]], *, loop: AbstractEventLoop = ...) -> None: ... + def __repr__(self) -> str: ... + def get_stack(self, *, limit: int = ...) -> List[FrameType]: ... + def print_stack(self, *, limit: int = ..., file: TextIO = ...) -> None: ... + def cancel(self) -> bool: ... + def _step(self, value: Any = ..., exc: Exception = ...) -> None: ... + def _wakeup(self, future: Future[Any]) -> None: ... + +if sys.version_info >= (3, 7): + def all_tasks(loop: Optional[AbstractEventLoop] = ...) -> Set[Task]: ... + def create_task(coro: Union[Generator[Any, None, _T], Awaitable[_T]]) -> Task: ... + def current_task(loop: Optional[AbstractEventLoop] = ...) -> Optional[Task]: ... diff --git a/client/typeshed-fallback/stdlib/3/asyncio/transports.pyi b/client/typeshed-fallback/stdlib/3/asyncio/transports.pyi new file mode 100644 index 000000000..9ea6688d7 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/asyncio/transports.pyi @@ -0,0 +1,38 @@ +from typing import Dict, Any, TypeVar, Mapping, List, Optional, Tuple + +__all__: List[str] + +class BaseTransport: + def __init__(self, extra: Mapping[Any, Any] = ...) -> None: ... + def get_extra_info(self, name: Any, default: Any = ...) -> Any: ... + def is_closing(self) -> bool: ... + def close(self) -> None: ... + +class ReadTransport(BaseTransport): + def pause_reading(self) -> None: ... + def resume_reading(self) -> None: ... + +class WriteTransport(BaseTransport): + def set_write_buffer_limits( + self, high: int = ..., low: int = ... + ) -> None: ... + def get_write_buffer_size(self) -> int: ... + def write(self, data: Any) -> None: ... + def writelines(self, list_of_data: List[Any]) -> None: ... + def write_eof(self) -> None: ... + def can_write_eof(self) -> bool: ... + def abort(self) -> None: ... + +class Transport(ReadTransport, WriteTransport): ... + +class DatagramTransport(BaseTransport): + def sendto(self, data: Any, addr: Optional[Tuple[str, int]] = ...) -> None: ... + def abort(self) -> None: ... + +class SubprocessTransport(BaseTransport): + def get_pid(self) -> int: ... + def get_returncode(self) -> int: ... + def get_pipe_transport(self, fd: int) -> BaseTransport: ... + def send_signal(self, signal: int) -> int: ... + def terminate(self) -> None: ... + def kill(self) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/atexit.pyi b/client/typeshed-fallback/stdlib/3/atexit.pyi new file mode 100644 index 000000000..24f93899d --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/atexit.pyi @@ -0,0 +1,9 @@ +"""Stub file for the 'atexit' module.""" + +from typing import Any, Callable + +def _clear() -> None: ... +def _ncallbacks() -> int: ... +def _run_exitfuncs() -> None: ... +def register(func: Callable[..., Any], *args: Any, **kwargs: Any) -> Callable[..., Any]: ... +def unregister(func: Callable[..., Any]) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/collections/__init__.pyi b/client/typeshed-fallback/stdlib/3/collections/__init__.pyi new file mode 100644 index 000000000..87e42cac7 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/collections/__init__.pyi @@ -0,0 +1,348 @@ +# These are not exported. +import sys +import typing +from typing import ( + TypeVar, Generic, Dict, overload, List, Tuple, + Any, Type, Optional, Union +) +# These are exported. +from . import abc + +from typing import ( + Callable as Callable, + Container as Container, + Hashable as Hashable, + Iterable as Iterable, + Iterator as Iterator, + Sized as Sized, + Generator as Generator, + ByteString as ByteString, + Reversible as Reversible, + Mapping as Mapping, + MappingView as MappingView, + ItemsView as ItemsView, + KeysView as KeysView, + ValuesView as ValuesView, + MutableMapping as MutableMapping, + Sequence as Sequence, + MutableSequence as MutableSequence, + MutableSet as MutableSet, + AbstractSet as Set, +) +if sys.version_info >= (3, 6): + from typing import ( + Collection as Collection, + AsyncGenerator as AsyncGenerator, + ) +if sys.version_info >= (3, 5): + from typing import ( + Awaitable as Awaitable, + Coroutine as Coroutine, + AsyncIterable as AsyncIterable, + AsyncIterator as AsyncIterator, + ) + +_S = TypeVar('_S') +_T = TypeVar('_T') +_KT = TypeVar('_KT') +_VT = TypeVar('_VT') + + +# namedtuple is special-cased in the type checker; the initializer is ignored. +if sys.version_info >= (3, 7): + def namedtuple(typename: str, field_names: Union[str, Iterable[str]], *, + rename: bool = ..., module: Optional[str] = ..., defaults: Optional[Iterable[Any]] = ...) -> Type[tuple]: ... +elif sys.version_info >= (3, 6): + def namedtuple(typename: str, field_names: Union[str, Iterable[str]], *, + verbose: bool = ..., rename: bool = ..., module: Optional[str] = ...) -> Type[tuple]: ... +else: + def namedtuple(typename: str, field_names: Union[str, Iterable[str]], + verbose: bool = ..., rename: bool = ...) -> Type[tuple]: ... + +_UserDictT = TypeVar('_UserDictT', bound=UserDict) + +class UserDict(MutableMapping[_KT, _VT]): + data: Dict[_KT, _VT] + def __init__(self, dict: Optional[Mapping[_KT, _VT]] = ..., **kwargs: _VT) -> None: ... + def __len__(self) -> int: ... + def __getitem__(self, key: _KT) -> _VT: ... + def __setitem__(self, key: _KT, item: _VT) -> None: ... + def __delitem__(self, key: _KT) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + def __contains__(self, key: object) -> bool: ... + def copy(self: _UserDictT) -> _UserDictT: ... + @classmethod + def fromkeys(cls: Type[_UserDictT], iterable: Iterable[_KT], value: Optional[_VT] = ...) -> _UserDictT: ... + +_UserListT = TypeVar('_UserListT', bound=UserList) + +class UserList(MutableSequence[_T]): + data: List[_T] + def __init__(self, initlist: Optional[Iterable[_T]] = ...) -> None: ... + def __lt__(self, other: object) -> bool: ... + def __le__(self, other: object) -> bool: ... + def __gt__(self, other: object) -> bool: ... + def __ge__(self, other: object) -> bool: ... + def __contains__(self, item: object) -> bool: ... + def __len__(self) -> int: ... + @overload + def __getitem__(self, i: int) -> _T: ... + @overload + def __getitem__(self, i: slice) -> MutableSequence[_T]: ... + @overload + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + def __setitem__(self, i: slice, o: Iterable[_T]) -> None: ... + def __delitem__(self, i: Union[int, slice]) -> None: ... + def __add__(self: _UserListT, other: Iterable[_T]) -> _UserListT: ... + def __iadd__(self: _UserListT, other: Iterable[_T]) -> _UserListT: ... + def __mul__(self: _UserListT, n: int) -> _UserListT: ... + def __imul__(self: _UserListT, n: int) -> _UserListT: ... + def append(self, item: _T) -> None: ... + def insert(self, i: int, item: _T) -> None: ... + def pop(self, i: int = ...) -> _T: ... + def remove(self, item: _T) -> None: ... + def clear(self) -> None: ... + def copy(self: _UserListT) -> _UserListT: ... + def count(self, item: _T) -> int: ... + def index(self, item: _T, *args: Any) -> int: ... + def reverse(self) -> None: ... + def sort(self, *args: Any, **kwds: Any) -> None: ... + def extend(self, other: Iterable[_T]) -> None: ... + +_UserStringT = TypeVar('_UserStringT', bound=UserString) + +class UserString(Sequence[str]): + data: str + def __init__(self, seq: object) -> None: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __complex__(self) -> complex: ... + if sys.version_info >= (3, 5): + def __getnewargs__(self) -> Tuple[str]: ... + def __lt__(self, string: Union[str, UserString]) -> bool: ... + def __le__(self, string: Union[str, UserString]) -> bool: ... + def __gt__(self, string: Union[str, UserString]) -> bool: ... + def __ge__(self, string: Union[str, UserString]) -> bool: ... + def __contains__(self, char: object) -> bool: ... + def __len__(self) -> int: ... + # It should return a str to implement Sequence correctly, but it doesn't. + def __getitem__(self: _UserStringT, i: Union[int, slice]) -> _UserStringT: ... # type: ignore + def __add__(self: _UserStringT, other: object) -> _UserStringT: ... + def __mul__(self: _UserStringT, n: int) -> _UserStringT: ... + def __mod__(self: _UserStringT, args: Any) -> _UserStringT: ... + def capitalize(self: _UserStringT) -> _UserStringT: ... + if sys.version_info >= (3, 5): + def casefold(self: _UserStringT) -> _UserStringT: ... + def center(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... + def count(self, sub: Union[str, UserString], start: int = ..., end: int = ...) -> int: ... + def encode(self: _UserStringT, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> _UserStringT: ... + def endswith(self, suffix: Union[str, Tuple[str, ...]], start: int = ..., end: int = ...) -> bool: ... + def expandtabs(self: _UserStringT, tabsize: int = ...) -> _UserStringT: ... + def find(self, sub: Union[str, UserString], start: int = ..., end: int = ...) -> int: ... + def format(self, *args: Any, **kwds: Any) -> str: ... + if sys.version_info >= (3, 5): + def format_map(self, mapping: Mapping[str, Any]) -> str: ... + def index(self, sub: str, start: int = ..., end: int = ...) -> int: ... + def isalpha(self) -> bool: ... + def isalnum(self) -> bool: ... + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + def isidentifier(self) -> bool: ... + def islower(self) -> bool: ... + def isnumeric(self) -> bool: ... + if sys.version_info >= (3, 5): + def isprintable(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, seq: Iterable[str]) -> str: ... + def ljust(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... + def lower(self: _UserStringT) -> _UserStringT: ... + def lstrip(self: _UserStringT, chars: Optional[str] = ...) -> _UserStringT: ... + if sys.version_info >= (3, 5): + @staticmethod + @overload + def maketrans(x: Union[Dict[int, _T], Dict[str, _T], Dict[Union[str, int], _T]]) -> Dict[int, _T]: ... + @staticmethod + @overload + def maketrans(x: str, y: str, z: str = ...) -> Dict[int, Union[int, None]]: ... + def partition(self, sep: str) -> Tuple[str, str, str]: ... + def replace(self: _UserStringT, old: Union[str, UserString], new: Union[str, UserString], maxsplit: int = ...) -> _UserStringT: ... + def rfind(self, sub: Union[str, UserString], start: int = ..., end: int = ...) -> int: ... + def rindex(self, sub: Union[str, UserString], start: int = ..., end: int = ...) -> int: ... + def rjust(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... + def rpartition(self, sep: str) -> Tuple[str, str, str]: ... + def rstrip(self: _UserStringT, chars: Optional[str] = ...) -> _UserStringT: ... + def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... + def splitlines(self, keepends: bool = ...) -> List[str]: ... + def startswith(self, prefix: Union[str, Tuple[str, ...]], start: int = ..., end: int = ...) -> bool: ... + def strip(self: _UserStringT, chars: Optional[str] = ...) -> _UserStringT: ... + def swapcase(self: _UserStringT) -> _UserStringT: ... + def title(self: _UserStringT) -> _UserStringT: ... + def translate(self: _UserStringT, *args: Any) -> _UserStringT: ... + def upper(self: _UserStringT) -> _UserStringT: ... + def zfill(self: _UserStringT, width: int) -> _UserStringT: ... + + +# Technically, deque only derives from MutableSequence in 3.5 (before then, the insert and index +# methods did not exist). +# But in practice it's not worth losing sleep over. +class deque(MutableSequence[_T], Generic[_T]): + @property + def maxlen(self) -> Optional[int]: ... + def __init__(self, iterable: Iterable[_T] = ..., + maxlen: Optional[int] = ...) -> None: ... + def append(self, x: _T) -> None: ... + def appendleft(self, x: _T) -> None: ... + def clear(self) -> None: ... + if sys.version_info >= (3, 5): + def copy(self) -> deque[_T]: ... + def count(self, x: _T) -> int: ... + def extend(self, iterable: Iterable[_T]) -> None: ... + def extendleft(self, iterable: Iterable[_T]) -> None: ... + def insert(self, i: int, x: _T) -> None: ... + def index(self, x: _T, start: int = ..., stop: int = ...) -> int: ... + def pop(self, i: int = ...) -> _T: ... + def popleft(self) -> _T: ... + def remove(self, value: _T) -> None: ... + def reverse(self) -> None: ... + def rotate(self, n: int) -> None: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __str__(self) -> str: ... + def __hash__(self) -> int: ... + + # These methods of deque don't really take slices, but we need to + # define them as taking a slice to satisfy MutableSequence. + @overload + def __getitem__(self, index: int) -> _T: ... + @overload + def __getitem__(self, s: slice) -> MutableSequence[_T]: + raise TypeError + @overload + def __setitem__(self, i: int, x: _T) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: + raise TypeError + @overload + def __delitem__(self, i: int) -> None: ... + @overload + def __delitem__(self, s: slice) -> None: + raise TypeError + + def __contains__(self, o: object) -> bool: ... + def __reversed__(self) -> Iterator[_T]: ... + + def __iadd__(self: _S, iterable: Iterable[_T]) -> _S: ... + + if sys.version_info >= (3, 5): + def __add__(self, other: deque[_T]) -> deque[_T]: ... + def __mul__(self, other: int) -> deque[_T]: ... + def __imul__(self, other: int) -> None: ... + +_CounterT = TypeVar('_CounterT', bound=Counter) + +class Counter(Dict[_T, int], Generic[_T]): + @overload + def __init__(self, **kwargs: int) -> None: ... + @overload + def __init__(self, mapping: Mapping[_T, int]) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T]) -> None: ... + def copy(self: _CounterT) -> _CounterT: ... + def elements(self) -> Iterator[_T]: ... + + def most_common(self, n: Optional[int] = ...) -> List[Tuple[_T, int]]: ... + + @overload + def subtract(self, __mapping: Mapping[_T, int]) -> None: ... + @overload + def subtract(self, iterable: Iterable[_T]) -> None: ... + + # The Iterable[Tuple[...]] argument type is not actually desirable + # (the tuples will be added as keys, breaking type safety) but + # it's included so that the signature is compatible with + # Dict.update. Not sure if we should use '# type: ignore' instead + # and omit the type from the union. + @overload + def update(self, __m: Mapping[_T, int], **kwargs: int) -> None: ... + @overload + def update(self, __m: Union[Iterable[_T], Iterable[Tuple[_T, int]]], **kwargs: int) -> None: ... + @overload + def update(self, **kwargs: int) -> None: ... + + def __add__(self, other: Counter[_T]) -> Counter[_T]: ... + def __sub__(self, other: Counter[_T]) -> Counter[_T]: ... + def __and__(self, other: Counter[_T]) -> Counter[_T]: ... + def __or__(self, other: Counter[_T]) -> Counter[_T]: ... + def __pos__(self) -> Counter[_T]: ... + def __neg__(self) -> Counter[_T]: ... + def __iadd__(self, other: Counter[_T]) -> Counter[_T]: ... + def __isub__(self, other: Counter[_T]) -> Counter[_T]: ... + def __iand__(self, other: Counter[_T]) -> Counter[_T]: ... + def __ior__(self, other: Counter[_T]) -> Counter[_T]: ... + +_OrderedDictT = TypeVar('_OrderedDictT', bound=OrderedDict) + +class _OrderedDictKeysView(KeysView[_KT], Reversible[_KT]): + def __reversed__(self) -> Iterator[_KT]: ... +class _OrderedDictItemsView(ItemsView[_KT, _VT], Reversible[Tuple[_KT, _VT]]): + def __reversed__(self) -> Iterator[Tuple[_KT, _VT]]: ... +class _OrderedDictValuesView(ValuesView[_VT], Reversible[_VT]): + def __reversed__(self) -> Iterator[_VT]: ... + +class OrderedDict(Dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): + def popitem(self, last: bool = ...) -> Tuple[_KT, _VT]: ... + def move_to_end(self, key: _KT, last: bool = ...) -> None: ... + def copy(self: _OrderedDictT) -> _OrderedDictT: ... + def __reversed__(self) -> Iterator[_KT]: ... + def keys(self) -> _OrderedDictKeysView[_KT]: ... + def items(self) -> _OrderedDictItemsView[_KT, _VT]: ... + def values(self) -> _OrderedDictValuesView[_VT]: ... + +_DefaultDictT = TypeVar('_DefaultDictT', bound=defaultdict) + +class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): + default_factory = ... # type: Optional[Callable[[], _VT]] + + @overload + def __init__(self, **kwargs: _VT) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]]) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], + map: Mapping[_KT, _VT]) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], + map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], + iterable: Iterable[Tuple[_KT, _VT]]) -> None: ... + @overload + def __init__(self, default_factory: Optional[Callable[[], _VT]], + iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __missing__(self, key: _KT) -> _VT: ... + # TODO __reversed__ + def copy(self: _DefaultDictT) -> _DefaultDictT: ... + +class ChainMap(MutableMapping[_KT, _VT], Generic[_KT, _VT]): + def __init__(self, *maps: Mapping[_KT, _VT]) -> None: ... + + @property + def maps(self) -> List[Mapping[_KT, _VT]]: ... + + def new_child(self, m: Mapping[_KT, _VT] = ...) -> typing.ChainMap[_KT, _VT]: ... + + @property + def parents(self) -> typing.ChainMap[_KT, _VT]: ... + + def __setitem__(self, k: _KT, v: _VT) -> None: ... + def __delitem__(self, v: _KT) -> None: ... + def __getitem__(self, k: _KT) -> _VT: ... + def __iter__(self) -> Iterator[_KT]: ... + def __len__(self) -> int: ... diff --git a/client/typeshed-fallback/stdlib/3/collections/abc.pyi b/client/typeshed-fallback/stdlib/3/collections/abc.pyi new file mode 100644 index 000000000..a9577285c --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/collections/abc.pyi @@ -0,0 +1,40 @@ +# Stubs for collections.abc (introduced from Python 3.3) +# +# https://docs.python.org/3.3/whatsnew/3.3.html#collections +import sys + +from . import ( + Container as Container, + Hashable as Hashable, + Iterable as Iterable, + Iterator as Iterator, + Sized as Sized, + Callable as Callable, + Mapping as Mapping, + MutableMapping as MutableMapping, + Sequence as Sequence, + MutableSequence as MutableSequence, + Set as Set, + MutableSet as MutableSet, + MappingView as MappingView, + ItemsView as ItemsView, + KeysView as KeysView, + ValuesView as ValuesView, +) + +if sys.version_info >= (3, 5): + from . import ( + Generator as Generator, + ByteString as ByteString, + Awaitable as Awaitable, + Coroutine as Coroutine, + AsyncIterable as AsyncIterable, + AsyncIterator as AsyncIterator, + ) + +if sys.version_info >= (3, 6): + from . import ( + Collection as Collection, + Reversible as Reversible, + AsyncGenerator as AsyncGenerator, + ) diff --git a/client/typeshed-fallback/stdlib/3/compileall.pyi b/client/typeshed-fallback/stdlib/3/compileall.pyi new file mode 100644 index 000000000..8d2731c05 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/compileall.pyi @@ -0,0 +1,20 @@ +# Stubs for compileall (Python 3) + +import os +import sys +from typing import Optional, Union, Pattern + +if sys.version_info < (3, 6): + _Path = Union[str, bytes] + _SuccessType = bool +else: + _Path = Union[str, bytes, os.PathLike] + _SuccessType = int + +# rx can be any object with a 'search' method; once we have Protocols we can change the type +if sys.version_info < (3, 5): + def compile_dir(dir: _Path, maxlevels: int = ..., ddir: Optional[_Path] = ..., force: bool = ..., rx: Optional[Pattern] = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ...) -> _SuccessType: ... +else: + def compile_dir(dir: _Path, maxlevels: int = ..., ddir: Optional[_Path] = ..., force: bool = ..., rx: Optional[Pattern] = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ..., workers: int = ...) -> _SuccessType: ... +def compile_file(fullname: _Path, ddir: Optional[_Path] = ..., force: bool = ..., rx: Optional[Pattern] = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ...) -> _SuccessType: ... +def compile_path(skip_curdir: bool = ..., maxlevels: int = ..., force: bool = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ...) -> _SuccessType: ... diff --git a/client/typeshed-fallback/stdlib/3/concurrent/__init__.pyi b/client/typeshed-fallback/stdlib/3/concurrent/__init__.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/3/concurrent/futures/__init__.pyi b/client/typeshed-fallback/stdlib/3/concurrent/futures/__init__.pyi new file mode 100644 index 000000000..4439dcadb --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/concurrent/futures/__init__.pyi @@ -0,0 +1,3 @@ +from ._base import * # noqa: F403 +from .thread import * # noqa: F403 +from .process import * # noqa: F403 diff --git a/client/typeshed-fallback/stdlib/3/concurrent/futures/_base.pyi b/client/typeshed-fallback/stdlib/3/concurrent/futures/_base.pyi new file mode 100644 index 000000000..5ffc07be5 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/concurrent/futures/_base.pyi @@ -0,0 +1,56 @@ +from typing import TypeVar, Generic, Any, Iterable, Iterator, Callable, Tuple, Optional, Set, NamedTuple +from types import TracebackType +import sys + +FIRST_COMPLETED = ... # type: str +FIRST_EXCEPTION = ... # type: str +ALL_COMPLETED = ... # type: str +PENDING = ... # type: Any +RUNNING = ... # type: Any +CANCELLED = ... # type: Any +CANCELLED_AND_NOTIFIED = ... # type: Any +FINISHED = ... # type: Any +LOGGER = ... # type: Any + +class Error(Exception): ... +class CancelledError(Error): ... +class TimeoutError(Error): ... + +_T = TypeVar('_T') + +class Future(Generic[_T]): + def __init__(self) -> None: ... + def cancel(self) -> bool: ... + def cancelled(self) -> bool: ... + def running(self) -> bool: ... + def done(self) -> bool: ... + def add_done_callback(self, fn: Callable[[Future[_T]], Any]) -> None: ... + def result(self, timeout: Optional[float] = ...) -> _T: ... + def set_running_or_notify_cancel(self) -> bool: ... + def set_result(self, result: _T) -> None: ... + + if sys.version_info >= (3,): + def exception(self, timeout: Optional[float] = ...) -> Optional[BaseException]: ... + def set_exception(self, exception: Optional[BaseException]) -> None: ... + else: + def exception(self, timeout: Optional[float] = ...) -> Any: ... + def exception_info(self, timeout: Optional[float] = ...) -> Tuple[Any, Optional[TracebackType]]: ... + def set_exception(self, exception: Any) -> None: ... + def set_exception_info(self, exception: Any, traceback: Optional[TracebackType]) -> None: ... + + +class Executor: + def submit(self, fn: Callable[..., _T], *args: Any, **kwargs: Any) -> Future[_T]: ... + if sys.version_info >= (3, 5): + def map(self, func: Callable[..., _T], *iterables: Iterable[Any], timeout: Optional[float] = ..., + chunksize: int = ...) -> Iterator[_T]: ... + else: + def map(self, func: Callable[..., _T], *iterables: Iterable[Any], timeout: Optional[float] = ...,) -> Iterator[_T]: ... + def shutdown(self, wait: bool = ...) -> None: ... + def __enter__(self: _T) -> _T: ... + def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> bool: ... + +def as_completed(fs: Iterable[Future[_T]], timeout: Optional[float] = ...) -> Iterator[Future[_T]]: ... + +def wait(fs: Iterable[Future[_T]], timeout: Optional[float] = ..., return_when: str = ...) -> Tuple[Set[Future[_T]], + Set[Future[_T]]]: ... diff --git a/client/typeshed-fallback/stdlib/3/concurrent/futures/process.pyi b/client/typeshed-fallback/stdlib/3/concurrent/futures/process.pyi new file mode 100644 index 000000000..3d50123c8 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/concurrent/futures/process.pyi @@ -0,0 +1,17 @@ +from typing import Any, Callable, Optional, Tuple +from ._base import Future, Executor +import sys + +EXTRA_QUEUED_CALLS = ... # type: Any + +if sys.version_info >= (3,): + class BrokenProcessPool(RuntimeError): ... + +if sys.version_info >= (3, 7): + class ProcessPoolExecutor(Executor): + def __init__(self, max_workers: Optional[int] = ..., + initializer: Optional[Callable[..., None]] = ..., + initargs: Tuple[Any, ...] = ...) -> None: ... +else: + class ProcessPoolExecutor(Executor): + def __init__(self, max_workers: Optional[int] = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/concurrent/futures/thread.pyi b/client/typeshed-fallback/stdlib/3/concurrent/futures/thread.pyi new file mode 100644 index 000000000..983594dc7 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/concurrent/futures/thread.pyi @@ -0,0 +1,15 @@ +from typing import Any, Callable, Optional, Tuple +from ._base import Executor, Future +import sys + +class ThreadPoolExecutor(Executor): + if sys.version_info >= (3, 7): + def __init__(self, max_workers: Optional[int] = ..., + thread_name_prefix: str = ..., + initializer: Optional[Callable[..., None]] = ..., + initargs: Tuple[Any, ...] = ...) -> None: ... + elif sys.version_info >= (3, 6) or sys.version_info < (3,): + def __init__(self, max_workers: Optional[int] = ..., + thread_name_prefix: str = ...) -> None: ... + else: + def __init__(self, max_workers: Optional[int] = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/configparser.pyi b/client/typeshed-fallback/stdlib/3/configparser.pyi new file mode 100644 index 000000000..2df7b3381 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/configparser.pyi @@ -0,0 +1,231 @@ +# Based on http://docs.python.org/3.5/library/configparser.html and on +# reading configparser.py. + +import sys +from typing import (AbstractSet, MutableMapping, Mapping, Dict, Sequence, List, + Union, Iterable, Iterator, Callable, Any, IO, overload, + Optional, Pattern, Type, TypeVar) +# Types only used in type comments only +from typing import Optional, Tuple # noqa + +if sys.version_info >= (3, 6): + from os import PathLike + +# Internal type aliases +_section = Mapping[str, str] +_parser = MutableMapping[str, _section] +_converter = Callable[[str], Any] +_converters = Dict[str, _converter] +_T = TypeVar('_T') + +if sys.version_info >= (3, 7): + _Path = Union[str, bytes, PathLike[str]] +elif sys.version_info >= (3, 6): + _Path = Union[str, PathLike[str]] +else: + _Path = str + +DEFAULTSECT: str +MAX_INTERPOLATION_DEPTH: int + +class Interpolation: + def before_get(self, parser: _parser, + section: str, + option: str, + value: str, + defaults: _section) -> str: ... + + def before_set(self, parser: _parser, + section: str, + option: str, + value: str) -> str: ... + + def before_read(self, parser: _parser, + section: str, + option: str, + value: str) -> str: ... + + def before_write(self, parser: _parser, + section: str, + option: str, + value: str) -> str: ... + + +class BasicInterpolation(Interpolation): ... +class ExtendedInterpolation(Interpolation): ... +class LegacyInterpolation(Interpolation): ... + + +class RawConfigParser(_parser): + def __init__(self, + defaults: Optional[_section] = ..., + dict_type: Type[Mapping[str, str]] = ..., + allow_no_value: bool = ..., + *, + delimiters: Sequence[str] = ..., + comment_prefixes: Sequence[str] = ..., + inline_comment_prefixes: Optional[Sequence[str]] = ..., + strict: bool = ..., + empty_lines_in_values: bool = ..., + default_section: str = ..., + interpolation: Optional[Interpolation] = ...) -> None: ... + + def __len__(self) -> int: ... + + def __getitem__(self, section: str) -> SectionProxy: ... + + def __setitem__(self, section: str, options: _section) -> None: ... + + def __delitem__(self, section: str) -> None: ... + + def __iter__(self) -> Iterator[str]: ... + + def defaults(self) -> _section: ... + + def sections(self) -> List[str]: ... + + def add_section(self, section: str) -> None: ... + + def has_section(self, section: str) -> bool: ... + + def options(self, section: str) -> List[str]: ... + + def has_option(self, section: str, option: str) -> bool: ... + + def read(self, filenames: Union[_Path, Iterable[_Path]], + encoding: Optional[str] = ...) -> List[str]: ... + def read_file(self, f: Iterable[str], source: Optional[str] = ...) -> None: ... + def read_string(self, string: str, source: str = ...) -> None: ... + def read_dict(self, dictionary: Mapping[str, Mapping[str, Any]], + source: str = ...) -> None: ... + def readfp(self, fp: Iterable[str], filename: Optional[str] = ...) -> None: ... + + # These get* methods are partially applied (with the same names) in + # SectionProxy; the stubs should be kept updated together + def getint(self, section: str, option: str, *, raw: bool = ..., vars: _section = ..., fallback: int = ...) -> int: ... + + def getfloat(self, section: str, option: str, *, raw: bool = ..., vars: _section = ..., fallback: float = ...) -> float: ... + + def getboolean(self, section: str, option: str, *, raw: bool = ..., vars: _section = ..., fallback: bool = ...) -> bool: ... + + def _get_conv(self, section: str, option: str, conv: Callable[[str], _T], *, raw: bool = ..., vars: _section = ..., fallback: _T = ...) -> _T: ... + + # This is incompatible with MutableMapping so we ignore the type + def get(self, section: str, option: str, *, raw: bool = ..., vars: _section = ..., fallback: str = ...) -> str: # type: ignore + ... + + @overload + def items(self, *, raw: bool = ..., vars: _section = ...) -> AbstractSet[Tuple[str, SectionProxy]]: ... + + @overload + def items(self, section: str, raw: bool = ..., vars: _section = ...) -> List[Tuple[str, str]]: ... + + def set(self, section: str, option: str, value: str) -> None: ... + + def write(self, + fileobject: IO[str], + space_around_delimiters: bool = ...) -> None: ... + + def remove_option(self, section: str, option: str) -> bool: ... + + def remove_section(self, section: str) -> bool: ... + + def optionxform(self, option: str) -> str: ... + + +class ConfigParser(RawConfigParser): + def __init__(self, + defaults: Optional[_section] = ..., + dict_type: Type[Mapping[str, str]] = ..., + allow_no_value: bool = ..., + delimiters: Sequence[str] = ..., + comment_prefixes: Sequence[str] = ..., + inline_comment_prefixes: Optional[Sequence[str]] = ..., + strict: bool = ..., + empty_lines_in_values: bool = ..., + default_section: str = ..., + interpolation: Optional[Interpolation] = ..., + converters: _converters = ...) -> None: ... + +class SafeConfigParser(ConfigParser): ... + +class SectionProxy(MutableMapping[str, str]): + def __init__(self, parser: RawConfigParser, name: str) -> None: ... + def __getitem__(self, key: str) -> str: ... + def __setitem__(self, key: str, value: str) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __contains__(self, key: object) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + @property + def parser(self) -> RawConfigParser: ... + @property + def name(self) -> str: ... + def get(self, option: str, fallback: Optional[str] = ..., *, raw: bool = ..., vars: Optional[_section] = ..., **kwargs: Any) -> str: ... # type: ignore + + # These are partially-applied version of the methods with the same names in + # RawConfigParser; the stubs should be kept updated together + def getint(self, option: str, *, raw: bool = ..., vars: _section = ..., fallback: int = ...) -> int: ... + def getfloat(self, option: str, *, raw: bool = ..., vars: _section = ..., fallback: float = ...) -> float: ... + def getboolean(self, option: str, *, raw: bool = ..., vars: _section = ..., fallback: bool = ...) -> bool: ... + + # SectionProxy can have arbitrary attributes when custon converters are used + def __getattr__(self, key: str) -> Callable[..., Any]: ... + +class ConverterMapping(MutableMapping[str, Optional[_converter]]): + GETTERCRE: Pattern + def __init__(self, parser: RawConfigParser) -> None: ... + def __getitem__(self, key: str) -> _converter: ... + def __setitem__(self, key: str, value: Optional[_converter]) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + + +class Error(Exception): ... + + +class NoSectionError(Error): ... + + +class DuplicateSectionError(Error): + section = ... # type: str + source = ... # type: Optional[str] + lineno = ... # type: Optional[int] + + +class DuplicateOptionError(Error): + section = ... # type: str + option = ... # type: str + source = ... # type: Optional[str] + lineno = ... # type: Optional[int] + + +class NoOptionError(Error): + section = ... # type: str + option = ... # type: str + + +class InterpolationError(Error): + section = ... # type: str + option = ... # type: str + + +class InterpolationDepthError(InterpolationError): ... + + +class InterpolationMissingOptionError(InterpolationError): + reference = ... # type: str + + +class InterpolationSyntaxError(InterpolationError): ... + + +class ParsingError(Error): + source = ... # type: str + errors = ... # type: Sequence[Tuple[int, str]] + + +class MissingSectionHeaderError(ParsingError): + lineno = ... # type: int + line = ... # type: str diff --git a/client/typeshed-fallback/stdlib/3/curses/__init__.pyi b/client/typeshed-fallback/stdlib/3/curses/__init__.pyi new file mode 100644 index 000000000..a8d6df47f --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/curses/__init__.pyi @@ -0,0 +1,12 @@ +import _curses +from _curses import * # noqa: F403 +from typing import TypeVar, Callable, Any, Sequence, Mapping + +_T = TypeVar('_T') + +LINES: int +COLS: int + +def initscr() -> _curses._CursesWindow: ... +def start_color() -> None: ... +def wrapper(func: Callable[..., _T], *arg: Any, **kwds: Any) -> _T: ... diff --git a/client/typeshed-fallback/stdlib/3/curses/ascii.pyi b/client/typeshed-fallback/stdlib/3/curses/ascii.pyi new file mode 100644 index 000000000..403376925 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/curses/ascii.pyi @@ -0,0 +1,62 @@ +from typing import List, Union, overload, TypeVar + +_Ch = TypeVar('_Ch', str, int) + +NUL: int +SOH: int +STX: int +ETX: int +EOT: int +ENQ: int +ACK: int +BEL: int +BS: int +TAB: int +HT: int +LF: int +NL: int +VT: int +FF: int +CR: int +SO: int +SI: int +DLE: int +DC1: int +DC2: int +DC3: int +DC4: int +NAK: int +SYN: int +ETB: int +CAN: int +EM: int +SUB: int +ESC: int +FS: int +GS: int +RS: int +US: int +SP: int +DEL: int + +controlnames: List[int] + +def isalnum(c: Union[str, int]) -> bool: ... +def isalpha(c: Union[str, int]) -> bool: ... +def isascii(c: Union[str, int]) -> bool: ... +def isblank(c: Union[str, int]) -> bool: ... +def iscntrl(c: Union[str, int]) -> bool: ... +def isdigit(c: Union[str, int]) -> bool: ... +def isgraph(c: Union[str, int]) -> bool: ... +def islower(c: Union[str, int]) -> bool: ... +def isprint(c: Union[str, int]) -> bool: ... +def ispunct(c: Union[str, int]) -> bool: ... +def isspace(c: Union[str, int]) -> bool: ... +def isupper(c: Union[str, int]) -> bool: ... +def isxdigit(c: Union[str, int]) -> bool: ... +def isctrl(c: Union[str, int]) -> bool: ... +def ismeta(c: Union[str, int]) -> bool: ... +def ascii(c: _Ch) -> _Ch: ... +def ctrl(c: _Ch) -> _Ch: ... +def alt(c: _Ch) -> _Ch: ... +def unctrl(c: Union[str, int]) -> str: ... diff --git a/client/typeshed-fallback/stdlib/3/curses/panel.pyi b/client/typeshed-fallback/stdlib/3/curses/panel.pyi new file mode 100644 index 000000000..90f70c4f7 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/curses/panel.pyi @@ -0,0 +1,20 @@ +from _curses import _CursesWindow + +class _Curses_Panel: # type is (note the space in the class name) + def above(self) -> _Curses_Panel: ... + def below(self) -> _Curses_Panel: ... + def bottom(self) -> None: ... + def hidden(self) -> bool: ... + def hide(self) -> None: ... + def move(self, y: int, x: int) -> None: ... + def replace(self, win: _CursesWindow) -> None: ... + def set_userptr(self, obj: object) -> None: ... + def show(self) -> None: ... + def top(self) -> None: ... + def userptr(self) -> object: ... + def window(self) -> _CursesWindow: ... + +def bottom_panel() -> _Curses_Panel: ... +def new_panel(win: _CursesWindow) -> _Curses_Panel: ... +def top_panel() -> _Curses_Panel: ... +def update_panels() -> _Curses_Panel: ... diff --git a/client/typeshed-fallback/stdlib/3/curses/textpad.pyi b/client/typeshed-fallback/stdlib/3/curses/textpad.pyi new file mode 100644 index 000000000..a218564c0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/curses/textpad.pyi @@ -0,0 +1,11 @@ +from _curses import _CursesWindow +from typing import Callable, Union + +def rectangle(win: _CursesWindow, uly: int, ulx: int, lry: int, lrx: int) -> None: ... + +class Textbox: + stripspaces: bool + def __init__(self, w: _CursesWindow, insert_mode: bool = ...) -> None: ... + def edit(self, validate: Callable[[int], int]) -> str: ... + def do_command(self, ch: Union[str, int]) -> None: ... + def gather(self) -> str: ... diff --git a/client/typeshed-fallback/stdlib/3/email/__init__.pyi b/client/typeshed-fallback/stdlib/3/email/__init__.pyi new file mode 100644 index 000000000..ec7c25bd4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/__init__.pyi @@ -0,0 +1,26 @@ +# Stubs for email (Python 3.4) + +from typing import Callable, Optional, IO +import sys +from email.message import Message +from email.policy import Policy + +def message_from_string(s: str, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... +def message_from_bytes(s: bytes, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... +def message_from_file(fp: IO[str], _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... +def message_from_binary_file(fp: IO[bytes], _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... + +# Names in __all__ with no definition: +# base64mime +# charset +# encoders +# errors +# feedparser +# generator +# header +# iterators +# message +# mime +# parser +# quoprimime +# utils diff --git a/client/typeshed-fallback/stdlib/3/email/charset.pyi b/client/typeshed-fallback/stdlib/3/email/charset.pyi new file mode 100644 index 000000000..979726607 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/charset.pyi @@ -0,0 +1,31 @@ +# Stubs for email.charset (Python 3.4) + +from typing import List, Optional, Iterator, Any + +QP: int +BASE64: int +SHORTEST: int + +class Charset: + input_charset = ... # type: str + header_encoding = ... # type: int + body_encoding = ... # type: int + output_charset = ... # type: Optional[str] + input_codec = ... # type: Optional[str] + output_codec = ... # type: Optional[str] + def __init__(self, input_charset: str = ...) -> None: ... + def get_body_encoding(self) -> str: ... + def get_output_charset(self) -> Optional[str]: ... + def header_encode(self, string: str) -> str: ... + def header_encode_lines(self, string: str, + maxlengths: Iterator[int]) -> List[str]: ... + def body_encode(self, string: str) -> str: ... + def __str__(self) -> str: ... + def __eq__(self, other: Any) -> bool: ... + def __ne__(self, other: Any) -> bool: ... + +def add_charset(charset: str, header_enc: Optional[int] = ..., + body_enc: Optional[int] = ..., + output_charset: Optional[str] = ...) -> None: ... +def add_alias(alias: str, canonical: str) -> None: ... +def add_codec(charset: str, codecname: str) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/email/contentmanager.pyi b/client/typeshed-fallback/stdlib/3/email/contentmanager.pyi new file mode 100644 index 000000000..096347409 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/contentmanager.pyi @@ -0,0 +1,15 @@ +# Stubs for email.contentmanager (Python 3.4) + +from typing import Any, Callable +from email.message import Message + +class ContentManager: + def __init__(self) -> None: ... + def get_content(self, msg: Message, *args: Any, **kw: Any) -> Any: ... + def set_content(self, msg: Message, obj: Any, *args: Any, + **kw: Any) -> Any: ... + def add_get_handler(self, key: str, handler: Callable[..., Any]) -> None: ... + def add_set_handler(self, typekey: type, + handler: Callable[..., Any]) -> None: ... + +raw_data_manager = ... # type: ContentManager diff --git a/client/typeshed-fallback/stdlib/3/email/encoders.pyi b/client/typeshed-fallback/stdlib/3/email/encoders.pyi new file mode 100644 index 000000000..bb5c84cb1 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/encoders.pyi @@ -0,0 +1,8 @@ +# Stubs for email.encoders (Python 3.4) + +from email.message import Message + +def encode_base64(msg: Message) -> None: ... +def encode_quopri(msg: Message) -> None: ... +def encode_7or8bit(msg: Message) -> None: ... +def encode_noop(msg: Message) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/email/errors.pyi b/client/typeshed-fallback/stdlib/3/email/errors.pyi new file mode 100644 index 000000000..77d9902cc --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/errors.pyi @@ -0,0 +1,19 @@ +# Stubs for email.errors (Python 3.4) + +class MessageError(Exception): ... +class MessageParseError(MessageError): ... +class HeaderParseError(MessageParseError): ... +class BoundaryError(MessageParseError): ... +class MultipartConversionError(MessageError, TypeError): ... + +class MessageDefect(ValueError): ... +class NoBoundaryInMultipartDefect(MessageDefect): ... +class StartBoundaryNotFoundDefect(MessageDefect): ... +class FirstHeaderLineIsContinuationDefect(MessageDefect): ... +class MisplacedEnvelopeHeaderDefect(MessageDefect): ... +class MalformedHeaderDefect(MessageDefect): ... +class MultipartInvariantViolationDefect(MessageDefect): ... +class InvalidBase64PaddingDefect(MessageDefect): ... +class InvalidBase64CharactersDefect(MessageDefect): ... +class CloseBoundaryNotFoundDefect(MessageDefect): ... +class MissingHeaderBodySeparatorDefect(MessageDefect): ... diff --git a/client/typeshed-fallback/stdlib/3/email/feedparser.pyi b/client/typeshed-fallback/stdlib/3/email/feedparser.pyi new file mode 100644 index 000000000..48d940b39 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/feedparser.pyi @@ -0,0 +1,18 @@ +# Stubs for email.feedparser (Python 3.4) + +from typing import Callable +import sys +from email.message import Message +from email.policy import Policy + +class FeedParser: + def __init__(self, _factory: Callable[[], Message] = ..., *, + policy: Policy = ...) -> None: ... + def feed(self, data: str) -> None: ... + def close(self) -> Message: ... + +class BytesFeedParser: + def __init__(self, _factory: Callable[[], Message] = ..., *, + policy: Policy = ...) -> None: ... + def feed(self, data: str) -> None: ... + def close(self) -> Message: ... diff --git a/client/typeshed-fallback/stdlib/3/email/generator.pyi b/client/typeshed-fallback/stdlib/3/email/generator.pyi new file mode 100644 index 000000000..036f26ee7 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/generator.pyi @@ -0,0 +1,28 @@ +# Stubs for email.generator (Python 3.4) + +from typing import TextIO, Optional +from email.message import Message +from email.policy import Policy + +class Generator: + def clone(self, fp: TextIO) -> Generator: ... + def write(self, s: str) -> None: ... + def __init__(self, outfp: TextIO, mangle_from_: bool = ..., + maxheaderlen: int = ..., *, + policy: Policy = ...) -> None: ... + def flatten(self, msg: Message, unixfrom: bool = ..., + linesep: Optional[str] = ...) -> None: ... + +class BytesGenerator: + def clone(self, fp: TextIO) -> Generator: ... + def write(self, s: str) -> None: ... + def __init__(self, outfp: TextIO, mangle_from_: bool = ..., + maxheaderlen: int = ..., *, + policy: Policy = ...) -> None: ... + def flatten(self, msg: Message, unixfrom: bool = ..., + linesep: Optional[str] = ...) -> None: ... + +class DecodedGenerator(Generator): + # TODO `fmt` is positional + def __init__(self, outfp: TextIO, mangle_from_: bool = ..., + maxheaderlen: int = ..., *, fmt: Optional[str]=...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/email/header.pyi b/client/typeshed-fallback/stdlib/3/email/header.pyi new file mode 100644 index 000000000..21b999530 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/header.pyi @@ -0,0 +1,25 @@ +# Stubs for email.header (Python 3.4) + +from typing import Union, Optional, Any, List, Tuple +from email.charset import Charset + +class Header: + def __init__(self, s: Union[bytes, str, None] = ..., + charset: Union[Charset, str, None] = ..., + maxlinelen: Optional[int] = ..., + header_name: Optional[str] = ..., continuation_ws: str = ..., + errors: str = ...) -> None: ... + def append(self, s: Union[bytes, str], + charset: Union[Charset, str, None] = ..., + errors: str = ...) -> None: ... + def encode(self, splitchars: str = ..., maxlinelen: Optional[int] = ..., + linesep: str = ...) -> str: ... + def __str__(self) -> str: ... + def __eq__(self, other: Any) -> bool: ... + def __ne__(self, other: Any) -> bool: ... + +def decode_header(header: Union[Header, str]) -> List[Tuple[bytes, Optional[str]]]: ... +def make_header(decoded_seq: List[Tuple[bytes, Optional[str]]], + maxlinelen: Optional[int] = ..., + header_name: Optional[str] = ..., + continuation_ws: str = ...) -> Header: ... diff --git a/client/typeshed-fallback/stdlib/3/email/headerregistry.pyi b/client/typeshed-fallback/stdlib/3/email/headerregistry.pyi new file mode 100644 index 000000000..10a8b8509 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/headerregistry.pyi @@ -0,0 +1,97 @@ +# Stubs for email.headerregistry (Python 3.4) + +from datetime import datetime as _datetime +from typing import Dict, Tuple, Optional, Any, Union, Mapping +from email.errors import MessageDefect +from email.policy import Policy + +class BaseHeader(str): + @property + def name(self) -> str: ... + @property + def defects(self) -> Tuple[MessageDefect, ...]: ... + @property + def max_count(self) -> Optional[int]: ... + def __new__(cls, name: str, value: Any) -> BaseHeader: ... + def init(self, *args: Any, **kw: Any) -> None: ... + def fold(self, *, policy: Policy) -> str: ... + +class UnstructuredHeader: + @classmethod + def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + +class UniqueUnstructuredHeader(UnstructuredHeader): ... + +class DateHeader: + datetime = ... # type: _datetime + @classmethod + def parse(cls, string: Union[str, _datetime], + kwds: Dict[str, Any]) -> None: ... + +class UniqueDateHeader(DateHeader): ... + +class AddressHeader: + groups = ... # type: Tuple[Group, ...] + addresses = ... # type: Tuple[Address, ...] + @classmethod + def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + +class UniqueAddressHeader(AddressHeader): ... + +class SingleAddressHeader(AddressHeader): + @property + def address(self) -> Address: ... + +class UniqueSingleAddressHeader(SingleAddressHeader): ... + +class MIMEVersionHeader: + version = ... # type: Optional[str] + major = ... # type: Optional[int] + minor = ... # type: Optional[int] + @classmethod + def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + +class ParameterizedMIMEHeader: + params = ... # type: Mapping[str, Any] + @classmethod + def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + +class ContentTypeHeader(ParameterizedMIMEHeader): + content_type = ... # type: str + maintype = ... # type: str + subtype = ... # type: str + +class ContentDispositionHeader(ParameterizedMIMEHeader): + content_disposition = ... # type: str + +class ContentTransferEncodingHeader: + cte = ... # type: str + @classmethod + def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + +class HeaderRegistry: + def __init__(self, base_class: BaseHeader = ..., + default_class: BaseHeader = ..., + use_default_map: bool = ...) -> None: ... + def map_to_type(self, name: str, cls: BaseHeader) -> None: ... + def __getitem__(self, name: str) -> BaseHeader: ... + def __call__(self, name: str, value: Any) -> BaseHeader: ... + +class Address: + display_name = ... # type: str + username = ... # type: str + domain = ... # type: str + @property + def addr_spec(self) -> str: ... + def __init__(self, display_name: str = ..., + username: Optional[str] = ..., + domain: Optional[str] = ..., + addr_spec: Optional[str] = ...) -> None: ... + def __str__(self) -> str: ... + +class Group: + display_name = ... # type: Optional[str] + addresses = ... # type: Tuple[Address, ...] + def __init__(self, display_name: Optional[str] = ..., + addresses: Optional[Tuple[Address, ...]] = ...) -> None: ... + def __str__(self) -> str: ... diff --git a/client/typeshed-fallback/stdlib/3/email/iterators.pyi b/client/typeshed-fallback/stdlib/3/email/iterators.pyi new file mode 100644 index 000000000..6a69f39c9 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/iterators.pyi @@ -0,0 +1,8 @@ +# Stubs for email.iterators (Python 3.4) + +from typing import Iterator, Optional +from email.message import Message + +def body_line_iterator(msg: Message, decode: bool = ...) -> Iterator[str]: ... +def typed_subpart_iterator(msg: Message, maintype: str = ..., + subtype: Optional[str] = ...) -> Iterator[str]: ... diff --git a/client/typeshed-fallback/stdlib/3/email/message.pyi b/client/typeshed-fallback/stdlib/3/email/message.pyi new file mode 100644 index 000000000..946dca242 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/message.pyi @@ -0,0 +1,105 @@ +# Stubs for email.message (Python 3.4) + +from typing import ( + List, Optional, Union, Tuple, TypeVar, Generator, Sequence, Iterator, Any +) +import sys +from email.charset import Charset +from email.errors import MessageDefect +from email.header import Header +from email.policy import Policy +from email.contentmanager import ContentManager + +_T = TypeVar('_T') + +_PayloadType = Union[List[Message], str, bytes] +_CharsetType = Union[Charset, str, None] +_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] +_ParamType = Union[str, Tuple[Optional[str], Optional[str], str]] +_HeaderType = Union[str, Header] + +class Message: + preamble = ... # type: Optional[str] + epilogue = ... # type: Optional[str] + defects = ... # type: List[MessageDefect] + def __str__(self) -> str: ... + def is_multipart(self) -> bool: ... + def set_unixfrom(self, unixfrom: str) -> None: ... + def get_unixfrom(self) -> Optional[str]: ... + def attach(self, payload: Message) -> None: ... + def get_payload(self, i: int = ..., decode: bool = ...) -> Optional[_PayloadType]: ... + def set_payload(self, payload: _PayloadType, + charset: _CharsetType = ...) -> None: ... + def set_charset(self, charset: _CharsetType) -> None: ... + def get_charset(self) -> _CharsetType: ... + def __len__(self) -> int: ... + def __contains__(self, name: str) -> bool: ... + def __getitem__(self, name: str) -> Optional[_HeaderType]: ... + def __setitem__(self, name: str, val: _HeaderType) -> None: ... + def __delitem__(self, name: str) -> None: ... + def keys(self) -> List[str]: ... + def values(self) -> List[_HeaderType]: ... + def items(self) -> List[Tuple[str, _HeaderType]]: ... + def get(self, name: str, failobj: _T = ...) -> Union[_HeaderType, _T]: ... + def get_all(self, name: str, failobj: _T = ...) -> Union[List[_HeaderType], _T]: ... + def add_header(self, _name: str, _value: str, **_params: _ParamsType) -> None: ... + def replace_header(self, _name: str, _value: _HeaderType) -> None: ... + def get_content_type(self) -> str: ... + def get_content_maintype(self) -> str: ... + def get_content_subtype(self) -> str: ... + def get_default_type(self) -> str: ... + def set_default_type(self, ctype: str) -> None: ... + def get_params(self, failobj: _T = ..., header: str = ..., + unquote: bool = ...) -> Union[List[Tuple[str, str]], _T]: ... + def get_param(self, param: str, failobj: _T = ..., header: str = ..., + unquote: bool = ...) -> Union[_T, _ParamType]: ... + def del_param(self, param: str, header: str = ..., + requote: bool = ...) -> None: ... + def set_type(self, type: str, header: str = ..., + requote: bool = ...) -> None: ... + def get_filename(self, failobj: _T = ...) -> Union[_T, str]: ... + def get_boundary(self, failobj: _T = ...) -> Union[_T, str]: ... + def set_boundary(self, boundary: str) -> None: ... + def get_content_charset(self, failobj: _T = ...) -> Union[_T, str]: ... + def get_charsets(self, failobj: _T = ...) -> Union[_T, List[str]]: ... + def walk(self) -> Generator[Message, None, None]: ... + if sys.version_info >= (3, 5): + def get_content_disposition(self) -> Optional[str]: ... + def as_string(self, unixfrom: bool = ..., maxheaderlen: int = ..., + policy: Optional[Policy] = ...) -> str: ... + def as_bytes(self, unixfrom: bool = ..., + policy: Optional[Policy] = ...) -> bytes: ... + def __bytes__(self) -> bytes: ... + def set_param(self, param: str, value: str, header: str = ..., + requote: bool = ..., charset: str = ..., + language: str = ..., replace: bool = ...) -> None: ... + def __init__(self, policy: Policy = ...) -> None: ... + +class MIMEPart(Message): + def get_body(self, + preferencelist: Sequence[str] = ...) -> Optional[Message]: ... + def iter_attachments(self) -> Iterator[Message]: ... + def iter_parts(self) -> Iterator[Message]: ... + def get_content(self, *args: Any, + content_manager: Optional[ContentManager] = ..., + **kw: Any) -> Any: ... + def set_content(self, *args: Any, + content_manager: Optional[ContentManager] = ..., + **kw: Any) -> None: ... + def make_related(self, boundary: Optional[str] = ...) -> None: ... + def make_alternative(self, boundary: Optional[str] = ...) -> None: ... + def make_mixed(self, boundary: Optional[str] = ...) -> None: ... + def add_related(self, *args: Any, + content_manager: Optional[ContentManager] = ..., + **kw: Any) -> None: ... + def add_alternative(self, *args: Any, + content_manager: Optional[ContentManager] = ..., + **kw: Any) -> None: ... + def add_attachment(self, *args: Any, + content_manager: Optional[ContentManager] = ..., + **kw: Any) -> None: ... + def clear(self) -> None: ... + def clear_content(self) -> None: ... + def is_attachment(self) -> bool: ... + +class EmailMessage(MIMEPart): ... diff --git a/client/typeshed-fallback/stdlib/3/email/mime/__init__.pyi b/client/typeshed-fallback/stdlib/3/email/mime/__init__.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/3/email/mime/application.pyi b/client/typeshed-fallback/stdlib/3/email/mime/application.pyi new file mode 100644 index 000000000..1aa0580ec --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/mime/application.pyi @@ -0,0 +1,11 @@ +# Stubs for email.mime.application (Python 3.4) + +from typing import Callable, Optional, Tuple, Union +from email.mime.nonmultipart import MIMENonMultipart + +_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] + +class MIMEApplication(MIMENonMultipart): + def __init__(self, _data: bytes, _subtype: str = ..., + _encoder: Callable[[MIMEApplication], None] = ..., + **_params: _ParamsType) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/email/mime/audio.pyi b/client/typeshed-fallback/stdlib/3/email/mime/audio.pyi new file mode 100644 index 000000000..2d2c90c2a --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/mime/audio.pyi @@ -0,0 +1,11 @@ +# Stubs for email.mime.audio (Python 3.4) + +from typing import Callable, Optional, Tuple, Union +from email.mime.nonmultipart import MIMENonMultipart + +_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] + +class MIMEAudio(MIMENonMultipart): + def __init__(self, _audiodata: bytes, _subtype: Optional[str] = ..., + _encoder: Callable[[MIMEAudio], None] = ..., + **_params: _ParamsType) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/email/mime/base.pyi b/client/typeshed-fallback/stdlib/3/email/mime/base.pyi new file mode 100644 index 000000000..448d34be1 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/mime/base.pyi @@ -0,0 +1,10 @@ +# Stubs for email.mime.base (Python 3.4) + +from typing import Optional, Tuple, Union +import email.message + +_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] + +class MIMEBase(email.message.Message): + def __init__(self, _maintype: str, _subtype: str, + **_params: _ParamsType) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/email/mime/image.pyi b/client/typeshed-fallback/stdlib/3/email/mime/image.pyi new file mode 100644 index 000000000..9ec5deba0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/mime/image.pyi @@ -0,0 +1,11 @@ +# Stubs for email.mime.image (Python 3.4) + +from typing import Callable, Optional, Tuple, Union +from email.mime.nonmultipart import MIMENonMultipart + +_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] + +class MIMEImage(MIMENonMultipart): + def __init__(self, _imagedata: bytes, _subtype: Optional[str] = ..., + _encoder: Callable[[MIMEImage], None] = ..., + **_params: _ParamsType) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/email/mime/message.pyi b/client/typeshed-fallback/stdlib/3/email/mime/message.pyi new file mode 100644 index 000000000..561e8c35f --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/mime/message.pyi @@ -0,0 +1,7 @@ +# Stubs for email.mime.message (Python 3.4) + +from email.message import Message +from email.mime.nonmultipart import MIMENonMultipart + +class MIMEMessage(MIMENonMultipart): + def __init__(self, _msg: Message, _subtype: str = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/email/mime/multipart.pyi b/client/typeshed-fallback/stdlib/3/email/mime/multipart.pyi new file mode 100644 index 000000000..ea5eba15e --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/mime/multipart.pyi @@ -0,0 +1,12 @@ +# Stubs for email.mime.multipart (Python 3.4) + +from typing import Optional, Sequence, Tuple, Union +from email.message import Message +from email.mime.base import MIMEBase + +_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] + +class MIMEMultipart(MIMEBase): + def __init__(self, _subtype: str = ..., boundary: Optional[str] = ..., + _subparts: Optional[Sequence[Message]] = ..., + **_params: _ParamsType) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/email/mime/nonmultipart.pyi b/client/typeshed-fallback/stdlib/3/email/mime/nonmultipart.pyi new file mode 100644 index 000000000..1fd3ea98b --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/mime/nonmultipart.pyi @@ -0,0 +1,5 @@ +# Stubs for email.mime.nonmultipart (Python 3.4) + +from email.mime.base import MIMEBase + +class MIMENonMultipart(MIMEBase): ... diff --git a/client/typeshed-fallback/stdlib/3/email/mime/text.pyi b/client/typeshed-fallback/stdlib/3/email/mime/text.pyi new file mode 100644 index 000000000..73adaf5f6 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/mime/text.pyi @@ -0,0 +1,8 @@ +# Stubs for email.mime.text (Python 3.4) + +from typing import Optional +from email.mime.nonmultipart import MIMENonMultipart + +class MIMEText(MIMENonMultipart): + def __init__(self, _text: str, _subtype: str = ..., + _charset: Optional[str] = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/email/parser.pyi b/client/typeshed-fallback/stdlib/3/email/parser.pyi new file mode 100644 index 000000000..180e382ee --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/parser.pyi @@ -0,0 +1,33 @@ +# Stubs for email.parser (Python 3.4) + +import email.feedparser +from email.message import Message +from email.policy import Policy +from typing import BinaryIO, Callable, Optional, TextIO + +FeedParser = email.feedparser.FeedParser +BytesFeedParser = email.feedparser.BytesFeedParser + +class Parser: + def __init__(self, _class: Callable[[], Message] = ..., *, + policy: Policy = ...) -> None: ... + def parse(self, fp: TextIO, headersonly: bool = ...) -> Message: ... + def parsestr(self, text: str, headersonly: bool = ...) -> Message: ... + +class HeaderParser(Parser): + def __init__(self, _class: Callable[[], Message] = ..., *, + policy: Policy = ...) -> None: ... + def parse(self, fp: TextIO, headersonly: bool = ...) -> Message: ... + def parsestr(self, text: str, headersonly: bool = ...) -> Message: ... + +class BytesHeaderParser(BytesParser): + def __init__(self, _class: Callable[[], Message] = ..., *, + policy: Policy = ...) -> None: ... + def parse(self, fp: BinaryIO, headersonly: bool = ...) -> Message: ... + def parsebytes(self, text: bytes, headersonly: bool = ...) -> Message: ... + +class BytesParser: + def __init__(self, _class: Callable[[], Message] = ..., *, + policy: Policy = ...) -> None: ... + def parse(self, fp: BinaryIO, headersonly: bool = ...) -> Message: ... + def parsebytes(self, text: bytes, headersonly: bool = ...) -> Message: ... diff --git a/client/typeshed-fallback/stdlib/3/email/policy.pyi b/client/typeshed-fallback/stdlib/3/email/policy.pyi new file mode 100644 index 000000000..43904015e --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/policy.pyi @@ -0,0 +1,64 @@ +# Stubs for email.policy (Python 3.4) + +from abc import abstractmethod +from typing import Any, List, Optional, Tuple, Union, Callable +import sys +from email.message import Message +from email.errors import MessageDefect +from email.header import Header +from email.contentmanager import ContentManager + +class Policy: + max_line_length = ... # type: Optional[int] + linesep = ... # type: str + cte_type = ... # type: str + raise_on_defect = ... # type: bool + if sys.version_info >= (3, 5): + mange_from = ... # type: bool + def __init__(self, **kw: Any) -> None: ... + def clone(self, **kw: Any) -> Policy: ... + def handle_defect(self, obj: Message, + defect: MessageDefect) -> None: ... + def register_defect(self, obj: Message, + defect: MessageDefect) -> None: ... + def header_max_count(self, name: str) -> Optional[int]: ... + @abstractmethod + def header_source_parse(self, sourcelines: List[str]) -> str: ... + @abstractmethod + def header_store_parse(self, name: str, + value: str) -> Tuple[str, str]: ... + @abstractmethod + def header_fetch_parse(self, name: str, + value: str) -> str: ... + @abstractmethod + def fold(self, name: str, value: str) -> str: ... + @abstractmethod + def fold_binary(self, name: str, value: str) -> bytes: ... + +class Compat32(Policy): + def header_source_parse(self, sourcelines: List[str]) -> str: ... + def header_store_parse(self, name: str, + value: str) -> Tuple[str, str]: ... + def header_fetch_parse(self, name: str, value: str) -> Union[str, Header]: ... # type: ignore + def fold(self, name: str, value: str) -> str: ... + def fold_binary(self, name: str, value: str) -> bytes: ... + +compat32 = ... # type: Compat32 + +class EmailPolicy(Policy): + utf8 = ... # type: bool + refold_source = ... # type: str + header_factory = ... # type: Callable[[str, str], str] + content_manager = ... # type: ContentManager + def header_source_parse(self, sourcelines: List[str]) -> str: ... + def header_store_parse(self, name: str, + value: str) -> Tuple[str, str]: ... + def header_fetch_parse(self, name: str, value: str) -> str: ... + def fold(self, name: str, value: str) -> str: ... + def fold_binary(self, name: str, value: str) -> bytes: ... + +default = ... # type: EmailPolicy +SMTP = ... # type: EmailPolicy +SMTPUTF8 = ... # type: EmailPolicy +HTTP = ... # type: EmailPolicy +strict = ... # type: EmailPolicy diff --git a/client/typeshed-fallback/stdlib/3/email/utils.pyi b/client/typeshed-fallback/stdlib/3/email/utils.pyi new file mode 100644 index 000000000..6c0a18319 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/email/utils.pyi @@ -0,0 +1,33 @@ +# Stubs for email.utils (Python 3.4) + +from typing import List, Optional, Tuple, Union +from email.charset import Charset +import datetime + +_ParamType = Union[str, Tuple[Optional[str], Optional[str], str]] +_PDTZ = Tuple[int, int, int, int, int, int, int, int, int, Optional[int]] + +def quote(str: str) -> str: ... +def unquote(str: str) -> str: ... +def parseaddr(address: Optional[str]) -> Tuple[str, str]: ... +def formataddr(pair: Tuple[Optional[str], str], + charset: Union[str, Charset] = ...) -> str: ... +def getaddresses(fieldvalues: List[str]) -> List[Tuple[str, str]]: ... +def parsedate(date: str) -> Optional[Tuple[int, int, int, int, int, int, int, int, int]]: ... +def parsedate_tz(date: str) -> Optional[_PDTZ]: ... +def parsedate_to_datetime(date: str) -> datetime.datetime: ... +def mktime_tz(tuple: _PDTZ) -> int: ... +def formatdate(timeval: Optional[float] = ..., localtime: bool = ..., + usegmt: bool = ...) -> str: ... +def format_datetime(dt: datetime.datetime, usegmt: bool = ...) -> str: ... +def localtime(dt: Optional[datetime.datetime] = ...) -> datetime.datetime: ... +def make_msgid(idstring: Optional[str] = ..., + domain: Optional[str] = ...) -> str: ... +def decode_rfc2231(s: str) -> Tuple[Optional[str], Optional[str], str]: ... +def encode_rfc2231(s: str, charset: Optional[str] = ..., + language: Optional[str] = ...) -> str: ... +def collapse_rfc2231_value(value: _ParamType, errors: str = ..., + fallback_charset: str = ...) -> str: ... +def decode_params( + params: List[Tuple[str, str]] +) -> List[Tuple[str, _ParamType]]: ... diff --git a/client/typeshed-fallback/stdlib/3/encodings/__init__.pyi b/client/typeshed-fallback/stdlib/3/encodings/__init__.pyi new file mode 100644 index 000000000..2ae6c0a93 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/encodings/__init__.pyi @@ -0,0 +1,6 @@ +import codecs + +import typing + +def search_function(encoding: str) -> codecs.CodecInfo: + ... diff --git a/client/typeshed-fallback/stdlib/3/encodings/utf_8.pyi b/client/typeshed-fallback/stdlib/3/encodings/utf_8.pyi new file mode 100644 index 000000000..d38bd58d0 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/encodings/utf_8.pyi @@ -0,0 +1,15 @@ +import codecs +from typing import Text, Tuple + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: Text, final: bool = ...) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input: bytes, errors: str, final: bool) -> Tuple[Text, int]: ... + +class StreamWriter(codecs.StreamWriter): ... +class StreamReader(codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... +def encode(input: Text, errors: Text = ...) -> bytes: ... +def decode(input: bytes, errors: Text = ...) -> Text: ... diff --git a/client/typeshed-fallback/stdlib/3/enum.pyi b/client/typeshed-fallback/stdlib/3/enum.pyi new file mode 100644 index 000000000..404da0292 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/enum.pyi @@ -0,0 +1,74 @@ +# NB: third_party/2/enum.pyi and stdlib/3.4/enum.pyi must remain consistent! +import sys +from typing import Any, Iterator, List, Mapping, Type, TypeVar, Union +from abc import ABCMeta + +_T = TypeVar('_T') +_S = TypeVar('_S', bound=Type[Enum]) + +# Note: EnumMeta actually subclasses type directly, not ABCMeta. +# This is a temporary workaround to allow multiple creation of enums with builtins +# such as str as mixins, which due to the handling of ABCs of builtin types, cause +# spurious inconsistent metaclass structure. See #1595. +# Structurally: Iterable[T], Reversible[T], Container[T] where T is the enum itself +class EnumMeta(ABCMeta): + def __iter__(self: Type[_T]) -> Iterator[_T]: ... + def __reversed__(self: Type[_T]) -> Iterator[_T]: ... + def __contains__(self: Type[_T], member: object) -> bool: ... + def __getitem__(self: Type[_T], name: str) -> _T: ... + @property + def __members__(self: Type[_T]) -> Mapping[str, _T]: ... + def __len__(self) -> int: ... + +class Enum(metaclass=EnumMeta): + name: str + value: Any + _name_: str + _value_: Any + if sys.version_info >= (3, 7): + _ignore_: Union[str, List[str]] + if sys.version_info >= (3, 6): + _order_: str + @classmethod + def _missing_(cls, value: object) -> Any: ... + @staticmethod + def _generate_next_value_(name: str, start: int, count: int, last_values: List[Any]) -> Any: ... + def __new__(cls: Type[_T], value: object) -> _T: ... + def __repr__(self) -> str: ... + def __str__(self) -> str: ... + def __dir__(self) -> List[str]: ... + def __format__(self, format_spec: str) -> str: ... + def __hash__(self) -> Any: ... + def __reduce_ex__(self, proto: object) -> Any: ... + +class IntEnum(int, Enum): + value: int + +def unique(enumeration: _S) -> _S: ... + +if sys.version_info >= (3, 6): + _auto_null: Any + + # subclassing IntFlag so it picks up all implemented base functions, best modeling behavior of enum.auto() + class auto(IntFlag): + value: Any + + class Flag(Enum): + def __contains__(self: _T, other: _T) -> bool: ... + def __repr__(self) -> str: ... + def __str__(self) -> str: ... + def __bool__(self) -> bool: ... + def __or__(self: _T, other: _T) -> _T: ... + def __and__(self: _T, other: _T) -> _T: ... + def __xor__(self: _T, other: _T) -> _T: ... + def __invert__(self: _T) -> _T: ... + + # The `type: ignore` comment is needed because mypy considers the type + # signatures of several methods defined in int and Flag to be incompatible. + class IntFlag(int, Flag): # type: ignore + def __or__(self: _T, other: Union[int, _T]) -> _T: ... + def __and__(self: _T, other: Union[int, _T]) -> _T: ... + def __xor__(self: _T, other: Union[int, _T]) -> _T: ... + __ror__ = __or__ + __rand__ = __and__ + __rxor__ = __xor__ diff --git a/client/typeshed-fallback/stdlib/3/faulthandler.pyi b/client/typeshed-fallback/stdlib/3/faulthandler.pyi new file mode 100644 index 000000000..1a87c9cf9 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/faulthandler.pyi @@ -0,0 +1,23 @@ +import sys +from typing import Union, Protocol + + +class _HasFileno(Protocol): + def fileno(self) -> int: ... + + +if sys.version_info >= (3, 5): + _File = Union[_HasFileno, int] +else: + _File = _HasFileno + + +def cancel_dump_traceback_later() -> None: ... +def disable() -> None: ... +def dump_traceback(file: _File = ..., all_threads: bool = ...) -> None: ... +def dump_traceback_later(timeout: int, repeat: bool = ..., file: _File = ..., exit: bool = ...) -> None: ... +def enable(file: _File = ..., all_threads: bool = ...) -> None: ... +def is_enabled() -> bool: ... +if sys.platform != "win32": + def register(signum: int, file: _File = ..., all_threads: bool = ..., chain: bool = ...) -> None: ... + def unregister(signum: int) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/fcntl.pyi b/client/typeshed-fallback/stdlib/3/fcntl.pyi new file mode 100644 index 000000000..1ff20d60d --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/fcntl.pyi @@ -0,0 +1,96 @@ +# Stubs for fcntl +from io import IOBase +from typing import Any, IO, Union + +FASYNC = ... # type: int +FD_CLOEXEC = ... # type: int +DN_ACCESS = ... # type: int +DN_ATTRIB = ... # type: int +DN_CREATE = ... # type: int +DN_DELETE = ... # type: int +DN_MODIFY = ... # type: int +DN_MULTISHOT = ... # type: int +DN_RENAME = ... # type: int +F_DUPFD = ... # type: int +F_DUPFD_CLOEXEC = ... # type: int +F_FULLFSYNC = ... # type: int +F_EXLCK = ... # type: int +F_GETFD = ... # type: int +F_GETFL = ... # type: int +F_GETLEASE = ... # type: int +F_GETLK = ... # type: int +F_GETLK64 = ... # type: int +F_GETOWN = ... # type: int +F_NOCACHE = ... # type: int +F_GETSIG = ... # type: int +F_NOTIFY = ... # type: int +F_RDLCK = ... # type: int +F_SETFD = ... # type: int +F_SETFL = ... # type: int +F_SETLEASE = ... # type: int +F_SETLK = ... # type: int +F_SETLK64 = ... # type: int +F_SETLKW = ... # type: int +F_SETLKW64 = ... # type: int +F_SETOWN = ... # type: int +F_SETSIG = ... # type: int +F_SHLCK = ... # type: int +F_UNLCK = ... # type: int +F_WRLCK = ... # type: int +I_ATMARK = ... # type: int +I_CANPUT = ... # type: int +I_CKBAND = ... # type: int +I_FDINSERT = ... # type: int +I_FIND = ... # type: int +I_FLUSH = ... # type: int +I_FLUSHBAND = ... # type: int +I_GETBAND = ... # type: int +I_GETCLTIME = ... # type: int +I_GETSIG = ... # type: int +I_GRDOPT = ... # type: int +I_GWROPT = ... # type: int +I_LINK = ... # type: int +I_LIST = ... # type: int +I_LOOK = ... # type: int +I_NREAD = ... # type: int +I_PEEK = ... # type: int +I_PLINK = ... # type: int +I_POP = ... # type: int +I_PUNLINK = ... # type: int +I_PUSH = ... # type: int +I_RECVFD = ... # type: int +I_SENDFD = ... # type: int +I_SETCLTIME = ... # type: int +I_SETSIG = ... # type: int +I_SRDOPT = ... # type: int +I_STR = ... # type: int +I_SWROPT = ... # type: int +I_UNLINK = ... # type: int +LOCK_EX = ... # type: int +LOCK_MAND = ... # type: int +LOCK_NB = ... # type: int +LOCK_READ = ... # type: int +LOCK_RW = ... # type: int +LOCK_SH = ... # type: int +LOCK_UN = ... # type: int +LOCK_WRITE = ... # type: int + +_AnyFile = Union[int, IO[Any], IOBase] + +# TODO All these return either int or bytes depending on the value of +# cmd (not on the type of arg). +def fcntl(fd: _AnyFile, + cmd: int, + arg: Union[int, bytes] = ...) -> Any: ... +# TODO This function accepts any object supporting a buffer interface, +# as arg, is there a better way to express this than bytes? +def ioctl(fd: _AnyFile, + request: int, + arg: Union[int, bytes] = ..., + mutate_flag: bool = ...) -> Any: ... +def flock(fd: _AnyFile, operation: int) -> None: ... +def lockf(fd: _AnyFile, + cmd: int, + len: int = ..., + start: int = ..., + whence: int = ...) -> Any: ... diff --git a/client/typeshed-fallback/stdlib/3/fnmatch.pyi b/client/typeshed-fallback/stdlib/3/fnmatch.pyi new file mode 100644 index 000000000..4f99b4aaf --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/fnmatch.pyi @@ -0,0 +1,11 @@ +# Stubs for fnmatch + +# Based on http://docs.python.org/3.2/library/fnmatch.html and +# python-lib/fnmatch.py + +from typing import Iterable, List, AnyStr + +def fnmatch(name: AnyStr, pat: AnyStr) -> bool: ... +def fnmatchcase(name: AnyStr, pat: AnyStr) -> bool: ... +def filter(names: Iterable[AnyStr], pat: AnyStr) -> List[AnyStr]: ... +def translate(pat: str) -> str: ... diff --git a/client/typeshed-fallback/stdlib/3/functools.pyi b/client/typeshed-fallback/stdlib/3/functools.pyi new file mode 100644 index 000000000..d3a898427 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/functools.pyi @@ -0,0 +1,76 @@ +import sys +from typing import Any, Callable, Generic, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Type, TypeVar, NamedTuple, Union, overload + +_AnyCallable = Callable[..., Any] + +_T = TypeVar("_T") +_S = TypeVar("_S") +@overload +def reduce(function: Callable[[_T, _S], _T], + sequence: Iterable[_S], initial: _T) -> _T: ... +@overload +def reduce(function: Callable[[_T, _T], _T], + sequence: Iterable[_T]) -> _T: ... + + +class _CacheInfo(NamedTuple('CacheInfo', [ + ('hits', int), + ('misses', int), + ('maxsize', int), + ('currsize', int) +])): ... + +class _lru_cache_wrapper(Generic[_T]): + __wrapped__ = ... # type: Callable[..., _T] + def __call__(self, *args: Any, **kwargs: Any) -> _T: ... + def cache_info(self) -> _CacheInfo: ... + def cache_clear(self) -> None: ... + +class lru_cache(): + def __init__(self, maxsize: Optional[int] = ..., typed: bool = ...) -> None: ... + def __call__(self, f: Callable[..., _T]) -> _lru_cache_wrapper[_T]: ... + + +WRAPPER_ASSIGNMENTS = ... # type: Sequence[str] +WRAPPER_UPDATES = ... # type: Sequence[str] + +def update_wrapper(wrapper: _AnyCallable, wrapped: _AnyCallable, assigned: Sequence[str] = ..., + updated: Sequence[str] = ...) -> _AnyCallable: ... +def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_AnyCallable], _AnyCallable]: ... +def total_ordering(cls: type) -> type: ... +def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], Any]: ... + +class partial(Generic[_T]): + func = ... # type: Callable[..., _T] + args = ... # type: Tuple[Any, ...] + keywords = ... # type: Dict[str, Any] + def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> _T: ... + +# With protocols, this could change into a generic protocol that defines __get__ and returns _T +_Descriptor = Any + +class partialmethod(Generic[_T]): + func: Union[Callable[..., _T], _Descriptor] + args: Tuple[Any, ...] + keywords: Dict[str, Any] + + @overload + def __init__(self, func: Callable[..., _T], *args: Any, **keywords: Any) -> None: ... + @overload + def __init__(self, func: _Descriptor, *args: Any, **keywords: Any) -> None: ... + def __get__(self, obj: Any, cls: Type[Any]) -> Callable[..., _T]: ... + @property + def __isabstractmethod__(self) -> bool: ... + +class _SingleDispatchCallable(Generic[_T]): + registry = ... # type: Mapping[Any, Callable[..., _T]] + def dispatch(self, cls: Any) -> Callable[..., _T]: ... + @overload + def register(self, cls: Any) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + @overload + def register(self, cls: Any, func: Callable[..., _T]) -> Callable[..., _T]: ... + def _clear_cache(self) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> _T: ... + +def singledispatch(func: Callable[..., _T]) -> _SingleDispatchCallable[_T]: ... diff --git a/client/typeshed-fallback/stdlib/3/gc.pyi b/client/typeshed-fallback/stdlib/3/gc.pyi new file mode 100644 index 000000000..ec94f29c5 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/gc.pyi @@ -0,0 +1,28 @@ +# Stubs for gc + +from typing import Any, Dict, List, Tuple + + +DEBUG_COLLECTABLE = ... # type: int +DEBUG_LEAK = ... # type: int +DEBUG_SAVEALL = ... # type: int +DEBUG_STATS = ... # type: int +DEBUG_UNCOLLECTABLE = ... # type: int +callbacks = ... # type: List[Any] +garbage = ... # type: List[Any] + +def collect(generations: int = ...) -> int: ... +def disable() -> None: ... +def enable() -> None: ... +def get_count() -> Tuple[int, int, int]: ... +def get_debug() -> int: ... +def get_objects() -> List[Any]: ... +def get_referents(*objs: Any) -> List[Any]: ... +def get_referrers(*objs: Any) -> List[Any]: ... +def get_stats() -> List[Dict[str, Any]]: ... +def get_threshold() -> Tuple[int, int, int]: ... +def is_tracked(obj: Any) -> bool: ... +def isenabled() -> bool: ... +def set_debug(flags: int) -> None: ... +def set_threshold(threshold0: int, threshold1: int = ..., + threshold2: int = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/getopt.pyi b/client/typeshed-fallback/stdlib/3/getopt.pyi new file mode 100644 index 000000000..f94f69820 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/getopt.pyi @@ -0,0 +1,14 @@ +# Stubs for getopt + +# Based on http://docs.python.org/3.2/library/getopt.html + +from typing import List, Tuple + +def getopt(args: List[str], shortopts: str, longopts: List[str] = ...) -> Tuple[List[Tuple[str, str]], List[str]]: ... +def gnu_getopt(args: List[str], shortopts: str, longopts: List[str] = ...) -> Tuple[List[Tuple[str, str]], List[str]]: ... + +class GetoptError(Exception): + msg = ... # type: str + opt = ... # type: str + +error = GetoptError diff --git a/client/typeshed-fallback/stdlib/3/getpass.pyi b/client/typeshed-fallback/stdlib/3/getpass.pyi new file mode 100644 index 000000000..55a8433fc --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/getpass.pyi @@ -0,0 +1,12 @@ +# Stubs for getpass + +from typing import Optional, TextIO + + +def getpass(prompt: str = ..., stream: Optional[TextIO] = ...) -> str: ... + + +def getuser() -> str: ... + + +class GetPassWarning(UserWarning): ... diff --git a/client/typeshed-fallback/stdlib/3/gettext.pyi b/client/typeshed-fallback/stdlib/3/gettext.pyi new file mode 100644 index 000000000..267a10632 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/gettext.pyi @@ -0,0 +1,44 @@ +# Stubs for gettext (Python 3.4) + +from typing import Any, IO, List, Optional, Union, Callable + +class NullTranslations: + def __init__(self, fp: IO[str] = ...) -> None: ... + def add_fallback(self, fallback: NullTranslations) -> None: ... + def gettext(self, message: str) -> str: ... + def lgettext(self, message: str) -> str: ... + def ngettext(self, singular: str, plural: str, n: int) -> str: ... + def lngettext(self, singular: str, plural: str, n: int) -> str: ... + def info(self) -> Any: ... + def charset(self) -> Any: ... + def output_charset(self) -> Any: ... + def set_output_charset(self, charset: Any) -> None: ... + def install(self, names: List[str] = ...) -> None: ... + +class GNUTranslations(NullTranslations): + LE_MAGIC = ... # type: int + BE_MAGIC = ... # type: int + +def find(domain: str, localedir: str = ..., languages: List[str] = ..., + all: bool = ...): ... + +def translation(domain: str, localedir: str = ..., languages: List[str] = ..., + class_: Callable[[IO[str]], NullTranslations] = ..., + fallback: bool = ..., codeset: Any = ...) -> NullTranslations: ... + +def install(domain: str, localedir: str = ..., codeset: Any = ..., + names: List[str] = ...): ... + +def textdomain(domain: str = ...) -> str: ... +def bindtextdomain(domain: str, localedir: str = ...) -> str: ... +def bind_textdomain_codeset(domain: str, codeset: str = ...) -> str: ... +def dgettext(domain: str, message: str) -> str: ... +def ldgettext(domain: str, message: str) -> str: ... +def dngettext(domain: str, singular: str, plural: str, n: int) -> str: ... +def ldngettext(domain: str, singular: str, plural: str, n: int) -> str: ... +def gettext(message: str) -> str: ... +def lgettext(message: str) -> str: ... +def ngettext(singular: str, plural: str, n: int) -> str: ... +def lngettext(singular: str, plural: str, n: int) -> str: ... + +Catalog = translation diff --git a/client/typeshed-fallback/stdlib/3/glob.pyi b/client/typeshed-fallback/stdlib/3/glob.pyi new file mode 100644 index 000000000..701c4cacc --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/glob.pyi @@ -0,0 +1,21 @@ +# Stubs for glob +# Based on http://docs.python.org/3/library/glob.html + +from typing import List, Iterator, AnyStr +import sys + +if sys.version_info >= (3, 6): + def glob0(dirname: AnyStr, pattern: AnyStr) -> List[AnyStr]: ... +else: + def glob0(dirname: AnyStr, basename: AnyStr) -> List[AnyStr]: ... + +def glob1(dirname: AnyStr, pattern: AnyStr) -> List[AnyStr]: ... + +if sys.version_info >= (3, 5): + def glob(pathname: AnyStr, *, recursive: bool = ...) -> List[AnyStr]: ... + def iglob(pathname: AnyStr, *, recursive: bool = ...) -> Iterator[AnyStr]: ... +else: + def glob(pathname: AnyStr) -> List[AnyStr]: ... + def iglob(pathname: AnyStr) -> Iterator[AnyStr]: ... + +def escape(pathname: AnyStr) -> AnyStr: ... diff --git a/client/typeshed-fallback/stdlib/3/gzip.pyi b/client/typeshed-fallback/stdlib/3/gzip.pyi new file mode 100644 index 000000000..6f1bf7adc --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/gzip.pyi @@ -0,0 +1,49 @@ +from typing import Any, IO, Optional +from os.path import _PathType +import _compression +import zlib + +def open(filename, mode: str = ..., compresslevel: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., newline: Optional[str] = ...) -> IO[Any]: ... + +class _PaddedFile: + file: IO[bytes] + def __init__(self, f: IO[bytes], prepend: bytes = ...) -> None: ... + def read(self, size: int) -> bytes: ... + def prepend(self, prepend: bytes = ...) -> None: ... + def seek(self, off: int) -> int: ... + def seekable(self) -> bool: ... + +class GzipFile(_compression.BaseStream): + myfileobj: Optional[IO[bytes]] + mode: str + name: str + compress: zlib._Compress + fileobj: IO[bytes] + def __init__(self, filename: Optional[_PathType] = ..., mode: Optional[str] = ..., compresslevel: int = ..., fileobj: Optional[IO[bytes]] = ..., mtime: Optional[float] = ...) -> None: ... + @property + def filename(self) -> str: ... + @property + def mtime(self) -> Optional[int]: ... + crc: int + def write(self, data: bytes) -> int: ... + def read(self, size: Optional[int] = ...) -> bytes: ... + def read1(self, size: int = ...) -> bytes: ... + def peek(self, n: int) -> bytes: ... + @property + def closed(self) -> bool: ... + def close(self) -> None: ... + def flush(self, zlib_mode: int = ...) -> None: ... + def fileno(self) -> int: ... + def rewind(self) -> None: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def readline(self, size: int = ...) -> bytes: ... + +class _GzipReader(_compression.DecompressReader): + def __init__(self, fp: IO[bytes]) -> None: ... + def read(self, size: int = ...) -> bytes: ... + +def compress(data, compresslevel: int = ...) -> bytes: ... +def decompress(data: bytes) -> bytes: ... diff --git a/client/typeshed-fallback/stdlib/3/hashlib.pyi b/client/typeshed-fallback/stdlib/3/hashlib.pyi new file mode 100644 index 000000000..90bce96b2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/hashlib.pyi @@ -0,0 +1,69 @@ +# Stubs for hashlib + +import sys +from typing import AbstractSet, Optional, Union + +_DataType = Union[bytes, bytearray, memoryview] + +class _Hash(object): + digest_size = ... # type: int + block_size = ... # type: int + + # [Python documentation note] Changed in version 3.4: The name attribute has + # been present in CPython since its inception, but until Python 3.4 was not + # formally specified, so may not exist on some platforms + name = ... # type: str + + def __init__(self, data: _DataType = ...) -> None: ... + + def copy(self) -> _Hash: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def update(self, arg: _DataType) -> None: ... + +def md5(arg: _DataType = ...) -> _Hash: ... +def sha1(arg: _DataType = ...) -> _Hash: ... +def sha224(arg: _DataType = ...) -> _Hash: ... +def sha256(arg: _DataType = ...) -> _Hash: ... +def sha384(arg: _DataType = ...) -> _Hash: ... +def sha512(arg: _DataType = ...) -> _Hash: ... + +def new(name: str, data: _DataType = ...) -> _Hash: ... + +algorithms_guaranteed = ... # type: AbstractSet[str] +algorithms_available = ... # type: AbstractSet[str] + +def pbkdf2_hmac(hash_name: str, password: _DataType, salt: _DataType, iterations: int, dklen: Optional[int] = ...) -> bytes: ... + +if sys.version_info >= (3, 6): + class _VarLenHash(object): + digest_size = ... # type: int + block_size = ... # type: int + name = ... # type: str + + def __init__(self, data: _DataType = ...) -> None: ... + + def copy(self) -> _VarLenHash: ... + def digest(self, length: int) -> bytes: ... + def hexdigest(self, length: int) -> str: ... + def update(self, arg: _DataType) -> None: ... + + sha3_224 = _Hash + sha3_256 = _Hash + sha3_384 = _Hash + sha3_512 = _Hash + shake_128 = _VarLenHash + shake_256 = _VarLenHash + + def scrypt(password: _DataType, *, salt: _DataType, n: int, r: int, p: int, maxmem: int = ..., dklen: int = ...) -> bytes: ... + + class _BlakeHash(_Hash): + MAX_DIGEST_SIZE = ... # type: int + MAX_KEY_SIZE = ... # type: int + PERSON_SIZE = ... # type: int + SALT_SIZE = ... # type: int + + def __init__(self, data: _DataType = ..., digest_size: int = ..., key: _DataType = ..., salt: _DataType = ..., person: _DataType = ..., fanout: int = ..., depth: int = ..., leaf_size: int = ..., node_offset: int = ..., node_depth: int = ..., inner_size: int = ..., last_node: bool = ...) -> None: ... + + blake2b = _BlakeHash + blake2s = _BlakeHash diff --git a/client/typeshed-fallback/stdlib/3/heapq.pyi b/client/typeshed-fallback/stdlib/3/heapq.pyi new file mode 100644 index 000000000..5c49dfac1 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/heapq.pyi @@ -0,0 +1,23 @@ +# Stubs for heapq + +# Based on http://docs.python.org/3.2/library/heapq.html + +import sys +from typing import TypeVar, List, Iterable, Any, Callable, Optional + +_T = TypeVar('_T') + +def heappush(heap: List[_T], item: _T) -> None: ... +def heappop(heap: List[_T]) -> _T: ... +def heappushpop(heap: List[_T], item: _T) -> _T: ... +def heapify(x: List[_T]) -> None: ... +def heapreplace(heap: List[_T], item: _T) -> _T: ... +if sys.version_info >= (3, 5): + def merge(*iterables: Iterable[_T], key: Callable[[_T], Any] = ..., + reverse: bool = ...) -> Iterable[_T]: ... +else: + def merge(*iterables: Iterable[_T]) -> Iterable[_T]: ... +def nlargest(n: int, iterable: Iterable[_T], + key: Optional[Callable[[_T], Any]] = ...) -> List[_T]: ... +def nsmallest(n: int, iterable: Iterable[_T], + key: Callable[[_T], Any] = ...) -> List[_T]: ... diff --git a/client/typeshed-fallback/stdlib/3/html/__init__.pyi b/client/typeshed-fallback/stdlib/3/html/__init__.pyi new file mode 100644 index 000000000..af2a80021 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/html/__init__.pyi @@ -0,0 +1,4 @@ +from typing import AnyStr + +def escape(s: AnyStr, quote: bool = ...) -> AnyStr: ... +def unescape(s: AnyStr) -> AnyStr: ... diff --git a/client/typeshed-fallback/stdlib/3/html/entities.pyi b/client/typeshed-fallback/stdlib/3/html/entities.pyi new file mode 100644 index 000000000..470217b0f --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/html/entities.pyi @@ -0,0 +1,6 @@ +from typing import Any + +name2codepoint = ... # type: Any +html5 = ... # type: Any +codepoint2name = ... # type: Any +entitydefs = ... # type: Any diff --git a/client/typeshed-fallback/stdlib/3/html/parser.pyi b/client/typeshed-fallback/stdlib/3/html/parser.pyi new file mode 100644 index 000000000..102a2cc0e --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/html/parser.pyi @@ -0,0 +1,31 @@ +from typing import List, Tuple +from _markupbase import ParserBase +import sys + +class HTMLParser(ParserBase): + if sys.version_info >= (3, 5): + def __init__(self, *, convert_charrefs: bool = ...) -> None: ... + else: + def __init__(self, strict: bool = ..., *, + convert_charrefs: bool = ...) -> None: ... + def feed(self, feed: str) -> None: ... + def close(self) -> None: ... + def reset(self) -> None: ... + def getpos(self) -> Tuple[int, int]: ... + def get_starttag_text(self) -> str: ... + + def handle_starttag(self, tag: str, + attrs: List[Tuple[str, str]]) -> None: ... + def handle_endtag(self, tag: str) -> None: ... + def handle_startendtag(self, tag: str, + attrs: List[Tuple[str, str]]) -> None: ... + def handle_data(self, data: str) -> None: ... + def handle_entityref(self, name: str) -> None: ... + def handle_charref(self, name: str) -> None: ... + def handle_comment(self, data: str) -> None: ... + def handle_decl(self, decl: str) -> None: ... + def handle_pi(self, data: str) -> None: ... + def unknown_decl(self, data: str) -> None: ... + +if sys.version_info < (3, 5): + class HTMLParseError(Exception): ... diff --git a/client/typeshed-fallback/stdlib/3/http/__init__.pyi b/client/typeshed-fallback/stdlib/3/http/__init__.pyi new file mode 100644 index 000000000..bc9dcb687 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/http/__init__.pyi @@ -0,0 +1,69 @@ +import sys + +from enum import IntEnum + +if sys.version_info >= (3, 5): + class HTTPStatus(IntEnum): + + def __init__(self, *a) -> None: ... + + phrase = ... # type: str + description = ... # type: str + + CONTINUE = ... + SWITCHING_PROTOCOLS = ... + PROCESSING = ... + OK = ... + CREATED = ... + ACCEPTED = ... + NON_AUTHORITATIVE_INFORMATION = ... + NO_CONTENT = ... + RESET_CONTENT = ... + PARTIAL_CONTENT = ... + MULTI_STATUS = ... + ALREADY_REPORTED = ... + IM_USED = ... + MULTIPLE_CHOICES = ... + MOVED_PERMANENTLY = ... + FOUND = ... + SEE_OTHER = ... + NOT_MODIFIED = ... + USE_PROXY = ... + TEMPORARY_REDIRECT = ... + PERMANENT_REDIRECT = ... + BAD_REQUEST = ... + UNAUTHORIZED = ... + PAYMENT_REQUIRED = ... + FORBIDDEN = ... + NOT_FOUND = ... + METHOD_NOT_ALLOWED = ... + NOT_ACCEPTABLE = ... + PROXY_AUTHENTICATION_REQUIRED = ... + REQUEST_TIMEOUT = ... + CONFLICT = ... + GONE = ... + LENGTH_REQUIRED = ... + PRECONDITION_FAILED = ... + REQUEST_ENTITY_TOO_LARGE = ... + REQUEST_URI_TOO_LONG = ... + UNSUPPORTED_MEDIA_TYPE = ... + REQUESTED_RANGE_NOT_SATISFIABLE = ... + EXPECTATION_FAILED = ... + UNPROCESSABLE_ENTITY = ... + LOCKED = ... + FAILED_DEPENDENCY = ... + UPGRADE_REQUIRED = ... + PRECONDITION_REQUIRED = ... + TOO_MANY_REQUESTS = ... + REQUEST_HEADER_FIELDS_TOO_LARGE = ... + INTERNAL_SERVER_ERROR = ... + NOT_IMPLEMENTED = ... + BAD_GATEWAY = ... + SERVICE_UNAVAILABLE = ... + GATEWAY_TIMEOUT = ... + HTTP_VERSION_NOT_SUPPORTED = ... + VARIANT_ALSO_NEGOTIATES = ... + INSUFFICIENT_STORAGE = ... + LOOP_DETECTED = ... + NOT_EXTENDED = ... + NETWORK_AUTHENTICATION_REQUIRED = ... diff --git a/client/typeshed-fallback/stdlib/3/http/client.pyi b/client/typeshed-fallback/stdlib/3/http/client.pyi new file mode 100644 index 000000000..bd11f567e --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/http/client.pyi @@ -0,0 +1,223 @@ +from typing import ( + Any, Dict, IO, Iterable, List, Iterator, Mapping, Optional, + Protocol, Tuple, Type, TypeVar, + Union, + overload, + BinaryIO, +) +import email.message +import io +from socket import socket +import sys +import ssl +import types + +_DataType = Union[bytes, IO[Any], Iterable[bytes], str] +_T = TypeVar('_T') + +HTTP_PORT = ... # type: int +HTTPS_PORT = ... # type: int + +CONTINUE = ... # type: int +SWITCHING_PROTOCOLS = ... # type: int +PROCESSING = ... # type: int + +OK = ... # type: int +CREATED = ... # type: int +ACCEPTED = ... # type: int +NON_AUTHORITATIVE_INFORMATION = ... # type: int +NO_CONTENT = ... # type: int +RESET_CONTENT = ... # type: int +PARTIAL_CONTENT = ... # type: int +MULTI_STATUS = ... # type: int +IM_USED = ... # type: int + +MULTIPLE_CHOICES = ... # type: int +MOVED_PERMANENTLY = ... # type: int +FOUND = ... # type: int +SEE_OTHER = ... # type: int +NOT_MODIFIED = ... # type: int +USE_PROXY = ... # type: int +TEMPORARY_REDIRECT = ... # type: int + +BAD_REQUEST = ... # type: int +UNAUTHORIZED = ... # type: int +PAYMENT_REQUIRED = ... # type: int +FORBIDDEN = ... # type: int +NOT_FOUND = ... # type: int +METHOD_NOT_ALLOWED = ... # type: int +NOT_ACCEPTABLE = ... # type: int +PROXY_AUTHENTICATION_REQUIRED = ... # type: int +REQUEST_TIMEOUT = ... # type: int +CONFLICT = ... # type: int +GONE = ... # type: int +LENGTH_REQUIRED = ... # type: int +PRECONDITION_FAILED = ... # type: int +REQUEST_ENTITY_TOO_LARGE = ... # type: int +REQUEST_URI_TOO_LONG = ... # type: int +UNSUPPORTED_MEDIA_TYPE = ... # type: int +REQUESTED_RANGE_NOT_SATISFIABLE = ... # type: int +EXPECTATION_FAILED = ... # type: int +UNPROCESSABLE_ENTITY = ... # type: int +LOCKED = ... # type: int +FAILED_DEPENDENCY = ... # type: int +UPGRADE_REQUIRED = ... # type: int +PRECONDITION_REQUIRED = ... # type: int +TOO_MANY_REQUESTS = ... # type: int +REQUEST_HEADER_FIELDS_TOO_LARGE = ... # type: int + +INTERNAL_SERVER_ERROR = ... # type: int +NOT_IMPLEMENTED = ... # type: int +BAD_GATEWAY = ... # type: int +SERVICE_UNAVAILABLE = ... # type: int +GATEWAY_TIMEOUT = ... # type: int +HTTP_VERSION_NOT_SUPPORTED = ... # type: int +INSUFFICIENT_STORAGE = ... # type: int +NOT_EXTENDED = ... # type: int +NETWORK_AUTHENTICATION_REQUIRED = ... # type: int + +responses = ... # type: Dict[int, str] + +class HTTPMessage(email.message.Message): ... + +if sys.version_info >= (3, 5): + # Ignore errors to work around python/mypy#5027 + class HTTPResponse(io.BufferedIOBase, BinaryIO): # type: ignore + msg = ... # type: HTTPMessage + headers = ... # type: HTTPMessage + version = ... # type: int + debuglevel = ... # type: int + closed = ... # type: bool + status = ... # type: int + reason = ... # type: str + def __init__(self, sock: socket, debuglevel: int = ..., + method: Optional[str] = ..., url: Optional[str] = ...) -> None: ... + def read(self, amt: Optional[int] = ...) -> bytes: ... + @overload + def getheader(self, name: str) -> Optional[str]: ... + @overload + def getheader(self, name: str, default: _T) -> Union[str, _T]: ... + def getheaders(self) -> List[Tuple[str, str]]: ... + def fileno(self) -> int: ... + def isclosed(self) -> bool: ... + def __iter__(self) -> Iterator[bytes]: ... + def __enter__(self) -> HTTPResponse: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[types.TracebackType]) -> bool: ... + def info(self) -> email.message.Message: ... + def geturl(self) -> str: ... + def getcode(self) -> int: ... + def begin(self) -> None: ... +else: + class HTTPResponse(io.RawIOBase, BinaryIO): # type: ignore + msg = ... # type: HTTPMessage + headers = ... # type: HTTPMessage + version = ... # type: int + debuglevel = ... # type: int + closed = ... # type: bool + status = ... # type: int + reason = ... # type: str + def read(self, amt: Optional[int] = ...) -> bytes: ... + def readinto(self, b: bytearray) -> int: ... + @overload + def getheader(self, name: str) -> Optional[str]: ... + @overload + def getheader(self, name: str, default: _T) -> Union[str, _T]: ... + def getheaders(self) -> List[Tuple[str, str]]: ... + def fileno(self) -> int: ... + def __iter__(self) -> Iterator[bytes]: ... + def __enter__(self) -> HTTPResponse: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[types.TracebackType]) -> bool: ... + def info(self) -> email.message.Message: ... + def geturl(self) -> str: ... + def getcode(self) -> int: ... + def begin(self) -> None: ... + +# This is an API stub only for the class below, not a class itself. +# urllib.request uses it for a parameter. +class HTTPConnectionProtocol(Protocol): + if sys.version_info >= (3, 7): + def __call__(self, host: str, port: Optional[int] = ..., + timeout: int = ..., + source_address: Optional[Tuple[str, int]] = ..., + blocksize: int = ...): ... + else: + def __call__(self, host: str, port: Optional[int] = ..., + timeout: int = ..., + source_address: Optional[Tuple[str, int]] = ...): ... + +class HTTPConnection: + host: str = ... + port: int = ... + if sys.version_info >= (3, 7): + def __init__( + self, + host: str, port: Optional[int] = ..., + timeout: int = ..., + source_address: Optional[Tuple[str, int]] = ..., blocksize: int = ... + ) -> None: ... + else: + def __init__( + self, + host: str, port: Optional[int] = ..., + timeout: int = ..., + source_address: Optional[Tuple[str, int]] = ... + ) -> None: ... + if sys.version_info >= (3, 6): + def request(self, method: str, url: str, + body: Optional[_DataType] = ..., + headers: Mapping[str, str] = ..., + *, encode_chunked: bool = ...) -> None: ... + else: + def request(self, method: str, url: str, + body: Optional[_DataType] = ..., + headers: Mapping[str, str] = ...) -> None: ... + def getresponse(self) -> HTTPResponse: ... + def set_debuglevel(self, level: int) -> None: ... + def set_tunnel(self, host: str, port: Optional[int] = ..., + headers: Optional[Mapping[str, str]] = ...) -> None: ... + def connect(self) -> None: ... + def close(self) -> None: ... + def putrequest(self, request: str, selector: str, skip_host: bool = ..., + skip_accept_encoding: bool = ...) -> None: ... + def putheader(self, header: str, *argument: str) -> None: ... + if sys.version_info >= (3, 6): + def endheaders(self, message_body: Optional[_DataType] = ..., + *, encode_chunked: bool = ...) -> None: ... + else: + def endheaders(self, message_body: Optional[_DataType] = ...) -> None: ... + def send(self, data: _DataType) -> None: ... + +class HTTPSConnection(HTTPConnection): + def __init__(self, + host: str, port: Optional[int] = ..., + key_file: Optional[str] = ..., + cert_file: Optional[str] = ..., + timeout: int = ..., + source_address: Optional[Tuple[str, int]] = ..., + *, context: Optional[ssl.SSLContext] = ..., + check_hostname: Optional[bool] = ...) -> None: ... + +class HTTPException(Exception): ... +error = HTTPException + +class NotConnected(HTTPException): ... +class InvalidURL(HTTPException): ... +class UnknownProtocol(HTTPException): ... +class UnknownTransferEncoding(HTTPException): ... +class UnimplementedFileMode(HTTPException): ... +class IncompleteRead(HTTPException): ... + +class ImproperConnectionState(HTTPException): ... +class CannotSendRequest(ImproperConnectionState): ... +class CannotSendHeader(ImproperConnectionState): ... +class ResponseNotReady(ImproperConnectionState): ... + +class BadStatusLine(HTTPException): ... +class LineTooLong(HTTPException): ... + +if sys.version_info >= (3, 5): + class RemoteDisconnected(ConnectionResetError, BadStatusLine): ... diff --git a/client/typeshed-fallback/stdlib/3/http/cookiejar.pyi b/client/typeshed-fallback/stdlib/3/http/cookiejar.pyi new file mode 100644 index 000000000..02d26f3b7 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/http/cookiejar.pyi @@ -0,0 +1,106 @@ +from typing import Iterable, Iterator, Optional, Sequence, Tuple, TypeVar, Union, overload +from http.client import HTTPResponse +from urllib.request import Request + +_T = TypeVar('_T') + +class LoadError(OSError): ... + + +class CookieJar(Iterable[Cookie]): + def __init__(self, policy: Optional[CookiePolicy] = ...) -> None: ... + def add_cookie_header(self, request: Request) -> None: ... + def extract_cookies(self, response: HTTPResponse, + request: Request) -> None: ... + def set_policy(self, policy: CookiePolicy) -> None: ... + def make_cookies(self, response: HTTPResponse, + request: Request) -> Sequence[Cookie]: ... + def set_cookie(self, cookie: Cookie) -> None: ... + def set_cookie_if_ok(self, cookie: Cookie, + request: Request) -> None: ... + def clear(self, domain: str = ..., path: str = ..., + name: str = ...) -> None: ... + def clear_session_cookies(self) -> None: ... + def __iter__(self) -> Iterator[Cookie]: ... + def __len__(self) -> int: ... + +class FileCookieJar(CookieJar): + filename = ... # type: str + delayload = ... # type: bool + def __init__(self, filename: str = ..., delayload: bool = ..., + policy: Optional[CookiePolicy] = ...) -> None: ... + def save(self, filename: Optional[str] = ..., ignore_discard: bool = ..., + ignore_expires: bool = ...) -> None: ... + def load(self, filename: Optional[str] = ..., ignore_discard: bool = ..., + ignore_expires: bool = ...) -> None: ... + def revert(self, filename: Optional[str] = ..., ignore_discard: bool = ..., + ignore_expires: bool = ...) -> None: ... + +class MozillaCookieJar(FileCookieJar): ... +class LWPCookieJar(FileCookieJar): ... + + +class CookiePolicy: + netscape = ... # type: bool + rfc2965 = ... # type: bool + hide_cookie2 = ... # type: bool + def set_ok(self, cookie: Cookie, request: Request) -> bool: ... + def return_ok(self, cookie: Cookie, request: Request) -> bool: ... + def domain_return_ok(self, domain: str, request: Request) -> bool: ... + def path_return_ok(self, path: str, request: Request) -> bool: ... + + +class DefaultCookiePolicy(CookiePolicy): + rfc2109_as_netscape = ... # type: bool + strict_domain = ... # type: bool + strict_rfc2965_unverifiable = ... # type: bool + strict_ns_unverifiable = ... # type: bool + strict_ns_domain = ... # type: int + strict_ns_set_initial_dollar = ... # type: bool + strict_ns_set_path = ... # type: bool + DomainStrictNoDots = ... # type: int + DomainStrictNonDomain = ... # type: int + DomainRFC2965Match = ... # type: int + DomainLiberal = ... # type: int + DomainStrict = ... # type: int + def __init__(self, blocked_domains: Optional[Sequence[str]] = ..., + allowed_domains: Optional[Sequence[str]] = ..., + netscape: bool = ..., + rfc2965: bool = ..., + rfc2109_as_netscape: Optional[bool] = ..., + hide_cookie2: bool = ..., strict_domain: bool = ..., + strict_rfc2965_unverifiable: bool = ..., + strict_ns_unverifiable: bool = ..., + strict_ns_domain: int = ..., + strict_ns_set_initial_dollar: bool = ..., + strict_ns_set_path: bool = ...) -> None: ... + def blocked_domains(self) -> Tuple[str, ...]: ... + def set_blocked_domains(self, blocked_domains: Sequence[str]) -> None: ... + def is_blocked(self, domain: str) -> bool: ... + def allowed_domains(self) -> Optional[Tuple[str, ...]]: ... + def set_allowed_domains(self, allowed_domains: Optional[Sequence[str]]) -> None: ... + def is_not_allowed(self, domain: str) -> bool: ... + + +class Cookie: + version = ... # type: Optional[int] + name = ... # type: str + value = ... # type: Optional[str] + port = ... # type: Optional[str] + path = ... # type: str + secure = ... # type: bool + expires = ... # type: Optional[int] + discard = ... # type: bool + comment = ... # type: Optional[str] + comment_url = ... # type: Optional[str] + rfc2109 = ... # type: bool + port_specified = ... # type: bool + domain_specified = ... # type: bool + domain_initial_dot = ... # type: bool + def has_nonstandard_attr(self, name: str) -> bool: ... + @overload + def get_nonstandard_attr(self, name: str) -> Optional[str]: ... + @overload + def get_nonstandard_attr(self, name: str, default: _T = ...) -> Union[str, _T]: ... + def set_nonstandard_attr(self, name: str, value: str) -> None: ... + def is_expired(self, now: int = ...) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/3/http/cookies.pyi b/client/typeshed-fallback/stdlib/3/http/cookies.pyi new file mode 100644 index 000000000..1c415b565 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/http/cookies.pyi @@ -0,0 +1,31 @@ +# Stubs for http.cookies (Python 3.5) + +from typing import Generic, Dict, List, Mapping, MutableMapping, Optional, TypeVar, Union + +_DataType = Union[str, Mapping[str, Union[str, Morsel]]] +_T = TypeVar('_T') + +class CookieError(Exception): ... + +class Morsel(Dict[str, str], Generic[_T]): + value = ... # type: str + coded_value = ... # type: _T + key = ... # type: str + def set(self, key: str, val: str, coded_val: _T) -> None: ... + def isReservedKey(self, K: str) -> bool: ... + def output(self, attrs: Optional[List[str]] = ..., + header: str = ...) -> str: ... + def js_output(self, attrs: Optional[List[str]] = ...) -> str: ... + def OutputString(self, attrs: Optional[List[str]] = ...) -> str: ... + +class BaseCookie(Dict[str, Morsel], Generic[_T]): + def __init__(self, input: Optional[_DataType] = ...) -> None: ... + def value_decode(self, val: str) -> _T: ... + def value_encode(self, val: _T) -> str: ... + def output(self, attrs: Optional[List[str]] = ..., header: str = ..., + sep: str = ...) -> str: ... + def js_output(self, attrs: Optional[List[str]] = ...) -> str: ... + def load(self, rawdata: _DataType) -> None: ... + def __setitem__(self, key: str, value: Union[str, Morsel]) -> None: ... + +class SimpleCookie(BaseCookie): ... diff --git a/client/typeshed-fallback/stdlib/3/http/server.pyi b/client/typeshed-fallback/stdlib/3/http/server.pyi new file mode 100644 index 000000000..2e610e547 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/http/server.pyi @@ -0,0 +1,71 @@ +# Stubs for http.server (Python 3.4) + +import sys +from typing import Any, BinaryIO, Dict, List, Mapping, Optional, Tuple, Union +import socketserver +import email.message + +if sys.version_info >= (3, 7): + from builtins import _PathLike + +class HTTPServer(socketserver.TCPServer): + server_name = ... # type: str + server_port = ... # type: int + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: type) -> None: ... + +class BaseHTTPRequestHandler: + client_address = ... # type: Tuple[str, int] + server = ... # type: socketserver.BaseServer + close_connection = ... # type: bool + requestline = ... # type: str + command = ... # type: str + path = ... # type: str + request_version = ... # type: str + headers = ... # type: email.message.Message + rfile = ... # type: BinaryIO + wfile = ... # type: BinaryIO + server_version = ... # type: str + sys_version = ... # type: str + error_message_format = ... # type: str + error_content_type = ... # type: str + protocol_version = ... # type: str + MessageClass = ... # type: type + responses = ... # type: Mapping[int, Tuple[str, str]] + def __init__(self, request: bytes, client_address: Tuple[str, int], + server: socketserver.BaseServer) -> None: ... + def handle(self) -> None: ... + def handle_one_request(self) -> None: ... + def handle_expect_100(self) -> bool: ... + def send_error(self, code: int, message: Optional[str] = ..., + explain: Optional[str] = ...) -> None: ... + def send_response(self, code: int, + message: Optional[str] = ...) -> None: ... + def send_header(self, keyword: str, value: str) -> None: ... + def send_response_only(self, code: int, + message: Optional[str] = ...) -> None: ... + def end_headers(self) -> None: ... + def flush_headers(self) -> None: ... + def log_request(self, code: Union[int, str] = ..., + size: Union[int, str] = ...) -> None: ... + def log_error(self, format: str, *args: Any) -> None: ... + def log_message(self, format: str, *args: Any) -> None: ... + def version_string(self) -> str: ... + def date_time_string(self, timestamp: Optional[int] = ...) -> str: ... + def log_date_time_string(self) -> str: ... + def address_string(self) -> str: ... + +class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): + extensions_map = ... # type: Dict[str, str] + if sys.version_info >= (3, 7): + def __init__(self, request: bytes, client_address: Tuple[str, int], + server: socketserver.BaseServer, directory: Optional[Union[str, _PathLike[str]]]) -> None: ... + else: + def __init__(self, request: bytes, client_address: Tuple[str, int], + server: socketserver.BaseServer) -> None: ... + def do_GET(self) -> None: ... + def do_HEAD(self) -> None: ... + +class CGIHTTPRequestHandler(SimpleHTTPRequestHandler): + cgi_directories = ... # type: List[str] + def do_POST(self) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/imp.pyi b/client/typeshed-fallback/stdlib/3/imp.pyi new file mode 100644 index 000000000..33440910a --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/imp.pyi @@ -0,0 +1,55 @@ +# Stubs for imp (Python 3.6) + +import os +import sys +import types +from typing import Any, IO, List, Optional, Tuple, TypeVar, Union + +from _imp import (lock_held as lock_held, acquire_lock as acquire_lock, release_lock as release_lock, + get_frozen_object as get_frozen_object, is_frozen_package as is_frozen_package, + init_frozen as init_frozen, is_builtin as is_builtin, is_frozen as is_frozen) + +if sys.version_info >= (3, 5): + from _imp import create_dynamic as create_dynamic + +_T = TypeVar('_T') + +if sys.version_info >= (3, 6): + _Path = Union[str, os.PathLike[str]] +else: + _Path = str + +SEARCH_ERROR: int +PY_SOURCE: int +PY_COMPILED: int +C_EXTENSION: int +PY_RESOURCE: int +PKG_DIRECTORY: int +C_BUILTIN: int +PY_FROZEN: int +PY_CODERESOURCE: int +IMP_HOOK: int + +def new_module(name: str) -> types.ModuleType: ... +def get_magic() -> bytes: ... +def get_tag() -> str: ... +def cache_from_source(path: _Path, debug_override: Optional[bool] = ...) -> str: ... +def source_from_cache(path: _Path) -> str: ... +def get_suffixes() -> List[Tuple[str, str, int]]: ... + +class NullImporter: + def __init__(self, path: _Path) -> None: ... + def find_module(self, fullname: Any) -> None: ... + +# PathLike doesn't work for the pathname argument here +def load_source(name: str, pathname: str, file: Optional[IO[Any]] = ...) -> types.ModuleType: ... +def load_compiled(name: str, pathname: str, file: Optional[IO[Any]] = ...) -> types.ModuleType: ... +def load_package(name: str, path: _Path) -> types.ModuleType: ... +def load_module(name: str, file: IO[Any], filename: str, details: Tuple[str, str, int]) -> types.ModuleType: ... +if sys.version_info >= (3, 6): + def find_module(name: str, path: Union[None, List[str], List[os.PathLike[str]], List[_Path]] = ...) -> Tuple[str, str, Tuple[IO[Any], str, int]]: ... +else: + def find_module(name: str, path: Optional[List[str]] = ...) -> Tuple[str, str, Tuple[IO[Any], str, int]]: ... +def reload(module: types.ModuleType) -> types.ModuleType: ... +def init_builtin(name: str) -> Optional[types.ModuleType]: ... +def load_dynamic(name: str, path: str, file: Optional[IO[Any]] = ...) -> types.ModuleType: ... diff --git a/client/typeshed-fallback/stdlib/3/importlib/__init__.pyi b/client/typeshed-fallback/stdlib/3/importlib/__init__.pyi new file mode 100644 index 000000000..78a81712d --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/importlib/__init__.pyi @@ -0,0 +1,18 @@ +from importlib import util +from importlib.abc import Loader +import sys +import types +from typing import Any, Mapping, Optional, Sequence + +def __import__(name: str, globals: Optional[Mapping[str, Any]] = ..., + locals: Optional[Mapping[str, Any]] = ..., + fromlist: Sequence[str] = ..., + level: int = ...) -> types.ModuleType: ... + +def import_module(name: str, package: Optional[str] = ...) -> types.ModuleType: ... + +def find_loader(name: str, path: Optional[str] = ...) -> Optional[Loader]: ... + +def invalidate_caches() -> None: ... + +def reload(module: types.ModuleType) -> types.ModuleType: ... diff --git a/client/typeshed-fallback/stdlib/3/importlib/abc.pyi b/client/typeshed-fallback/stdlib/3/importlib/abc.pyi new file mode 100644 index 000000000..c811946b2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/importlib/abc.pyi @@ -0,0 +1,97 @@ +from abc import ABCMeta, abstractmethod +import os +import sys +import types +from typing import Any, IO, Iterator, Mapping, Optional, Sequence, Tuple, Union + +# Loader is exported from this module, but for circular import reasons +# exists in its own stub file (with ModuleSpec and ModuleType). +from _importlib_modulespec import Loader as Loader # Exported + +from _importlib_modulespec import ModuleSpec + +_Path = Union[bytes, str] + +class Finder(metaclass=ABCMeta): + ... + # Technically this class defines the following method, but its subclasses + # in this module violate its signature. Since this class is deprecated, it's + # easier to simply ignore that this method exists. + # @abstractmethod + # def find_module(self, fullname: str, + # path: Optional[Sequence[_Path]] = ...) -> Optional[Loader]: ... + +class ResourceLoader(Loader): + @abstractmethod + def get_data(self, path: _Path) -> bytes: ... + +class InspectLoader(Loader): + def is_package(self, fullname: str) -> bool: ... + def get_code(self, fullname: str) -> Optional[types.CodeType]: ... + def load_module(self, fullname: str) -> types.ModuleType: ... + @abstractmethod + def get_source(self, fullname: str) -> Optional[str]: ... + def exec_module(self, module: types.ModuleType) -> None: ... + if sys.version_info < (3, 5): + def source_to_code(self, data: Union[bytes, str], + path: str = ...) -> types.CodeType: ... + else: + @staticmethod + def source_to_code(data: Union[bytes, str], + path: str = ...) -> types.CodeType: ... + +class ExecutionLoader(InspectLoader): + @abstractmethod + def get_filename(self, fullname: str) -> _Path: ... + def get_code(self, fullname: str) -> Optional[types.CodeType]: ... + +class SourceLoader(ResourceLoader, ExecutionLoader, metaclass=ABCMeta): + def path_mtime(self, path: _Path) -> float: ... + def set_data(self, path: _Path, data: bytes) -> None: ... + def get_source(self, fullname: str) -> Optional[str]: ... + def path_stats(self, path: _Path) -> Mapping[str, Any]: ... + + +class MetaPathFinder(Finder): + def find_module(self, fullname: str, + path: Optional[Sequence[_Path]]) -> Optional[Loader]: + ... + def invalidate_caches(self) -> None: ... + # Not defined on the actual class, but expected to exist. + def find_spec( + self, fullname: str, path: Optional[Sequence[_Path]], + target: Optional[types.ModuleType] = ... + ) -> Optional[ModuleSpec]: + ... + +class PathEntryFinder(Finder): + def find_module(self, fullname: str) -> Optional[Loader]: ... + def find_loader( + self, fullname: str + ) -> Tuple[Optional[Loader], Sequence[_Path]]: ... + def invalidate_caches(self) -> None: ... + # Not defined on the actual class, but expected to exist. + def find_spec( + self, fullname: str, + target: Optional[types.ModuleType] = ... + ) -> Optional[ModuleSpec]: ... + +class FileLoader(ResourceLoader, ExecutionLoader, metaclass=ABCMeta): + name = ... # type: str + path = ... # type: _Path + def __init__(self, fullname: str, path: _Path) -> None: ... + def get_data(self, path: _Path) -> bytes: ... + def get_filename(self, fullname: str) -> _Path: ... + +if sys.version_info >= (3, 7): + _PathLike = Union[bytes, str, os.PathLike[Any]] + + class ResourceReader(metaclass=ABCMeta): + @abstractmethod + def open_resource(self, resource: _PathLike) -> IO[bytes]: ... + @abstractmethod + def resource_path(self, resource: _PathLike) -> str: ... + @abstractmethod + def is_resource(self, name: str) -> bool: ... + @abstractmethod + def contents(self) -> Iterator[str]: ... diff --git a/client/typeshed-fallback/stdlib/3/importlib/machinery.pyi b/client/typeshed-fallback/stdlib/3/importlib/machinery.pyi new file mode 100644 index 000000000..a60c30786 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/importlib/machinery.pyi @@ -0,0 +1,116 @@ +import importlib.abc +import sys +import types +from typing import Any, Callable, List, Optional, Sequence, Tuple, Union + +# ModuleSpec is exported from this module, but for circular import +# reasons exists in its own stub file (with Loader and ModuleType). +from _importlib_modulespec import ModuleSpec as ModuleSpec # Exported + +class BuiltinImporter(importlib.abc.MetaPathFinder, + importlib.abc.InspectLoader): + # MetaPathFinder + @classmethod + def find_module( + cls, fullname: str, + path: Optional[Sequence[importlib.abc._Path]] + ) -> Optional[importlib.abc.Loader]: + ... + @classmethod + def find_spec(cls, fullname: str, + path: Optional[Sequence[importlib.abc._Path]], + target: Optional[types.ModuleType] = ...) -> Optional[ModuleSpec]: + ... + # InspectLoader + @classmethod + def is_package(cls, fullname: str) -> bool: ... + @classmethod + def load_module(cls, fullname: str) -> types.ModuleType: ... + @classmethod + def get_code(cls, fullname: str) -> None: ... + @classmethod + def get_source(cls, fullname: str) -> None: ... + # Loader + @staticmethod + def module_repr(module: types.ModuleType) -> str: ... + @classmethod + def create_module(cls, spec: ModuleSpec) -> Optional[types.ModuleType]: ... + @classmethod + def exec_module(cls, module: types.ModuleType) -> None: ... + +class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): + # MetaPathFinder + @classmethod + def find_module( + cls, fullname: str, + path: Optional[Sequence[importlib.abc._Path]] + ) -> Optional[importlib.abc.Loader]: + ... + @classmethod + def find_spec(cls, fullname: str, + path: Optional[Sequence[importlib.abc._Path]], + target: Optional[types.ModuleType] = ...) -> Optional[ModuleSpec]: + ... + # InspectLoader + @classmethod + def is_package(cls, fullname: str) -> bool: ... + @classmethod + def load_module(cls, fullname: str) -> types.ModuleType: ... + @classmethod + def get_code(cls, fullname: str) -> None: ... + @classmethod + def get_source(cls, fullname: str) -> None: ... + # Loader + @staticmethod + def module_repr(module: types.ModuleType) -> str: ... + @classmethod + def create_module(cls, spec: ModuleSpec) -> Optional[types.ModuleType]: + ... + @staticmethod + def exec_module(module: types.ModuleType) -> None: ... + +class WindowsRegistryFinder(importlib.abc.MetaPathFinder): + @classmethod + def find_module( + cls, fullname: str, + path: Optional[Sequence[importlib.abc._Path]] + ) -> Optional[importlib.abc.Loader]: + ... + @classmethod + def find_spec(cls, fullname: str, + path: Optional[Sequence[importlib.abc._Path]], + target: Optional[types.ModuleType] = ...) -> Optional[ModuleSpec]: + ... + +class PathFinder(importlib.abc.MetaPathFinder): ... + +SOURCE_SUFFIXES = ... # type: List[str] +DEBUG_BYTECODE_SUFFIXES = ... # type: List[str] +OPTIMIZED_BYTECODE_SUFFIXES = ... # type: List[str] +BYTECODE_SUFFIXES = ... # type: List[str] +EXTENSION_SUFFIXES = ... # type: List[str] + +def all_suffixes() -> List[str]: ... + +class FileFinder(importlib.abc.PathEntryFinder): + path = ... # type: str + def __init__( + self, path: str, + *loader_details: Tuple[importlib.abc.Loader, List[str]] + ) -> None: ... + @classmethod + def path_hook( + cls, *loader_details: Tuple[importlib.abc.Loader, List[str]] + ) -> Callable[[str], importlib.abc.PathEntryFinder]: ... + +class SourceFileLoader(importlib.abc.FileLoader, + importlib.abc.SourceLoader): + ... + +class SourcelessFileLoader(importlib.abc.FileLoader, + importlib.abc.SourceLoader): + ... + +class ExtensionFileLoader(importlib.abc.ExecutionLoader): + def get_filename(self, fullname: str) -> importlib.abc._Path: ... + def get_source(self, fullname: str) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/importlib/resources.pyi b/client/typeshed-fallback/stdlib/3/importlib/resources.pyi new file mode 100644 index 000000000..007477d51 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/importlib/resources.pyi @@ -0,0 +1,25 @@ +import sys +# This is a >=3.7 module, so we conditionally include its source. +if sys.version_info >= (3, 7): + import os + + from pathlib import Path + from types import ModuleType + from typing import ContextManager, Iterator, Union, BinaryIO, TextIO + + Package = Union[str, ModuleType] + Resource = Union[str, os.PathLike] + + def open_binary(package: Package, resource: Resource) -> BinaryIO: ... + def open_text(package: Package, + resource: Resource, + encoding: str = ..., + errors: str = ...) -> TextIO: ... + def read_binary(package: Package, resource: Resource) -> bytes: ... + def read_text(package: Package, + resource: Resource, + encoding: str = ..., + errors: str = ...) -> str: ... + def path(package: Package, resource: Resource) -> ContextManager[Path]: ... + def is_resource(package: Package, name: str) -> bool: ... + def contents(package: Package) -> Iterator[str]: ... diff --git a/client/typeshed-fallback/stdlib/3/importlib/util.pyi b/client/typeshed-fallback/stdlib/3/importlib/util.pyi new file mode 100644 index 000000000..577c28ed5 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/importlib/util.pyi @@ -0,0 +1,53 @@ +import importlib.abc +import importlib.machinery +import sys +import types +from typing import Any, Callable, List, Optional + +def module_for_loader( + fxn: Callable[..., types.ModuleType] +) -> Callable[..., types.ModuleType]: ... +def set_loader( + fxn: Callable[..., types.ModuleType] +) -> Callable[..., types.ModuleType]: ... +def set_package( + fxn: Callable[..., types.ModuleType] +) -> Callable[..., types.ModuleType]: ... + +def resolve_name(name: str, package: str) -> str: ... + +MAGIC_NUMBER = ... # type: bytes + +def cache_from_source(path: str, debug_override: Optional[bool] = ..., *, + optimization: Optional[Any] = ...) -> str: ... +def source_from_cache(path: str) -> str: ... +def decode_source(source_bytes: bytes) -> str: ... +def find_spec( + name: str, package: Optional[str] = ... +) -> Optional[importlib.machinery.ModuleSpec]: ... +def spec_from_loader( + name: str, loader: Optional[importlib.abc.Loader], *, + origin: Optional[str] = ..., loader_state: Optional[Any] = ..., + is_package: Optional[bool] = ... +) -> importlib.machinery.ModuleSpec: ... +def spec_from_file_location( + name: str, location: str, *, + loader: Optional[importlib.abc.Loader] = ..., + submodule_search_locations: Optional[List[str]] = ... +) -> importlib.machinery.ModuleSpec: ... + +if sys.version_info >= (3, 5): + def module_from_spec( + spec: importlib.machinery.ModuleSpec + ) -> types.ModuleType: ... + + class LazyLoader(importlib.abc.Loader): + def __init__(self, loader: importlib.abc.Loader) -> None: ... + @classmethod + def factory( + cls, loader: importlib.abc.Loader + ) -> Callable[..., LazyLoader]: ... + def create_module( + self, spec: importlib.machinery.ModuleSpec + ) -> Optional[types.ModuleType]: ... + def exec_module(self, module: types.ModuleType) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/inspect.pyi b/client/typeshed-fallback/stdlib/3/inspect.pyi new file mode 100644 index 000000000..10f9b3ff4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/inspect.pyi @@ -0,0 +1,329 @@ +import sys +from typing import (AbstractSet, Any, Callable, Dict, Generator, List, Mapping, + MutableMapping, NamedTuple, Optional, Sequence, Tuple, + Union, + ) +from types import CodeType, FrameType, ModuleType, TracebackType + +# +# Types and members +# +class EndOfBlock(Exception): ... + +class BlockFinder: + indent: int + islambda: bool + started: bool + passline: bool + indecorator: bool + decoratorhasargs: bool + last: int + def tokeneater(self, type: int, token: str, srow_scol: Tuple[int, int], + erow_ecol: Tuple[int, int], line: str) -> None: ... + +CO_OPTIMIZED: int +CO_NEWLOCALS: int +CO_VARARGS: int +CO_VARKEYWORDS: int +CO_NESTED: int +CO_GENERATOR: int +CO_NOFREE: int +if sys.version_info >= (3, 5): + CO_COROUTINE: int + CO_ITERABLE_COROUTINE: int +if sys.version_info >= (3, 6): + CO_ASYNC_GENERATOR: int +TPFLAGS_IS_ABSTRACT: int + +if sys.version_info < (3, 6): + ModuleInfo = NamedTuple('ModuleInfo', [('name', str), + ('suffix', str), + ('mode', str), + ('module_type', int), + ]) + def getmoduleinfo(path: str) -> Optional[ModuleInfo]: ... + +def getmembers(object: object, + predicate: Optional[Callable[[Any], bool]] = ..., + ) -> List[Tuple[str, Any]]: ... +def getmodulename(path: str) -> Optional[str]: ... + +def ismodule(object: object) -> bool: ... +def isclass(object: object) -> bool: ... +def ismethod(object: object) -> bool: ... +def isfunction(object: object) -> bool: ... +def isgeneratorfunction(object: object) -> bool: ... +def isgenerator(object: object) -> bool: ... + +if sys.version_info >= (3, 5): + def iscoroutinefunction(object: object) -> bool: ... + def iscoroutine(object: object) -> bool: ... + def isawaitable(object: object) -> bool: ... +if sys.version_info >= (3, 6): + def isasyncgenfunction(object: object) -> bool: ... + def isasyncgen(object: object) -> bool: ... +def istraceback(object: object) -> bool: ... +def isframe(object: object) -> bool: ... +def iscode(object: object) -> bool: ... +def isbuiltin(object: object) -> bool: ... +def isroutine(object: object) -> bool: ... +def isabstract(object: object) -> bool: ... +def ismethoddescriptor(object: object) -> bool: ... +def isdatadescriptor(object: object) -> bool: ... +def isgetsetdescriptor(object: object) -> bool: ... +def ismemberdescriptor(object: object) -> bool: ... + + +# +# Retrieving source code +# +def findsource(object: object) -> Tuple[List[str], int]: ... +def getabsfile(object: object) -> str: ... +def getblock(lines: Sequence[str]) -> Sequence[str]: ... +def getdoc(object: object) -> str: ... +def getcomments(object: object) -> str: ... +def getfile(object: object) -> str: ... +def getmodule(object: object) -> ModuleType: ... +def getsourcefile(object: object) -> str: ... +# TODO restrict to "module, class, method, function, traceback, frame, +# or code object" +def getsourcelines(object: object) -> Tuple[List[str], int]: ... +# TODO restrict to "a module, class, method, function, traceback, frame, +# or code object" +def getsource(object: object) -> str: ... +def cleandoc(doc: str) -> str: ... +def indentsize(line: str) -> int: ... + + +# +# Introspecting callables with the Signature object +# +def signature(callable: Callable[..., Any], + *, + follow_wrapped: bool = ...) -> Signature: ... + +class Signature: + def __init__(self, + parameters: Optional[Sequence[Parameter]] = ..., + *, + return_annotation: Any = ...) -> None: ... + # TODO: can we be more specific here? + empty: object = ... + + parameters: Mapping[str, Parameter] + + # TODO: can we be more specific here? + return_annotation: Any + + def bind(self, *args: Any, **kwargs: Any) -> BoundArguments: ... + def bind_partial(self, *args: Any, **kwargs: Any) -> BoundArguments: ... + def replace(self, + *, + parameters: Optional[Sequence[Parameter]] = ..., + return_annotation: Any = ...) -> Signature: ... + + if sys.version_info >= (3, 5): + @classmethod + def from_callable(cls, + obj: Callable[..., Any], + *, + follow_wrapped: bool = ...) -> Signature: ... + +# The name is the same as the enum's name in CPython +class _ParameterKind: ... + +class Parameter: + def __init__(self, + name: str, + kind: _ParameterKind, + *, + default: Any = ..., + annotation: Any = ...) -> None: ... + empty: Any = ... + name: str + default: Any + annotation: Any + + kind: _ParameterKind + POSITIONAL_ONLY: _ParameterKind = ... + POSITIONAL_OR_KEYWORD: _ParameterKind = ... + VAR_POSITIONAL: _ParameterKind = ... + KEYWORD_ONLY: _ParameterKind = ... + VAR_KEYWORD: _ParameterKind = ... + + def replace(self, + *, + name: Optional[str] = ..., + kind: Optional[_ParameterKind] = ..., + default: Any = ..., + annotation: Any = ...) -> Parameter: ... + +class BoundArguments: + arguments: MutableMapping[str, Any] + args: Tuple[Any, ...] + kwargs: Dict[str, Any] + signature: Signature + + if sys.version_info >= (3, 5): + def apply_defaults(self) -> None: ... + + +# +# Classes and functions +# + +# TODO: The actual return type should be List[_ClassTreeItem] but mypy doesn't +# seem to be supporting this at the moment: +# _ClassTreeItem = Union[List[_ClassTreeItem], Tuple[type, Tuple[type, ...]]] +def getclasstree(classes: List[type], unique: bool = ...) -> Any: ... + +ArgSpec = NamedTuple('ArgSpec', [('args', List[str]), + ('varargs', str), + ('keywords', str), + ('defaults', tuple), + ]) + +Arguments = NamedTuple('Arguments', [('args', List[str]), + ('varargs', Optional[str]), + ('varkw', Optional[str]), + ]) + +def getargs(co: CodeType) -> Arguments: ... +def getargspec(func: object) -> ArgSpec: ... + +FullArgSpec = NamedTuple('FullArgSpec', [('args', List[str]), + ('varargs', Optional[str]), + ('varkw', Optional[str]), + ('defaults', tuple), + ('kwonlyargs', List[str]), + ('kwonlydefaults', Dict[str, Any]), + ('annotations', Dict[str, Any]), + ]) + +def getfullargspec(func: object) -> FullArgSpec: ... + +# TODO make the field types more specific here +ArgInfo = NamedTuple('ArgInfo', [('args', List[str]), + ('varargs', Optional[str]), + ('keywords', Optional[str]), + ('locals', Dict[str, Any]), + ]) + +def getargvalues(frame: FrameType) -> ArgInfo: ... +def formatannotation(annotation: object, base_module: Optional[str] = ...) -> str: ... +def formatannotationrelativeto(object: object) -> Callable[[object], str]: ... +def formatargspec(args: List[str], + varargs: Optional[str] = ..., + varkw: Optional[str] = ..., + defaults: Optional[Tuple[Any, ...]] = ..., + kwonlyargs: Optional[List[str]] = ..., + kwonlydefaults: Optional[Dict[str, Any]] = ..., + annotations: Dict[str, Any] = ..., + formatarg: Callable[[str], str] = ..., + formatvarargs: Callable[[str], str] = ..., + formatvarkw: Callable[[str], str] = ..., + formatvalue: Callable[[Any], str] = ..., + formatreturns: Callable[[Any], str] = ..., + formatannotations: Callable[[Any], str] = ..., + ) -> str: ... +def formatargvalues(args: List[str], + varargs: Optional[str] = ..., + varkw: Optional[str] = ..., + locals: Optional[Dict[str, Any]] = ..., + formatarg: Optional[Callable[[str], str]] = ..., + formatvarargs: Optional[Callable[[str], str]] = ..., + formatvarkw: Optional[Callable[[str], str]] = ..., + formatvalue: Optional[Callable[[Any], str]] = ..., + ) -> str: ... +def getmro(cls: type) -> Tuple[type, ...]: ... + +def getcallargs(func: Callable[..., Any], + *args: Any, + **kwds: Any) -> Dict[str, Any]: ... + + +ClosureVars = NamedTuple('ClosureVars', [('nonlocals', Mapping[str, Any]), + ('globals', Mapping[str, Any]), + ('builtins', Mapping[str, Any]), + ('unbound', AbstractSet[str]), + ]) +def getclosurevars(func: Callable[..., Any]) -> ClosureVars: ... + +def unwrap(func: Callable[..., Any], + *, + stop: Optional[Callable[[Any], Any]] = ...) -> Any: ... + + +# +# The interpreter stack +# + +Traceback = NamedTuple( + 'Traceback', + [ + ('filename', str), + ('lineno', int), + ('function', str), + ('code_context', List[str]), + ('index', int), + ] +) + +# Python 3.5+ (functions returning it used to return regular tuples) +FrameInfo = NamedTuple('FrameInfo', [('frame', FrameType), + ('filename', str), + ('lineno', int), + ('function', str), + ('code_context', List[str]), + ('index', int), + ]) + +def getframeinfo(frame: Union[FrameType, TracebackType], context: int = ...) -> Traceback: ... +def getouterframes(frame: Any, context: int = ...) -> List[FrameInfo]: ... +def getinnerframes(traceback: TracebackType, context: int = ...) -> List[FrameInfo]: ... +def getlineno(frame: FrameType) -> int: ... +def currentframe() -> Optional[FrameType]: ... +def stack(context: int = ...) -> List[FrameInfo]: ... +def trace(context: int = ...) -> List[FrameInfo]: ... + +# +# Fetching attributes statically +# + +def getattr_static(obj: object, attr: str, default: Optional[Any] = ...) -> Any: ... + + +# +# Current State of Generators and Coroutines +# + +# TODO In the next two blocks of code, can we be more specific regarding the +# type of the "enums"? + +GEN_CREATED: str +GEN_RUNNING: str +GEN_SUSPENDED: str +GEN_CLOSED: str +def getgeneratorstate(generator: Generator[Any, Any, Any]) -> str: ... + +if sys.version_info >= (3, 5): + CORO_CREATED: str + CORO_RUNNING: str + CORO_SUSPENDED: str + CORO_CLOSED: str + # TODO can we be more specific than "object"? + def getcoroutinestate(coroutine: object) -> str: ... + +def getgeneratorlocals(generator: Generator[Any, Any, Any]) -> Dict[str, Any]: ... + +if sys.version_info >= (3, 5): + # TODO can we be more specific than "object"? + def getcoroutinelocals(coroutine: object) -> Dict[str, Any]: ... + +Attribute = NamedTuple('Attribute', [('name', str), + ('kind', str), + ('defining_class', type), + ('object', object), + ]) + +def classify_class_attrs(cls: type) -> List[Attribute]: ... diff --git a/client/typeshed-fallback/stdlib/3/io.pyi b/client/typeshed-fallback/stdlib/3/io.pyi new file mode 100644 index 000000000..c9060b043 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/io.pyi @@ -0,0 +1,210 @@ +from typing import ( + List, BinaryIO, TextIO, Iterator, Union, Optional, Callable, Tuple, Type, Any, IO, Iterable +) +import builtins +import codecs +from mmap import mmap +import sys +from types import TracebackType +from typing import TypeVar + +_bytearray_like = Union[bytearray, mmap] + +DEFAULT_BUFFER_SIZE = ... # type: int + +SEEK_SET = ... # type: int +SEEK_CUR = ... # type: int +SEEK_END = ... # type: int + +_T = TypeVar('_T', bound='IOBase') + +open = builtins.open + +BlockingIOError = builtins.BlockingIOError +class UnsupportedOperation(OSError, ValueError): ... + +class IOBase: + def __iter__(self) -> Iterator[bytes]: ... + def __next__(self) -> bytes: ... + def __enter__(self: _T) -> _T: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType]) -> bool: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + def readlines(self, hint: int = ...) -> List[bytes]: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def writable(self) -> bool: ... + def writelines(self, lines: Iterable[Union[bytes, bytearray]]) -> None: ... + def readline(self, size: int = ...) -> bytes: ... + def __del__(self) -> None: ... + @property + def closed(self) -> bool: ... + +class RawIOBase(IOBase): + def readall(self) -> bytes: ... + def readinto(self, b: bytearray) -> Optional[int]: ... + def write(self, b: Union[bytes, bytearray]) -> Optional[int]: ... + def read(self, size: int = ...) -> Optional[bytes]: ... + +class BufferedIOBase(IOBase): + def detach(self) -> RawIOBase: ... + def readinto(self, b: _bytearray_like) -> int: ... + def write(self, b: Union[bytes, bytearray]) -> int: ... + if sys.version_info >= (3, 5): + def readinto1(self, b: _bytearray_like) -> int: ... + def read(self, size: Optional[int] = ...) -> bytes: ... + def read1(self, size: int = ...) -> bytes: ... + + +class FileIO(RawIOBase): + mode = ... # type: str + name = ... # type: Union[int, str] + def __init__( + self, + name: Union[str, bytes, int], + mode: str = ..., + closefd: bool = ..., + opener: Optional[Callable[[Union[int, str], str], int]] = ... + ) -> None: ... + +# TODO should extend from BufferedIOBase +class BytesIO(BinaryIO): + def __init__(self, initial_bytes: bytes = ...) -> None: ... + # BytesIO does not contain a "name" field. This workaround is necessary + # to allow BytesIO sub-classes to add this field, as it is defined + # as a read-only property on IO[]. + name: Any + def getvalue(self) -> bytes: ... + def getbuffer(self) -> memoryview: ... + # copied from IOBase + def __iter__(self) -> Iterator[bytes]: ... + def __next__(self) -> bytes: ... + def __enter__(self) -> BytesIO: ... + def __exit__(self, t: Optional[Type[BaseException]] = ..., value: Optional[BaseException] = ..., + traceback: Optional[TracebackType] = ...) -> bool: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + def readlines(self, hint: int = ...) -> List[bytes]: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def writable(self) -> bool: ... + # TODO should be the next line instead + # def writelines(self, lines: List[Union[bytes, bytearray]]) -> None: ... + def writelines(self, lines: Any) -> None: ... + def readline(self, size: int = ...) -> bytes: ... + def __del__(self) -> None: ... + closed = ... # type: bool + # copied from BufferedIOBase + def detach(self) -> RawIOBase: ... + def readinto(self, b: _bytearray_like) -> int: ... + def write(self, b: Union[bytes, bytearray]) -> int: ... + if sys.version_info >= (3, 5): + def readinto1(self, b: _bytearray_like) -> int: ... + def read(self, size: Optional[int] = ...) -> bytes: ... + def read1(self, size: int = ...) -> bytes: ... + +class BufferedReader(BufferedIOBase): + def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... + def peek(self, size: int = ...) -> bytes: ... + +class BufferedWriter(BufferedIOBase): + def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... + def flush(self) -> None: ... + def write(self, b: Union[bytes, bytearray]) -> int: ... + +class BufferedRandom(BufferedReader, BufferedWriter): + def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + +class BufferedRWPair(BufferedIOBase): + def __init__(self, reader: RawIOBase, writer: RawIOBase, + buffer_size: int = ...) -> None: ... + + +class TextIOBase(IOBase): + encoding = ... # type: str + errors = ... # type: Optional[str] + newlines = ... # type: Union[str, Tuple[str, ...], None] + def __iter__(self) -> Iterator[str]: ... # type: ignore + def __next__(self) -> str: ... # type: ignore + def detach(self) -> IOBase: ... + def write(self, s: str) -> int: ... + def writelines(self, lines: List[str]) -> None: ... # type: ignore + def readline(self, size: int = ...) -> str: ... # type: ignore + def readlines(self, hint: int = ...) -> List[str]: ... # type: ignore + def read(self, size: Optional[int] = ...) -> str: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + +# TODO should extend from TextIOBase +class TextIOWrapper(TextIO): + line_buffering = ... # type: bool + # TODO uncomment after fixing mypy about using write_through + # def __init__(self, buffer: IO[bytes], encoding: str = ..., + # errors: Optional[str] = ..., newline: Optional[str] = ..., + # line_buffering: bool = ..., write_through: bool = ...) \ + # -> None: ... + def __init__( + self, + buffer: IO[bytes], + encoding: str = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ..., + line_buffering: bool = ..., + write_through: bool = ... + ) -> None: ... + # copied from IOBase + def __exit__(self, t: Optional[Type[BaseException]] = ..., value: Optional[BaseException] = ..., + traceback: Optional[TracebackType] = ...) -> bool: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + def readlines(self, hint: int = ...) -> List[str]: ... + def seekable(self) -> bool: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def writable(self) -> bool: ... + # TODO should be the next line instead + # def writelines(self, lines: List[str]) -> None: ... + def writelines(self, lines: Any) -> None: ... + def __del__(self) -> None: ... + closed = ... # type: bool + # copied from TextIOBase + encoding = ... # type: str + errors = ... # type: Optional[str] + newlines = ... # type: Union[str, Tuple[str, ...], None] + def __iter__(self) -> Iterator[str]: ... + def __next__(self) -> str: ... + def __enter__(self) -> TextIO: ... + def detach(self) -> IOBase: ... + def write(self, s: str) -> int: ... + def readline(self, size: int = ...) -> str: ... + def read(self, size: Optional[int] = ...) -> str: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + +class StringIO(TextIOWrapper): + def __init__(self, initial_value: str = ..., + newline: Optional[str] = ...) -> None: ... + # StringIO does not contain a "name" field. This workaround is necessary + # to allow StringIO sub-classes to add this field, as it is defined + # as a read-only property on IO[]. + name: Any + def getvalue(self) -> str: ... + def __enter__(self) -> StringIO: ... + +class IncrementalNewlineDecoder(codecs.IncrementalDecoder): + def decode(self, input: bytes, final: bool = ...) -> str: ... diff --git a/client/typeshed-fallback/stdlib/3/ipaddress.pyi b/client/typeshed-fallback/stdlib/3/ipaddress.pyi new file mode 100644 index 000000000..f706330b6 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/ipaddress.pyi @@ -0,0 +1,151 @@ +import sys +from typing import (Any, Container, Generic, Iterable, Iterator, Optional, + overload, SupportsInt, Tuple, TypeVar) + +# Undocumented length constants +IPV4LENGTH: int +IPV6LENGTH: int + +_A = TypeVar("_A", IPv4Address, IPv6Address) +_N = TypeVar("_N", IPv4Network, IPv6Network) +_T = TypeVar("_T") + +def ip_address(address: object) -> Any: ... # morally Union[IPv4Address, IPv6Address] +def ip_network(address: object, strict: bool = ...) -> Any: ... # morally Union[IPv4Network, IPv6Network] +def ip_interface(address: object) -> Any: ... # morally Union[IPv4Interface, IPv6Interface] + +class _IPAddressBase: + def __eq__(self, other: Any) -> bool: ... + def __ge__(self: _T, other: _T) -> bool: ... + def __gt__(self: _T, other: _T) -> bool: ... + def __le__(self: _T, other: _T) -> bool: ... + def __lt__(self: _T, other: _T) -> bool: ... + def __ne__(self, other: Any) -> bool: ... + @property + def compressed(self) -> str: ... + @property + def exploded(self) -> str: ... + if sys.version_info >= (3, 5): + @property + def reverse_pointer(self) -> str: ... + @property + def version(self) -> int: ... + +class _BaseAddress(_IPAddressBase, SupportsInt): + def __init__(self, address: object) -> None: ... + def __add__(self: _T, other: int) -> _T: ... + def __hash__(self) -> int: ... + def __int__(self) -> int: ... + def __sub__(self: _T, other: int) -> _T: ... + @property + def is_global(self) -> bool: ... + @property + def is_link_local(self) -> bool: ... + @property + def is_loopback(self) -> bool: ... + @property + def is_multicast(self) -> bool: ... + @property + def is_private(self) -> bool: ... + @property + def is_reserved(self) -> bool: ... + @property + def is_unspecified(self) -> bool: ... + @property + def max_prefixlen(self) -> int: ... + @property + def packed(self) -> bytes: ... + +class _BaseNetwork(_IPAddressBase, Container, Iterable[_A], Generic[_A]): + network_address: _A + netmask: _A + def __init__(self, address: object, strict: bool = ...) -> None: ... + def __contains__(self, other: Any) -> bool: ... + def __getitem__(self, n: int) -> _A: ... + def __iter__(self) -> Iterator[_A]: ... + def address_exclude(self: _T, other: _T) -> Iterator[_T]: ... + @property + def broadcast_address(self) -> _A: ... + def compare_networks(self: _T, other: _T) -> int: ... + def hosts(self) -> Iterator[_A]: ... + @property + def is_global(self) -> bool: ... + @property + def is_link_local(self) -> bool: ... + @property + def is_loopback(self) -> bool: ... + @property + def is_multicast(self) -> bool: ... + @property + def is_private(self) -> bool: ... + @property + def is_reserved(self) -> bool: ... + @property + def is_unspecified(self) -> bool: ... + @property + def max_prefixlen(self) -> int: ... + @property + def num_addresses(self) -> int: ... + def overlaps(self: _T, other: _T) -> bool: ... + @property + def prefixlen(self) -> int: ... + def subnets(self: _T, prefixlen_diff: int = ..., new_prefix: Optional[int] = ...) -> Iterator[_T]: ... + def supernet(self: _T, prefixlen_diff: int = ..., new_prefix: Optional[int] = ...) -> _T: ... + @property + def with_hostmask(self) -> str: ... + @property + def with_netmask(self) -> str: ... + @property + def with_prefixlen(self) -> str: ... + @property + def hostmask(self) -> _A: ... + +class _BaseInterface(_BaseAddress, Generic[_A, _N]): + hostmask: _A + netmask: _A + network: _N + @property + def ip(self) -> _A: ... + @property + def with_hostmask(self) -> str: ... + @property + def with_netmask(self) -> str: ... + @property + def with_prefixlen(self) -> str: ... + +class IPv4Address(_BaseAddress): ... +class IPv4Network(_BaseNetwork[IPv4Address]): ... +class IPv4Interface(IPv4Address, _BaseInterface[IPv4Address, IPv4Network]): ... + +class IPv6Address(_BaseAddress): + @property + def ipv4_mapped(self) -> Optional[IPv4Address]: ... + @property + def is_site_local(self) -> bool: ... + @property + def sixtofour(self) -> Optional[IPv4Address]: ... + @property + def teredo(self) -> Optional[Tuple[IPv4Address, IPv4Address]]: ... + +class IPv6Network(_BaseNetwork[IPv6Address]): + @property + def is_site_local(self) -> bool: ... + +class IPv6Interface(IPv6Address, _BaseInterface[IPv6Address, IPv6Network]): ... + +def v4_int_to_packed(address: int) -> bytes: ... +def v6_int_to_packed(address: int) -> bytes: ... +@overload +def summarize_address_range(first: IPv4Address, last: IPv4Address) -> Iterator[IPv4Network]: ... +@overload +def summarize_address_range(first: IPv6Address, last: IPv6Address) -> Iterator[IPv6Network]: ... +def collapse_addresses(addresses: Iterable[_N]) -> Iterator[_N]: ... +@overload +def get_mixed_type_key(obj: _A) -> Tuple[int, _A]: ... +@overload +def get_mixed_type_key(obj: IPv4Network) -> Tuple[int, IPv4Address, IPv4Address]: ... +@overload +def get_mixed_type_key(obj: IPv6Network) -> Tuple[int, IPv6Address, IPv6Address]: ... + +class AddressValueError(ValueError): ... +class NetmaskValueError(ValueError): ... diff --git a/client/typeshed-fallback/stdlib/3/itertools.pyi b/client/typeshed-fallback/stdlib/3/itertools.pyi new file mode 100644 index 000000000..8330ad499 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/itertools.pyi @@ -0,0 +1,106 @@ +# Stubs for itertools + +# Based on http://docs.python.org/3.2/library/itertools.html + +from typing import (Iterator, TypeVar, Iterable, overload, Any, Callable, Tuple, + Generic, Optional) + +_T = TypeVar('_T') +_S = TypeVar('_S') +_N = TypeVar('_N', int, float) +Predicate = Callable[[_T], object] + +def count(start: _N = ..., + step: _N = ...) -> Iterator[_N]: ... # more general types? +def cycle(iterable: Iterable[_T]) -> Iterator[_T]: ... + +@overload +def repeat(object: _T) -> Iterator[_T]: ... +@overload +def repeat(object: _T, times: int) -> Iterator[_T]: ... + +def accumulate(iterable: Iterable[_T], func: Callable[[_T, _T], _T] = ...) -> Iterator[_T]: ... + +class chain(Iterator[_T], Generic[_T]): + def __init__(self, *iterables: Iterable[_T]) -> None: ... + def __next__(self) -> _T: ... + def __iter__(self) -> Iterator[_T]: ... + @staticmethod + def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... + +def compress(data: Iterable[_T], selectors: Iterable[Any]) -> Iterator[_T]: ... +def dropwhile(predicate: Predicate[_T], + iterable: Iterable[_T]) -> Iterator[_T]: ... +def filterfalse(predicate: Optional[Predicate[_T]], + iterable: Iterable[_T]) -> Iterator[_T]: ... + +@overload +def groupby(iterable: Iterable[_T], key: None = ...) -> Iterator[Tuple[_T, Iterator[_T]]]: ... +@overload +def groupby(iterable: Iterable[_T], key: Callable[[_T], _S]) -> Iterator[Tuple[_S, Iterator[_T]]]: ... + +@overload +def islice(iterable: Iterable[_T], stop: Optional[int]) -> Iterator[_T]: ... +@overload +def islice(iterable: Iterable[_T], start: Optional[int], stop: Optional[int], + step: Optional[int] = ...) -> Iterator[_T]: ... + +def starmap(func: Callable[..., _S], iterable: Iterable[Iterable[Any]]) -> Iterator[_S]: ... +def takewhile(predicate: Predicate[_T], + iterable: Iterable[_T]) -> Iterator[_T]: ... +def tee(iterable: Iterable[_T], n: int = ...) -> Tuple[Iterator[_T], ...]: ... +def zip_longest(*p: Iterable[Any], + fillvalue: Any = ...) -> Iterator[Any]: ... + +_T1 = TypeVar('_T1') +_T2 = TypeVar('_T2') +_T3 = TypeVar('_T3') +_T4 = TypeVar('_T4') +_T5 = TypeVar('_T5') +_T6 = TypeVar('_T6') + +@overload +def product(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4]) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def product(iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6]) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... +@overload +def product(iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + iter7: Iterable[Any], + *iterables: Iterable[Any]) -> Iterator[Tuple[Any, ...]]: ... +@overload +def product(*iterables: Iterable[Any], repeat: int = ...) -> Iterator[Tuple[Any, ...]]: ... + +def permutations(iterable: Iterable[_T], + r: Optional[int] = ...) -> Iterator[Tuple[_T, ...]]: ... +def combinations(iterable: Iterable[_T], + r: int) -> Iterable[Tuple[_T, ...]]: ... +def combinations_with_replacement(iterable: Iterable[_T], + r: int) -> Iterable[Tuple[_T, ...]]: ... diff --git a/client/typeshed-fallback/stdlib/3/json/__init__.pyi b/client/typeshed-fallback/stdlib/3/json/__init__.pyi new file mode 100644 index 000000000..620b239b4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/json/__init__.pyi @@ -0,0 +1,58 @@ +import sys +from typing import Any, IO, Optional, Tuple, Callable, Dict, List, Union, Protocol + +from .decoder import JSONDecoder as JSONDecoder +from .encoder import JSONEncoder as JSONEncoder +if sys.version_info >= (3, 5): + from .decoder import JSONDecodeError as JSONDecodeError + +def dumps(obj: Any, + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + cls: Any = ..., + indent: Union[None, int, str] = ..., + separators: Optional[Tuple[str, str]] = ..., + default: Optional[Callable[[Any], Any]] = ..., + sort_keys: bool = ..., + **kwds: Any) -> str: ... + +def dump(obj: Any, + fp: IO[str], + skipkeys: bool = ..., + ensure_ascii: bool = ..., + check_circular: bool = ..., + allow_nan: bool = ..., + cls: Any = ..., + indent: Union[None, int, str] = ..., + separators: Optional[Tuple[str, str]] = ..., + default: Optional[Callable[[Any], Any]] = ..., + sort_keys: bool = ..., + **kwds: Any) -> None: ... + +if sys.version_info >= (3, 6): + _LoadsString = Union[str, bytes, bytearray] +else: + _LoadsString = str +def loads(s: _LoadsString, + encoding: Any = ..., # ignored and deprecated + cls: Any = ..., + object_hook: Optional[Callable[[Dict], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., + **kwds: Any) -> Any: ... + +class _Reader(Protocol): + def read(self) -> _LoadsString: ... + +def load(fp: _Reader, + cls: Any = ..., + object_hook: Optional[Callable[[Dict], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., + **kwds: Any) -> Any: ... diff --git a/client/typeshed-fallback/stdlib/3/json/decoder.pyi b/client/typeshed-fallback/stdlib/3/json/decoder.pyi new file mode 100644 index 000000000..d02e3dce4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/json/decoder.pyi @@ -0,0 +1,28 @@ +import sys +from typing import Any, Callable, Dict, List, Optional, Tuple + +if sys.version_info >= (3, 5): + class JSONDecodeError(ValueError): + msg: str + doc: str + pos: int + lineno: int + colno: int + def __init__(self, msg: str, doc: str, pos: int) -> None: ... + +class JSONDecoder: + object_hook = ... # type: Callable[[Dict[str, Any]], Any] + parse_float = ... # type: Callable[[str], Any] + parse_int = ... # type: Callable[[str], Any] + parse_constant = ... # Callable[[str], Any] + strict = ... # type: bool + object_pairs_hook = ... # type: Callable[[List[Tuple[str, Any]]], Any] + + def __init__(self, object_hook: Optional[Callable[[Dict[str, Any]], Any]] = ..., + parse_float: Optional[Callable[[str], Any]] = ..., + parse_int: Optional[Callable[[str], Any]] = ..., + parse_constant: Optional[Callable[[str], Any]] = ..., + strict: bool = ..., + object_pairs_hook: Optional[Callable[[List[Tuple[str, Any]]], Any]] = ...) -> None: ... + def decode(self, s: str) -> Any: ... + def raw_decode(self, s: str, idx: int = ...) -> Tuple[Any, int]: ... diff --git a/client/typeshed-fallback/stdlib/3/json/encoder.pyi b/client/typeshed-fallback/stdlib/3/json/encoder.pyi new file mode 100644 index 000000000..b3981a927 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/json/encoder.pyi @@ -0,0 +1,21 @@ +from typing import Any, Callable, Iterator, Optional, Tuple + +class JSONEncoder: + item_separator = ... # type: str + key_separator = ... # type: str + + skipkeys = ... # type: bool + ensure_ascii = ... # type: bool + check_circular = ... # type: bool + allow_nan = ... # type: bool + sort_keys = ... # type: bool + indent = ... # type: int + + def __init__(self, skipkeys: bool = ..., ensure_ascii: bool = ..., + check_circular: bool = ..., allow_nan: bool = ..., sort_keys: bool = ..., + indent: Optional[int] = ..., separators: Optional[Tuple[str, str]] = ..., + default: Optional[Callable] = ...) -> None: ... + + def default(self, o: Any) -> Any: ... + def encode(self, o: Any) -> str: ... + def iterencode(self, o: Any, _one_shot: bool = ...) -> Iterator[str]: ... diff --git a/client/typeshed-fallback/stdlib/3/lzma.pyi b/client/typeshed-fallback/stdlib/3/lzma.pyi new file mode 100644 index 000000000..cd0a088b4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/lzma.pyi @@ -0,0 +1,107 @@ +import io +import sys +from typing import Any, IO, Mapping, Optional, Sequence, Union + +if sys.version_info >= (3, 6): + from os import PathLike + _PathOrFile = Union[str, bytes, IO[Any], PathLike[Any]] +else: + _PathOrFile = Union[str, bytes, IO[Any]] + +_FilterChain = Sequence[Mapping[str, Any]] + +FORMAT_AUTO: int +FORMAT_XZ: int +FORMAT_ALONE: int +FORMAT_RAW: int +CHECK_NONE: int +CHECK_CRC32: int +CHECK_CRC64: int +CHECK_SHA256: int +CHECK_ID_MAX: int +CHECK_UNKNOWN: int +FILTER_LZMA1: int +FILTER_LZMA2: int +FILTER_DELTA: int +FILTER_X86: int +FILTER_IA64: int +FILTER_ARM: int +FILTER_ARMTHUMB: int +FILTER_SPARC: int +FILTER_POWERPC: int +MF_HC3: int +MF_HC4: int +MF_BT2: int +MF_BT3: int +MF_BT4: int +MODE_FAST: int +MODE_NORMAL: int +PRESET_DEFAULT: int +PRESET_EXTREME: int + +# from _lzma.c +class LZMADecompressor(object): + def __init__(self, format: Optional[int] = ..., memlimit: Optional[int] = ..., filters: Optional[_FilterChain] = ...) -> None: ... + def decompress(self, data: bytes, max_length: int = ...) -> bytes: ... + @property + def check(self) -> int: ... + @property + def eof(self) -> bool: ... + @property + def unused_data(self) -> bytes: ... + if sys.version_info >= (3, 5): + @property + def needs_input(self) -> bool: ... + +# from _lzma.c +class LZMACompressor(object): + def __init__(self, + format: Optional[int] = ..., + check: int = ..., + preset: Optional[int] = ..., + filters: Optional[_FilterChain] = ...) -> None: ... + def compress(self, data: bytes) -> bytes: ... + def flush(self) -> bytes: ... + + +class LZMAError(Exception): ... + + +class LZMAFile(io.BufferedIOBase, IO[bytes]): # type: ignore # python/mypy#5027 + def __init__(self, + filename: Optional[_PathOrFile] = ..., + mode: str = ..., + *, + format: Optional[int] = ..., + check: int = ..., + preset: Optional[int] = ..., + filters: Optional[_FilterChain] = ...) -> None: ... + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + def fileno(self) -> int: ... + def seekable(self) -> bool: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def peek(self, size: int = ...) -> bytes: ... + def read(self, size: Optional[int] = ...) -> bytes: ... + def read1(self, size: int = ...) -> bytes: ... + def readline(self, size: int = ...) -> bytes: ... + def write(self, data: bytes) -> int: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + + +def open(filename: _PathOrFile, + mode: str = ..., + *, + format: Optional[int] = ..., + check: int = ..., + preset: Optional[int] = ..., + filters: Optional[_FilterChain] = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + newline: Optional[str] = ...) -> IO[Any]: ... +def compress(data: bytes, format: int = ..., check: int = ..., preset: Optional[int] = ..., filters: Optional[_FilterChain] = ...) -> bytes: ... +def decompress(data: bytes, format: int = ..., memlimit: Optional[int] = ..., filters: Optional[_FilterChain] = ...) -> bytes: ... +def is_check_supported(check: int) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/3/msvcrt.pyi b/client/typeshed-fallback/stdlib/3/msvcrt.pyi new file mode 100644 index 000000000..bcab64cd9 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/msvcrt.pyi @@ -0,0 +1,8 @@ +# Stubs for msvcrt + +# NOTE: These are incomplete! + +from typing import overload, BinaryIO, TextIO + +def get_osfhandle(file: int) -> int: ... +def open_osfhandle(handle: int, flags: int) -> int: ... diff --git a/client/typeshed-fallback/stdlib/3/multiprocessing/__init__.pyi b/client/typeshed-fallback/stdlib/3/multiprocessing/__init__.pyi new file mode 100644 index 000000000..3356bb50a --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/multiprocessing/__init__.pyi @@ -0,0 +1,84 @@ +# Stubs for multiprocessing + +from typing import ( + Any, Callable, ContextManager, Iterable, Mapping, Optional, Dict, List, + Union, Sequence, Tuple +) + +from logging import Logger +from multiprocessing import connection, pool, spawn, synchronize +from multiprocessing.context import ( + BaseContext, + ProcessError as ProcessError, BufferTooShort as BufferTooShort, TimeoutError as TimeoutError, AuthenticationError as AuthenticationError) +from multiprocessing.managers import SyncManager +from multiprocessing.process import current_process as current_process +from multiprocessing.queues import Queue as Queue, SimpleQueue as SimpleQueue, JoinableQueue as JoinableQueue +from multiprocessing.spawn import freeze_support as freeze_support +from multiprocessing.spawn import set_executable as set_executable + +import sys + +# N.B. The functions below are generated at runtime by partially applying +# multiprocessing.context.BaseContext's methods, so the two signatures should +# be identical (modulo self). + +# Sychronization primitives +_LockLike = Union[synchronize.Lock, synchronize.RLock] +def Barrier(parties: int, + action: Optional[Callable] = ..., + timeout: Optional[float] = ...) -> synchronize.Barrier: ... +def BoundedSemaphore(value: int = ...) -> synchronize.BoundedSemaphore: ... +def Condition(lock: Optional[_LockLike] = ...) -> synchronize.Condition: ... +def Event(lock: Optional[_LockLike] = ...) -> synchronize.Event: ... +def Lock() -> synchronize.Lock: ... +def RLock() -> synchronize.RLock: ... +def Semaphore(value: int = ...) -> synchronize.Semaphore: ... + +def Pipe(duplex: bool = ...) -> Tuple[connection.Connection, connection.Connection]: ... + +def Pool(processes: Optional[int] = ..., + initializer: Optional[Callable[..., Any]] = ..., + initargs: Iterable[Any] = ..., + maxtasksperchild: Optional[int] = ...) -> pool.Pool: ... + +class Process(): + name: str + daemon: bool + pid: Optional[int] + exitcode: Optional[int] + authkey: bytes + sentinel: int + # TODO: set type of group to None + def __init__(self, + group: Any = ..., + target: Optional[Callable] = ..., + name: Optional[str] = ..., + args: Iterable[Any] = ..., + kwargs: Mapping[Any, Any] = ..., + *, + daemon: Optional[bool] = ...) -> None: ... + def start(self) -> None: ... + def run(self) -> None: ... + def terminate(self) -> None: ... + if sys.version_info >= (3, 7): + def kill(self) -> None: ... + def close(self) -> None: ... + def is_alive(self) -> bool: ... + def join(self, timeout: Optional[float] = ...) -> None: ... + +class Value(): + value: Any = ... + def __init__(self, typecode_or_type: str, *args: Any, lock: bool = ...) -> None: ... + +# ----- multiprocessing function stubs ----- +def active_children() -> List[Process]: ... +def allow_connection_pickling() -> None: ... +def cpu_count() -> int: ... +def get_logger() -> Logger: ... +def log_to_stderr(level: Optional[Union[str, int]] = ...) -> Logger: ... +def Manager() -> SyncManager: ... +def set_forkserver_preload(module_names: List[str]) -> None: ... +def get_all_start_methods() -> List[str]: ... +def get_context(method: Optional[str] = ...) -> BaseContext: ... +def get_start_method(allow_none: Optional[bool]) -> Optional[str]: ... +def set_start_method(method: str, force: Optional[bool] = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/multiprocessing/connection.pyi b/client/typeshed-fallback/stdlib/3/multiprocessing/connection.pyi new file mode 100644 index 000000000..76bdca01c --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/multiprocessing/connection.pyi @@ -0,0 +1,48 @@ +from typing import Any, Iterable, List, Optional, Tuple, Type, Union +import socket +import sys +import types + +# https://docs.python.org/3/library/multiprocessing.html#address-formats +_Address = Union[str, Tuple[str, int]] + +class _ConnectionBase: + @property + def closed(self) -> bool: ... # undocumented + @property + def readable(self) -> bool: ... # undocumented + @property + def writable(self) -> bool: ... # undocumented + def fileno(self) -> int: ... + def close(self) -> None: ... + def send_bytes(self, + buf: bytes, + offset: int = ..., + size: Optional[int] = ...) -> None: ... + def send(self, obj: Any) -> None: ... + def recv_bytes(self, maxlength: Optional[int] = ...) -> bytes: ... + def recv_bytes_into(self, buf: Any, offset: int = ...) -> int: ... + def recv(self) -> Any: ... + def poll(self, timeout: Optional[float] = ...) -> bool: ... + +class Connection(_ConnectionBase): ... + +if sys.platform == "win32": + class PipeConnection(_ConnectionBase): ... + +class Listener: + def __init__(self, address: Optional[_Address] = ..., family: Optional[str] = ..., backlog: int = ..., authkey: Optional[bytes] = ...) -> None: ... + def accept(self) -> Connection: ... + def close(self) -> None: ... + @property + def address(self) -> _Address: ... + @property + def last_accepted(self) -> Optional[_Address]: ... + def __enter__(self) -> Listener: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], exc_tb: Optional[types.TracebackType]) -> None: ... + +def deliver_challenge(connection: Connection, authkey: bytes) -> None: ... +def answer_challenge(connection: Connection, authkey: bytes) -> None: ... +def wait(object_list: Iterable[Union[Connection, socket.socket, int]], timeout: Optional[float] = ...) -> List[Union[Connection, socket.socket, int]]: ... +def Client(address: _Address, family: Optional[str] = ..., authkey: Optional[bytes] = ...) -> Connection: ... +def Pipe(duplex: bool = ...) -> Tuple[Connection, Connection]: ... diff --git a/client/typeshed-fallback/stdlib/3/multiprocessing/context.pyi b/client/typeshed-fallback/stdlib/3/multiprocessing/context.pyi new file mode 100644 index 000000000..359d8907c --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/multiprocessing/context.pyi @@ -0,0 +1,179 @@ +# Stubs for multiprocessing.context + +from logging import Logger +import multiprocessing +from multiprocessing import synchronize +from multiprocessing import queues +import sys +from typing import ( + Any, Callable, Iterable, Optional, List, Mapping, Sequence, Tuple, Type, + Union, +) + +_LockLike = Union[synchronize.Lock, synchronize.RLock] + +class ProcessError(Exception): ... + +class BufferTooShort(ProcessError): ... + +class TimeoutError(ProcessError): ... + +class AuthenticationError(ProcessError): ... + +class BaseContext(object): + ProcessError = ... # type: Type[Exception] + BufferTooShort = ... # type: Type[Exception] + TimeoutError = ... # type: Type[Exception] + AuthenticationError = ... # type: Type[Exception] + + # N.B. The methods below are applied at runtime to generate + # multiprocessing.*, so the signatures should be identical (modulo self). + + @staticmethod + def current_process() -> multiprocessing.Process: ... + @staticmethod + def active_children() -> List[multiprocessing.Process]: ... + def cpu_count(self) -> int: ... + # TODO: change return to SyncManager once a stub exists in multiprocessing.managers + def Manager(self) -> Any: ... + # TODO: change return to Pipe once a stub exists in multiprocessing.connection + def Pipe(self, duplex: bool) -> Any: ... + + def Barrier(self, + parties: int, + action: Optional[Callable] = ..., + timeout: Optional[float] = ...) -> synchronize.Barrier: ... + def BoundedSemaphore(self, + value: int = ...) -> synchronize.BoundedSemaphore: ... + def Condition(self, + lock: Optional[_LockLike] = ...) -> synchronize.Condition: ... + def Event(self, lock: Optional[_LockLike] = ...) -> synchronize.Event: ... + def Lock(self) -> synchronize.Lock: ... + def RLock(self) -> synchronize.RLock: ... + def Semaphore(self, value: int = ...) -> synchronize.Semaphore: ... + + def Queue(self, maxsize: int = ...) -> queues.Queue: ... + def JoinableQueue(self, maxsize: int = ...) -> queues.JoinableQueue: ... + def SimpleQueue(self) -> queues.SimpleQueue: ... + def Pool( + self, + processes: Optional[int] = ..., + initializer: Optional[Callable[..., Any]] = ..., + initargs: Iterable[Any] = ..., + maxtasksperchild: Optional[int] = ... + ) -> multiprocessing.pool.Pool: ... + def Process( + self, + group: Any = ..., + target: Optional[Callable] = ..., + name: Optional[str] = ..., + args: Iterable[Any] = ..., + kwargs: Mapping[Any, Any] = ..., + *, + daemon: Optional[bool] = ... + ) -> multiprocessing.Process: ... + # TODO: typecode_or_type param is a ctype with a base class of _SimpleCData or array.typecode Need to figure out + # how to handle the ctype + # TODO: change return to RawValue once a stub exists in multiprocessing.sharedctypes + def RawValue(self, typecode_or_type: Any, *args: Any) -> Any: ... + # TODO: typecode_or_type param is a ctype with a base class of _SimpleCData or array.typecode Need to figure out + # how to handle the ctype + # TODO: change return to RawArray once a stub exists in multiprocessing.sharedctypes + def RawArray(self, typecode_or_type: Any, size_or_initializer: Union[int, Sequence[Any]]) -> Any: ... + # TODO: typecode_or_type param is a ctype with a base class of _SimpleCData or array.typecode Need to figure out + # how to handle the ctype + # TODO: change return to Value once a stub exists in multiprocessing.sharedctypes + def Value( + self, + typecode_or_type: Any, + *args: Any, + lock: bool = ... + ) -> Any: ... + # TODO: typecode_or_type param is a ctype with a base class of _SimpleCData or array.typecode Need to figure out + # how to handle the ctype + # TODO: change return to Array once a stub exists in multiprocessing.sharedctypes + def Array( + self, + typecode_or_type: Any, + size_or_initializer: Union[int, Sequence[Any]], + *, + lock: bool = ... + ) -> Any: ... + def freeze_support(self) -> None: ... + def get_logger(self) -> Logger: ... + def log_to_stderr(self, level: Optional[str] = ...) -> Logger: ... + def allow_connection_pickling(self) -> None: ... + def set_executable(self, executable: str) -> None: ... + def set_forkserver_preload(self, module_names: List[str]) -> None: ... + def get_context(self, method: Optional[str] = ...) -> BaseContext: ... + def get_start_method(self, allow_none: bool = ...) -> str: ... + def set_start_method(self, method: Optional[str] = ...) -> None: ... + @property + def reducer(self) -> str: ... + @reducer.setter + def reducer(self, reduction: str) -> None: ... + def _check_available(self) -> None: ... + +class Process(object): + _start_method: Optional[str] + @staticmethod + # TODO: type should be BaseProcess once a stub in multiprocessing.process exists + def _Popen(process_obj: Any) -> DefaultContext: ... + +class DefaultContext(object): + Process = ... # type: Type[multiprocessing.Process] + + def __init__(self, context: BaseContext) -> None: ... + def get_context(self, method: Optional[str] = ...) -> BaseContext: ... + def set_start_method(self, method: str, force: bool = ...) -> None: ... + def get_start_method(self, allow_none: bool = ...) -> str: ... + def get_all_start_methods(self) -> List[str]: ... + +if sys.platform != 'win32': + # TODO: type should be BaseProcess once a stub in multiprocessing.process exists + class ForkProcess(Any): # type: ignore + _start_method: str + @staticmethod + def _Popen(process_obj: Any) -> Any: ... + + # TODO: type should be BaseProcess once a stub in multiprocessing.process exists + class SpawnProcess(Any): # type: ignore + _start_method: str + @staticmethod + def _Popen(process_obj: Any) -> SpawnProcess: ... + + # TODO: type should be BaseProcess once a stub in multiprocessing.process exists + class ForkServerProcess(Any): # type: ignore + _start_method: str + @staticmethod + def _Popen(process_obj: Any) -> Any: ... + + class ForkContext(BaseContext): + _name: str + Process = ... # type: Type[ForkProcess] + + class SpawnContext(BaseContext): + _name: str + Process = ... # type: Type[SpawnProcess] + + class ForkServerContext(BaseContext): + _name: str + Process = ... # type: Type[ForkServerProcess] +else: + # TODO: type should be BaseProcess once a stub in multiprocessing.process exists + class SpawnProcess(Any): # type: ignore + _start_method: str + @staticmethod + # TODO: type should be BaseProcess once a stub in multiprocessing.process exists + def _Popen(process_obj: Process) -> Any: ... + + class SpawnContext(BaseContext): + _name: str + Process = ... # type: Type[SpawnProcess] + +def _force_start_method(method: str) -> None: ... +# TODO: type should be BaseProcess once a stub in multiprocessing.process exists +def get_spawning_popen() -> Optional[Any]: ... +# TODO: type should be BaseProcess once a stub in multiprocessing.process exists +def set_spawning_popen(popen: Any) -> None: ... +def assert_spawning(obj: Any) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/multiprocessing/dummy/__init__.pyi b/client/typeshed-fallback/stdlib/3/multiprocessing/dummy/__init__.pyi new file mode 100644 index 000000000..b393726ce --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/multiprocessing/dummy/__init__.pyi @@ -0,0 +1,42 @@ +from typing import Any, Optional, List, Type + +import array +import sys +import threading +import weakref + +from .connection import Pipe +from threading import Lock, RLock, Semaphore, BoundedSemaphore +from threading import Event, Condition, Barrier +from queue import Queue + +JoinableQueue = Queue + + +class DummyProcess(threading.Thread): + _children = ... # type: weakref.WeakKeyDictionary + _parent = ... # type: threading.Thread + _pid = ... # type: None + _start_called = ... # type: int + exitcode = ... # type: Optional[int] + def __init__(self, group=..., target=..., name=..., args=..., kwargs=...) -> None: ... + +Process = DummyProcess + +class Namespace(object): + def __init__(self, **kwds) -> None: ... + +class Value(object): + _typecode = ... # type: Any + _value = ... # type: Any + value = ... # type: Any + def __init__(self, typecode, value, lock=...) -> None: ... + + +def Array(typecode, sequence, lock=...) -> array.array: ... +def Manager() -> Any: ... +def Pool(processes=..., initializer=..., initargs=...) -> Any: ... +def active_children() -> List: ... +def current_process() -> threading.Thread: ... +def freeze_support() -> None: ... +def shutdown() -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/multiprocessing/dummy/connection.pyi b/client/typeshed-fallback/stdlib/3/multiprocessing/dummy/connection.pyi new file mode 100644 index 000000000..ec3ca42db --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/multiprocessing/dummy/connection.pyi @@ -0,0 +1,35 @@ +from typing import Any, List, Optional, Tuple, Type, TypeVar + +from queue import Queue + +families = ... # type: List[None] + +_TConnection = TypeVar('_TConnection', bound=Connection) +_TListener = TypeVar('_TListener', bound=Listener) + +class Connection(object): + _in = ... # type: Any + _out = ... # type: Any + recv = ... # type: Any + recv_bytes = ... # type: Any + send = ... # type: Any + send_bytes = ... # type: Any + def __enter__(self: _TConnection) -> _TConnection: ... + def __exit__(self, exc_type, exc_value, exc_tb) -> None: ... + def __init__(self, _in, _out) -> None: ... + def close(self) -> None: ... + def poll(self, timeout: float = ...) -> bool: ... + +class Listener(object): + _backlog_queue = ... # type: Optional[Queue] + @property + def address(self) -> Optional[Queue]: ... + def __enter__(self: _TListener) -> _TListener: ... + def __exit__(self, exc_type, exc_value, exc_tb) -> None: ... + def __init__(self, address=..., family=..., backlog=...) -> None: ... + def accept(self) -> Connection: ... + def close(self) -> None: ... + + +def Client(address) -> Connection: ... +def Pipe(duplex: bool = ...) -> Tuple[Connection, Connection]: ... diff --git a/client/typeshed-fallback/stdlib/3/multiprocessing/managers.pyi b/client/typeshed-fallback/stdlib/3/multiprocessing/managers.pyi new file mode 100644 index 000000000..a5ec399d7 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/multiprocessing/managers.pyi @@ -0,0 +1,47 @@ +# Stubs for multiprocessing.managers + +# NOTE: These are incomplete! + +import queue +import threading +from typing import ( + Any, Callable, ContextManager, Dict, Iterable, List, Mapping, Optional, + Sequence, Tuple, TypeVar, Union, +) + +_T = TypeVar('_T') +_KT = TypeVar('_KT') +_VT = TypeVar('_VT') + +class Namespace: ... + +_Namespace = Namespace + +class BaseManager(ContextManager[BaseManager]): + address: Union[str, Tuple[str, int]] + def connect(self) -> None: ... + @classmethod + def register(cls, typeid: str, callable: Optional[Callable] = ..., + proxytype: Any = ..., + exposed: Optional[Sequence[str]] = ..., + method_to_typeid: Optional[Mapping[str, str]] = ..., + create_method: bool = ...) -> None: ... + def shutdown(self) -> None: ... + def start(self, initializer: Optional[Callable[..., Any]] = ..., + initargs: Iterable[Any] = ...) -> None: ... + +class SyncManager(BaseManager): + def BoundedSemaphore(self, value: Any = ...) -> threading.BoundedSemaphore: ... + def Condition(self, lock: Any = ...) -> threading.Condition: ... + def Event(self) -> threading.Event: ... + def Lock(self) -> threading.Lock: ... + def Namespace(self) -> _Namespace: ... + def Queue(self, maxsize: int = ...) -> queue.Queue: ... + def RLock(self) -> threading.RLock: ... + def Semaphore(self, value: Any = ...) -> threading.Semaphore: ... + def Array(self, typecode: Any, sequence: Sequence[_T]) -> Sequence[_T]: ... + def Value(self, typecode: Any, value: _T) -> _T: ... + def dict(self, sequence: Mapping[_KT, _VT] = ...) -> Dict[_KT, _VT]: ... + def list(self, sequence: Sequence[_T] = ...) -> List[_T]: ... + +class RemoteError(Exception): ... diff --git a/client/typeshed-fallback/stdlib/3/multiprocessing/pool.pyi b/client/typeshed-fallback/stdlib/3/multiprocessing/pool.pyi new file mode 100644 index 000000000..469d83ad3 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/multiprocessing/pool.pyi @@ -0,0 +1,87 @@ +from typing import ( + Any, Callable, ContextManager, Iterable, Mapping, Optional, List, + Type, TypeVar, Generic, Iterator +) +from types import TracebackType + +_PT = TypeVar('_PT', bound='Pool') +_S = TypeVar('_S') +_T = TypeVar('_T') + +class ApplyResult(Generic[_T]): + def get(self, timeout: Optional[float] = ...) -> _T: ... + def wait(self, timeout: Optional[float] = ...) -> None: ... + def ready(self) -> bool: ... + def successful(self) -> bool: ... + +# alias created during issue #17805 +AsyncResult = ApplyResult + +_IMIT = TypeVar('_IMIT', bound=IMapIterator) + +class IMapIterator(Iterator[_T]): + def __iter__(self: _IMIT) -> _IMIT: ... + def next(self, timeout: Optional[float] = ...) -> _T: ... + def __next__(self, timeout: Optional[float] = ...) -> _T: ... + +class IMapUnorderedIterator(IMapIterator): ... + +class Pool(ContextManager[Pool]): + def __init__(self, processes: Optional[int] = ..., + initializer: Optional[Callable[..., None]] = ..., + initargs: Iterable[Any] = ..., + maxtasksperchild: Optional[int] = ..., + context: Optional[Any] = ...) -> None: ... + def apply(self, + func: Callable[..., _T], + args: Iterable[Any] = ..., + kwds: Mapping[str, Any] = ...) -> _T: ... + def apply_async(self, + func: Callable[..., _T], + args: Iterable[Any] = ..., + kwds: Mapping[str, Any] = ..., + callback: Optional[Callable[[_T], None]] = ..., + error_callback: Optional[Callable[[BaseException], None]] = ...) -> AsyncResult[_T]: ... + def map(self, + func: Callable[[_S], _T], + iterable: Iterable[_S] = ..., + chunksize: Optional[int] = ...) -> List[_T]: ... + def map_async(self, func: Callable[[_S], _T], + iterable: Iterable[_S] = ..., + chunksize: Optional[int] = ..., + callback: Optional[Callable[[_T], None]] = ..., + error_callback: Optional[Callable[[BaseException], None]] = ...) -> AsyncResult[List[_T]]: ... + def imap(self, + func: Callable[[_S], _T], + iterable: Iterable[_S] = ..., + chunksize: Optional[int] = ...) -> IMapIterator[_T]: ... + def imap_unordered(self, + func: Callable[[_S], _T], + iterable: Iterable[_S] = ..., + chunksize: Optional[int] = ...) -> IMapIterator[_T]: ... + def starmap(self, + func: Callable[..., _T], + iterable: Iterable[Iterable[Any]] = ..., + chunksize: Optional[int] = ...) -> List[_T]: ... + def starmap_async(self, + func: Callable[..., _T], + iterable: Iterable[Iterable[Any]] = ..., + chunksize: Optional[int] = ..., + callback: Optional[Callable[[_T], None]] = ..., + error_callback: Optional[Callable[[BaseException], None]] = ...) -> AsyncResult[List[_T]]: ... + def close(self) -> None: ... + def terminate(self) -> None: ... + def join(self) -> None: ... + def __enter__(self: _PT) -> _PT: ... + + +class ThreadPool(Pool, ContextManager[ThreadPool]): + + def __init__(self, processes: Optional[int] = ..., + initializer: Optional[Callable[..., Any]] = ..., + initargs: Iterable[Any] = ...) -> None: ... + +# undocumented +RUN: int +CLOSE: int +TERMINATE: int diff --git a/client/typeshed-fallback/stdlib/3/multiprocessing/process.pyi b/client/typeshed-fallback/stdlib/3/multiprocessing/process.pyi new file mode 100644 index 000000000..df8ea9300 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/multiprocessing/process.pyi @@ -0,0 +1,5 @@ +from typing import List +from multiprocessing import Process + +def current_process() -> Process: ... +def active_children() -> List[Process]: ... diff --git a/client/typeshed-fallback/stdlib/3/multiprocessing/queues.pyi b/client/typeshed-fallback/stdlib/3/multiprocessing/queues.pyi new file mode 100644 index 000000000..c6dd0f20d --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/multiprocessing/queues.pyi @@ -0,0 +1,30 @@ +from typing import Any, Generic, Optional, TypeVar + +import queue + +_T = TypeVar('_T') + +class Queue(queue.Queue[_T]): + # FIXME: `ctx` is a circular dependency and it's not actually optional. + # It's marked as such to be able to use the generic Queue in __init__.pyi. + def __init__(self, maxsize: int = ..., *, ctx: Any = ...) -> None: ... + def get(self, block: bool = ..., timeout: Optional[float] = ...) -> _T: ... + def put(self, obj: _T, block: bool = ..., timeout: Optional[float] = ...) -> None: ... + def qsize(self) -> int: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def put_nowait(self, item: _T) -> None: ... + def get_nowait(self) -> _T: ... + def close(self) -> None: ... + def join_thread(self) -> None: ... + def cancel_join_thread(self) -> None: ... + +class JoinableQueue(Queue[_T]): + def task_done(self) -> None: ... + def join(self) -> None: ... + +class SimpleQueue(Generic[_T]): + def __init__(self, *, ctx: Any = ...) -> None: ... + def empty(self) -> bool: ... + def get(self) -> _T: ... + def put(self, item: _T) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/multiprocessing/spawn.pyi b/client/typeshed-fallback/stdlib/3/multiprocessing/spawn.pyi new file mode 100644 index 000000000..659253c48 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/multiprocessing/spawn.pyi @@ -0,0 +1,18 @@ +from typing import Any, Dict, List, Mapping, Optional, Sequence +from types import ModuleType + +WINEXE: bool +WINSERVICE: bool + +def set_executable(exe: str) -> None: ... +def get_executable() -> str: ... +def is_forking(argv: Sequence[str]) -> bool: ... +def freeze_support() -> None: ... +def get_command_line(**kwds: Any) -> List[str]: ... +def spawn_main(pipe_handle: int, parent_pid: Optional[int] = ..., tracker_fd: Optional[int] = ...) -> None: ... +# undocumented +def _main(fd: int) -> Any: ... +def get_preparation_data(name: str) -> Dict[str, Any]: ... +old_main_modules: List[ModuleType] = ... +def prepare(data: Mapping[str, Any]) -> None: ... +def import_main_path(main_path: str) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/multiprocessing/synchronize.pyi b/client/typeshed-fallback/stdlib/3/multiprocessing/synchronize.pyi new file mode 100644 index 000000000..9b226810e --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/multiprocessing/synchronize.pyi @@ -0,0 +1,63 @@ +from typing import Callable, ContextManager, Optional, Union + +from multiprocessing.context import BaseContext +import threading +import sys + +_LockLike = Union[Lock, RLock] + +class Barrier(threading.Barrier): + def __init__(self, + parties: int, + action: Optional[Callable] = ..., + timeout: Optional[float] = ..., + * + ctx: BaseContext) -> None: ... + +class BoundedSemaphore(Semaphore): + def __init__(self, value: int = ..., *, ctx: BaseContext) -> None: ... + +class Condition(ContextManager[bool]): + def __init__(self, + lock: Optional[_LockLike] = ..., + *, + ctx: BaseContext) -> None: ... + if sys.version_info >= (3, 7): + def notify(self, n: int = ...) -> None: ... + else: + def notify(self) -> None: ... + def notify_all(self) -> None: ... + def wait(self, timeout: Optional[float] = ...) -> bool: ... + def wait_for(self, + predicate: Callable[[], bool], + timeout: Optional[float] = ...) -> bool: ... + def acquire(self, + block: bool = ..., + timeout: Optional[float] = ...) -> bool: ... + def release(self) -> None: ... + +class Event(ContextManager[bool]): + def __init__(self, + lock: Optional[_LockLike] = ..., + *, + ctx: BaseContext) -> None: ... + def is_set(self) -> bool: ... + def set(self) -> None: ... + def clear(self) -> None: ... + def wait(self, timeout: Optional[float] = ...) -> bool: ... + +class Lock(SemLock): + def __init__(self, *, ctx: BaseContext) -> None: ... + +class RLock(SemLock): + def __init__(self, *, ctx: BaseContext) -> None: ... + +class Semaphore(SemLock): + def __init__(self, value: int = ..., *, ctx: BaseContext) -> None: ... + +# Not part of public API +class SemLock(ContextManager[bool]): + def acquire(self, + block: bool = ..., + timeout: Optional[float] = ...) -> bool: ... + def release(self) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/nntplib.pyi b/client/typeshed-fallback/stdlib/3/nntplib.pyi new file mode 100644 index 000000000..00abdd994 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/nntplib.pyi @@ -0,0 +1,102 @@ +# Stubs for nntplib (Python 3) + +import datetime +import socket +import ssl +from typing import Any, Dict, IO, Iterable, List, NamedTuple, Optional, Tuple, TypeVar, Union + +_SelfT = TypeVar('_SelfT', bound=_NNTPBase) +_File = Union[IO[bytes], bytes, str, None] + + +class NNTPError(Exception): + response: str +class NNTPReplyError(NNTPError): ... +class NNTPTemporaryError(NNTPError): ... +class NNTPPermanentError(NNTPError): ... +class NNTPProtocolError(NNTPError): ... +class NNTPDataError(NNTPError): ... + +NNTP_PORT: int +NNTP_SSL_PORT: int + +GroupInfo = NamedTuple('GroupInfo', [ + ('group', str), + ('last', str), + ('first', str), + ('flag', str), +]) +ArticleInfo = NamedTuple('ArticleInfo', [ + ('number', int), + ('message_id', str), + ('lines', List[bytes]), +]) + +def decode_header(header_str: str) -> str: ... + +class _NNTPBase: + encoding: str + errors: str + + host: str + file: IO[bytes] + debugging: int + welcome: str + readermode_afterauth: bool + tls_on: bool + authenticated: bool + nntp_implementation: str + nntp_version: int + + def __init__(self, file: IO[bytes], host: str, + readermode: Optional[bool] = ..., timeout: float = ...) -> None: ... + def __enter__(self: _SelfT) -> _SelfT: ... + def __exit__(self, *args: Any) -> None: ... + def getwelcome(self) -> str: ... + def getcapabilities(self) -> Dict[str, List[str]]: ... + def set_debuglevel(self, level: int) -> None: ... + def debug(self, level: int) -> None: ... + def capabilities(self) -> Tuple[str, Dict[str, List[str]]]: ... + def newgroups(self, date: Union[datetime.date, datetime.datetime], *, file: _File = ...) -> Tuple[str, List[str]]: ... + def newnews(self, group: str, date: Union[datetime.date, datetime.datetime], *, file: _File = ...) -> Tuple[str, List[str]]: ... + def list(self, group_pattern: Optional[str] = ..., *, file: _File = ...) -> Tuple[str, List[str]]: ... + def description(self, group: str) -> str: ... + def descriptions(self, group_pattern: str) -> Tuple[str, Dict[str, str]]: ... + def group(self, name: str) -> Tuple[str, int, int, int, str]: ... + def help(self, *, file: _File = ...) -> Tuple[str, List[str]]: ... + def stat(self, message_spec: Any = ...) -> Tuple[str, int, str]: ... + def next(self) -> Tuple[str, int, str]: ... + def last(self) -> Tuple[str, int, str]: ... + def head(self, message_spec: Any = ..., *, file: _File = ...) -> Tuple[str, ArticleInfo]: ... + def body(self, message_spec: Any = ..., *, file: _File = ...) -> Tuple[str, ArticleInfo]: ... + def article(self, message_spec: Any = ..., *, file: _File = ...) -> Tuple[str, ArticleInfo]: ... + def slave(self) -> str: ... + def xhdr(self, hdr: str, str: Any, *, file: _File = ...) -> Tuple[str, List[str]]: ... + def xover(self, start: int, end: int, *, file: _File = ...) -> Tuple[str, List[Tuple[int, Dict[str, str]]]]: ... + def over(self, message_spec: Union[None, str, List[Any], Tuple[Any, ...]], *, file: _File = ...) -> Tuple[str, List[Tuple[int, Dict[str, str]]]]: ... + def xgtitle(self, group: str, *, file: _File = ...) -> Tuple[str, List[Tuple[str, str]]]: ... + def xpath(self, id: Any) -> Tuple[str, str]: ... + def date(self) -> Tuple[str, datetime.datetime]: ... + def post(self, data: Union[bytes, Iterable[bytes]]) -> str: ... + def ihave(self, message_id: Any, data: Union[bytes, Iterable[bytes]]) -> str: ... + def quit(self) -> str: ... + def login(self, user: Optional[str] = ..., password: Optional[str] = ..., usenetrc: bool = ...) -> None: ... + def starttls(self, ssl_context: Optional[ssl.SSLContext] = ...) -> None: ... + + +class NNTP(_NNTPBase): + port: int + sock: socket.socket + + def __init__(self, host: str, port: int = ..., user: Optional[str] = ..., password: Optional[str] = ..., + readermode: Optional[bool] = ..., usenetrc: bool = ..., + timeout: float = ...) -> None: ... + + +class NNTP_SSL(_NNTPBase): + sock: socket.socket + + def __init__(self, host: str, port: int = ..., user: Optional[str] = ..., password: Optional[str] = ..., + ssl_context: Optional[ssl.SSLContext] = ..., + readermode: Optional[bool] = ..., usenetrc: bool = ..., + timeout: float = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/nturl2path.pyi b/client/typeshed-fallback/stdlib/3/nturl2path.pyi new file mode 100644 index 000000000..b8ad8d682 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/nturl2path.pyi @@ -0,0 +1,2 @@ +def url2pathname(url: str) -> str: ... +def pathname2url(p: str) -> str: ... diff --git a/client/typeshed-fallback/stdlib/3/os/__init__.pyi b/client/typeshed-fallback/stdlib/3/os/__init__.pyi new file mode 100644 index 000000000..2197a4e8c --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/os/__init__.pyi @@ -0,0 +1,719 @@ +# Stubs for os +# Ron Murawski + +from io import TextIOWrapper as _TextIOWrapper +import sys +from typing import ( + Mapping, MutableMapping, Dict, List, Any, Tuple, IO, Iterable, Iterator, NoReturn, overload, Union, AnyStr, + Optional, Generic, Set, Callable, Text, Sequence, NamedTuple, TypeVar, ContextManager +) + +# Re-exported names from other modules. +from builtins import OSError as error +from . import path as path + +_T = TypeVar('_T') + +# ----- os variables ----- + +if sys.version_info >= (3, 2): + supports_bytes_environ: bool + +if sys.version_info >= (3, 3): + supports_dir_fd: Set[Callable[..., Any]] + supports_fd: Set[Callable[..., Any]] + supports_effective_ids: Set[Callable[..., Any]] + supports_follow_symlinks: Set[Callable[..., Any]] + + if sys.platform != 'win32': + # Unix only + PRIO_PROCESS: int + PRIO_PGRP: int + PRIO_USER: int + + F_LOCK: int + F_TLOCK: int + F_ULOCK: int + F_TEST: int + + POSIX_FADV_NORMAL: int + POSIX_FADV_SEQUENTIAL: int + POSIX_FADV_RANDOM: int + POSIX_FADV_NOREUSE: int + POSIX_FADV_WILLNEED: int + POSIX_FADV_DONTNEED: int + + SF_NODISKIO: int + SF_MNOWAIT: int + SF_SYNC: int + + XATTR_SIZE_MAX: int # Linux only + XATTR_CREATE: int # Linux only + XATTR_REPLACE: int # Linux only + + P_PID: int + P_PGID: int + P_ALL: int + + WEXITED: int + WSTOPPED: int + WNOWAIT: int + + CLD_EXITED: int + CLD_DUMPED: int + CLD_TRAPPED: int + CLD_CONTINUED: int + + SCHED_OTHER: int # some flavors of Unix + SCHED_BATCH: int # some flavors of Unix + SCHED_IDLE: int # some flavors of Unix + SCHED_SPORADIC: int # some flavors of Unix + SCHED_FIFO: int # some flavors of Unix + SCHED_RR: int # some flavors of Unix + SCHED_RESET_ON_FORK: int # some flavors of Unix + + RTLD_LAZY: int + RTLD_NOW: int + RTLD_GLOBAL: int + RTLD_LOCAL: int + RTLD_NODELETE: int + RTLD_NOLOAD: int + RTLD_DEEPBIND: int + + +SEEK_SET: int +SEEK_CUR: int +SEEK_END: int +if sys.version_info >= (3, 3) and sys.platform != 'win32': + SEEK_DATA: int # some flavors of Unix + SEEK_HOLE: int # some flavors of Unix + +O_RDONLY: int +O_WRONLY: int +O_RDWR: int +O_APPEND: int +O_CREAT: int +O_EXCL: int +O_TRUNC: int +# We don't use sys.platform for O_* flags to denote platform-dependent APIs because some codes, +# including tests for mypy, use a more finer way than sys.platform before using these APIs +# See https://github.com/python/typeshed/pull/2286 for discussions +O_DSYNC: int # Unix only +O_RSYNC: int # Unix only +O_SYNC: int # Unix only +O_NDELAY: int # Unix only +O_NONBLOCK: int # Unix only +O_NOCTTY: int # Unix only +if sys.version_info >= (3, 3): + O_CLOEXEC: int # Unix only +O_SHLOCK: int # Unix only +O_EXLOCK: int # Unix only +O_BINARY: int # Windows only +O_NOINHERIT: int # Windows only +O_SHORT_LIVED: int # Windows only +O_TEMPORARY: int # Windows only +O_RANDOM: int # Windows only +O_SEQUENTIAL: int # Windows only +O_TEXT: int # Windows only +O_ASYNC: int # Gnu extension if in C library +O_DIRECT: int # Gnu extension if in C library +O_DIRECTORY: int # Gnu extension if in C library +O_NOFOLLOW: int # Gnu extension if in C library +O_NOATIME: int # Gnu extension if in C library +if sys.version_info >= (3, 4): + O_PATH: int # Gnu extension if in C library + O_TMPFILE: int # Gnu extension if in C library +O_LARGEFILE: int # Gnu extension if in C library + +curdir: str +pardir: str +sep: str +altsep: str +extsep: str +pathsep: str +defpath: str +linesep: str +devnull: str +name: str + +F_OK: int +R_OK: int +W_OK: int +X_OK: int + +class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): + def copy(self) -> Dict[AnyStr, AnyStr]: ... + def __delitem__(self, key: AnyStr) -> None: ... + def __getitem__(self, key: AnyStr) -> AnyStr: ... + def __setitem__(self, key: AnyStr, value: AnyStr) -> None: ... + def __iter__(self) -> Iterator[AnyStr]: ... + def __len__(self) -> int: ... + +environ: _Environ[str] +if sys.version_info >= (3, 2): + environb: _Environ[bytes] + +if sys.platform != 'win32': + confstr_names: Dict[str, int] + pathconf_names: Dict[str, int] + sysconf_names: Dict[str, int] + + EX_OK: int + EX_USAGE: int + EX_DATAERR: int + EX_NOINPUT: int + EX_NOUSER: int + EX_NOHOST: int + EX_UNAVAILABLE: int + EX_SOFTWARE: int + EX_OSERR: int + EX_OSFILE: int + EX_CANTCREAT: int + EX_IOERR: int + EX_TEMPFAIL: int + EX_PROTOCOL: int + EX_NOPERM: int + EX_CONFIG: int + EX_NOTFOUND: int + +P_NOWAIT: int +P_NOWAITO: int +P_WAIT: int +if sys.platform == 'win32': + P_DETACH: int + P_OVERLAY: int + +# wait()/waitpid() options +if sys.platform != 'win32': + WNOHANG: int # Unix only + WCONTINUED: int # some Unix systems + WUNTRACED: int # Unix only + +TMP_MAX: int # Undocumented, but used by tempfile + +# ----- os classes (structures) ----- +class stat_result: + # For backward compatibility, the return value of stat() is also + # accessible as a tuple of at least 10 integers giving the most important + # (and portable) members of the stat structure, in the order st_mode, + # st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime, + # st_ctime. More items may be added at the end by some implementations. + + st_mode: int # protection bits, + st_ino: int # inode number, + st_dev: int # device, + st_nlink: int # number of hard links, + st_uid: int # user id of owner, + st_gid: int # group id of owner, + st_size: int # size of file, in bytes, + st_atime: float # time of most recent access, + st_mtime: float # time of most recent content modification, + st_ctime: float # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) + st_atime_ns: int # time of most recent access, in nanoseconds + st_mtime_ns: int # time of most recent content modification in nanoseconds + st_ctime_ns: int # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) in nanoseconds + + def __getitem__(self, i: int) -> int: ... + + # not documented + def __init__(self, tuple: Tuple[int, ...]) -> None: ... + + # On some Unix systems (such as Linux), the following attributes may also + # be available: + st_blocks: int # number of blocks allocated for file + st_blksize: int # filesystem blocksize + st_rdev: int # type of device if an inode device + st_flags: int # user defined flags for file + + # On other Unix systems (such as FreeBSD), the following attributes may be + # available (but may be only filled out if root tries to use them): + st_gen: int # file generation number + st_birthtime: int # time of file creation + + # On Mac OS systems, the following attributes may also be available: + st_rsize: int + st_creator: int + st_type: int + +if sys.version_info >= (3, 6): + from builtins import _PathLike as PathLike # See comment in builtins + +_PathType = path._PathType +if sys.version_info >= (3, 3): + _FdOrPathType = Union[int, _PathType] +else: + _FdOrPathType = _PathType + +if sys.version_info >= (3, 6): + class DirEntry(PathLike[AnyStr]): + # This is what the scandir interator yields + # The constructor is hidden + + name: AnyStr + path: AnyStr + def inode(self) -> int: ... + def is_dir(self, *, follow_symlinks: bool = ...) -> bool: ... + def is_file(self, *, follow_symlinks: bool = ...) -> bool: ... + def is_symlink(self) -> bool: ... + def stat(self, *, follow_symlinks: bool = ...) -> stat_result: ... + + def __fspath__(self) -> AnyStr: ... +elif sys.version_info >= (3, 5): + class DirEntry(Generic[AnyStr]): + # This is what the scandir interator yields + # The constructor is hidden + + name: AnyStr + path: AnyStr + def inode(self) -> int: ... + def is_dir(self, *, follow_symlinks: bool = ...) -> bool: ... + def is_file(self, *, follow_symlinks: bool = ...) -> bool: ... + def is_symlink(self) -> bool: ... + def stat(self, *, follow_symlinks: bool = ...) -> stat_result: ... + + +if sys.platform != 'win32': + class statvfs_result: # Unix only + f_bsize: int + f_frsize: int + f_blocks: int + f_bfree: int + f_bavail: int + f_files: int + f_ffree: int + f_favail: int + f_flag: int + f_namemax: int + +# ----- os function stubs ----- +if sys.version_info >= (3, 6): + def fsencode(filename: Union[str, bytes, PathLike]) -> bytes: ... +else: + def fsencode(filename: Union[str, bytes]) -> bytes: ... + +if sys.version_info >= (3, 6): + def fsdecode(filename: Union[str, bytes, PathLike]) -> str: ... +else: + def fsdecode(filename: Union[str, bytes]) -> str: ... + +if sys.version_info >= (3, 6): + @overload + def fspath(path: str) -> str: ... + @overload + def fspath(path: bytes) -> bytes: ... + @overload + def fspath(path: PathLike) -> Any: ... + +def get_exec_path(env: Optional[Mapping[str, str]] = ...) -> List[str]: ... +# NOTE: get_exec_path(): returns List[bytes] when env not None +def getlogin() -> str: ... +def getpid() -> int: ... +def getppid() -> int: ... +def strerror(code: int) -> str: ... +def umask(mask: int) -> int: ... + +if sys.platform != 'win32': + # Unix only + def ctermid() -> str: ... + def getegid() -> int: ... + def geteuid() -> int: ... + def getgid() -> int: ... + if sys.version_info >= (3, 3): + def getgrouplist(user: str, gid: int) -> List[int]: ... + def getgroups() -> List[int]: ... # Unix only, behaves differently on Mac + def initgroups(username: str, gid: int) -> None: ... + def getpgid(pid: int) -> int: ... + def getpgrp() -> int: ... + if sys.version_info >= (3, 3): + def getpriority(which: int, who: int) -> int: ... + def setpriority(which: int, who: int, priority: int) -> None: ... + def getresuid() -> Tuple[int, int, int]: ... + def getresgid() -> Tuple[int, int, int]: ... + def getuid() -> int: ... + def setegid(egid: int) -> None: ... + def seteuid(euid: int) -> None: ... + def setgid(gid: int) -> None: ... + def setgroups(groups: Sequence[int]) -> None: ... + def setpgrp() -> None: ... + def setpgid(pid: int, pgrp: int) -> None: ... + def setregid(rgid: int, egid: int) -> None: ... + def setresgid(rgid: int, egid: int, sgid: int) -> None: ... + def setresuid(ruid: int, euid: int, suid: int) -> None: ... + def setreuid(ruid: int, euid: int) -> None: ... + def getsid(pid: int) -> int: ... + def setsid() -> None: ... + def setuid(uid: int) -> None: ... + if sys.version_info >= (3, 3): + from posix import uname_result + def uname() -> uname_result: ... + else: + def uname() -> Tuple[str, str, str, str, str]: ... + +@overload +def getenv(key: Text) -> Optional[str]: ... +@overload +def getenv(key: Text, default: _T) -> Union[str, _T]: ... +def getenvb(key: bytes, default: bytes = ...) -> bytes: ... +def putenv(key: Union[bytes, Text], value: Union[bytes, Text]) -> None: ... +def unsetenv(key: Union[bytes, Text]) -> None: ... + +# Return IO or TextIO +def fdopen(fd: int, mode: str = ..., buffering: int = ..., encoding: Optional[str] = ..., + errors: str = ..., newline: str = ..., closefd: bool = ...) -> Any: ... +def close(fd: int) -> None: ... +def closerange(fd_low: int, fd_high: int) -> None: ... +def device_encoding(fd: int) -> Optional[str]: ... +def dup(fd: int) -> int: ... +if sys.version_info >= (3, 7): + def dup2(fd: int, fd2: int, inheritable: bool = ...) -> int: ... +elif sys.version_info >= (3, 4): + def dup2(fd: int, fd2: int, inheritable: bool = ...) -> None: ... +else: + def dup2(fd: int, fd2: int) -> None: ... +def fstat(fd: int) -> stat_result: ... +def fsync(fd: int) -> None: ... +def lseek(fd: int, pos: int, how: int) -> int: ... +if sys.version_info >= (3, 3): + def open(file: _PathType, flags: int, mode: int = ..., *, dir_fd: Optional[int] = ...) -> int: ... +else: + def open(file: _PathType, flags: int, mode: int = ...) -> int: ... +def pipe() -> Tuple[int, int]: ... +def read(fd: int, n: int) -> bytes: ... + +if sys.platform != 'win32': + # Unix only + def fchmod(fd: int, mode: int) -> None: ... + def fchown(fd: int, uid: int, gid: int) -> None: ... + def fdatasync(fd: int) -> None: ... # Unix only, not Mac + def fpathconf(fd: int, name: Union[str, int]) -> int: ... + def fstatvfs(fd: int) -> statvfs_result: ... + def ftruncate(fd: int, length: int) -> None: ... + if sys.version_info >= (3, 5): + def get_blocking(fd: int) -> bool: ... + def set_blocking(fd: int, blocking: bool) -> None: ... + def isatty(fd: int) -> bool: ... + if sys.version_info >= (3, 3): + def lockf(__fd: int, __cmd: int, __length: int) -> None: ... + def openpty() -> Tuple[int, int]: ... # some flavors of Unix + if sys.version_info >= (3, 3): + def pipe2(flags: int) -> Tuple[int, int]: ... # some flavors of Unix + def posix_fallocate(fd: int, offset: int, length: int) -> None: ... + def posix_fadvise(fd: int, offset: int, length: int, advice: int) -> None: ... + def pread(fd: int, buffersize: int, offset: int) -> bytes: ... + def pwrite(fd: int, string: bytes, offset: int) -> int: ... + @overload + def sendfile(__out_fd: int, __in_fd: int, offset: Optional[int], count: int) -> int: ... + @overload + def sendfile(__out_fd: int, __in_fd: int, offset: int, count: int, + headers: Sequence[bytes] = ..., trailers: Sequence[bytes] = ..., flags: int = ...) -> int: ... # FreeBSD and Mac OS X only + def readv(fd: int, buffers: Sequence[bytearray]) -> int: ... + def writev(fd: int, buffers: Sequence[bytes]) -> int: ... + +terminal_size = NamedTuple('terminal_size', [('columns', int), ('lines', int)]) +def get_terminal_size(fd: int = ...) -> terminal_size: ... + +if sys.version_info >= (3, 4): + def get_inheritable(fd: int) -> bool: ... + def set_inheritable(fd: int, inheritable: bool) -> None: ... + +if sys.platform != 'win32': + # Unix only + def tcgetpgrp(fd: int) -> int: ... + def tcsetpgrp(fd: int, pg: int) -> None: ... + def ttyname(fd: int) -> str: ... +def write(fd: int, string: bytes) -> int: ... +if sys.version_info >= (3, 3): + def access(path: _FdOrPathType, mode: int, *, dir_fd: Optional[int] = ..., + effective_ids: bool = ..., follow_symlinks: bool = ...) -> bool: ... +else: + def access(path: _PathType, mode: int) -> bool: ... +def chdir(path: _FdOrPathType) -> None: ... +def fchdir(fd: int) -> None: ... +def getcwd() -> str: ... +def getcwdb() -> bytes: ... +if sys.version_info >= (3, 3): + def chmod(path: _FdOrPathType, mode: int, *, dir_fd: Optional[int] = ..., follow_symlinks: bool = ...) -> None: ... + if sys.platform != 'win32': + def chflags(path: _PathType, flags: int, follow_symlinks: bool = ...) -> None: ... # some flavors of Unix + def chown(path: _FdOrPathType, uid: int, gid: int, *, dir_fd: Optional[int] = ..., follow_symlinks: bool = ...) -> None: ... # Unix only +else: + def chmod(path: _PathType, mode: int) -> None: ... + if sys.platform != 'win32': + def chflags(path: _PathType, flags: int) -> None: ... # Some flavors of Unix + def chown(path: _PathType, uid: int, gid: int) -> None: ... # Unix only +if sys.platform != 'win32': + # Unix only + def chroot(path: _PathType) -> None: ... + def lchflags(path: _PathType, flags: int) -> None: ... + def lchmod(path: _PathType, mode: int) -> None: ... + def lchown(path: _PathType, uid: int, gid: int) -> None: ... +if sys.version_info >= (3, 3): + def link(src: _PathType, link_name: _PathType, *, src_dir_fd: Optional[int] = ..., + dst_dir_fd: Optional[int] = ..., follow_symlinks: bool = ...) -> None: ... +else: + def link(src: _PathType, link_name: _PathType) -> None: ... + +if sys.version_info >= (3, 6): + @overload + def listdir(path: Optional[str] = ...) -> List[str]: ... + @overload + def listdir(path: bytes) -> List[bytes]: ... + @overload + def listdir(path: int) -> List[str]: ... + @overload + def listdir(path: PathLike[str]) -> List[str]: ... +elif sys.version_info >= (3, 3): + @overload + def listdir(path: Optional[str] = ...) -> List[str]: ... + @overload + def listdir(path: bytes) -> List[bytes]: ... + @overload + def listdir(path: int) -> List[str]: ... +else: + @overload + def listdir(path: Optional[str] = ...) -> List[str]: ... + @overload + def listdir(path: bytes) -> List[bytes]: ... + +if sys.version_info >= (3, 3): + def lstat(path: _PathType, *, dir_fd: Optional[int] = ...) -> stat_result: ... + def mkdir(path: _PathType, mode: int = ..., *, dir_fd: Optional[int] = ...) -> None: ... + if sys.platform != 'win32': + def mkfifo(path: _PathType, mode: int = ..., *, dir_fd: Optional[int] = ...) -> None: ... # Unix only +else: + def lstat(path: _PathType) -> stat_result: ... + def mkdir(path: _PathType, mode: int = ...) -> None: ... + if sys.platform != 'win32': + def mkfifo(path: _PathType, mode: int = ...) -> None: ... # Unix only +if sys.version_info >= (3, 4): + def makedirs(name: _PathType, mode: int = ..., exist_ok: bool = ...) -> None: ... +else: + def makedirs(path: _PathType, mode: int = ..., exist_ok: bool = ...) -> None: ... +if sys.version_info >= (3, 4): + def mknod(path: _PathType, mode: int = ..., device: int = ..., + *, dir_fd: Optional[int] = ...) -> None: ... +elif sys.version_info >= (3, 3): + def mknod(filename: _PathType, mode: int = ..., device: int = ..., + *, dir_fd: Optional[int] = ...) -> None: ... +else: + def mknod(filename: _PathType, mode: int = ..., device: int = ...) -> None: ... +def major(device: int) -> int: ... +def minor(device: int) -> int: ... +def makedev(major: int, minor: int) -> int: ... +if sys.platform != 'win32': + def pathconf(path: _FdOrPathType, name: Union[str, int]) -> int: ... # Unix only +if sys.version_info >= (3, 6): + def readlink(path: Union[AnyStr, PathLike[AnyStr]], *, dir_fd: Optional[int] = ...) -> AnyStr: ... +elif sys.version_info >= (3, 3): + def readlink(path: AnyStr, *, dir_fd: Optional[int] = ...) -> AnyStr: ... +else: + def readlink(path: AnyStr) -> AnyStr: ... +if sys.version_info >= (3, 3): + def remove(path: _PathType, *, dir_fd: Optional[int] = ...) -> None: ... +else: + def remove(path: _PathType) -> None: ... +if sys.version_info >= (3, 4): + def removedirs(name: _PathType) -> None: ... +else: + def removedirs(path: _PathType) -> None: ... +if sys.version_info >= (3, 3): + def rename(src: _PathType, dst: _PathType, *, + src_dir_fd: Optional[int] = ..., dst_dir_fd: Optional[int] = ...) -> None: ... +else: + def rename(src: _PathType, dst: _PathType) -> None: ... +def renames(old: _PathType, new: _PathType) -> None: ... +if sys.version_info >= (3, 3): + def replace(src: _PathType, dst: _PathType, *, + src_dir_fd: Optional[int] = ..., dst_dir_fd: Optional[int] = ...) -> None: ... + def rmdir(path: _PathType, *, dir_fd: Optional[int] = ...) -> None: ... +else: + def rmdir(path: _PathType) -> None: ... +if sys.version_info >= (3, 7): + class _ScandirIterator(Iterator[DirEntry[AnyStr]], ContextManager[_ScandirIterator[AnyStr]]): + def __next__(self) -> DirEntry[AnyStr]: ... + def close(self) -> None: ... + @overload + def scandir() -> _ScandirIterator[str]: ... + @overload + def scandir(path: int) -> _ScandirIterator[str]: ... + @overload + def scandir(path: Union[AnyStr, PathLike[AnyStr]]) -> _ScandirIterator[AnyStr]: ... +elif sys.version_info >= (3, 6): + class _ScandirIterator(Iterator[DirEntry[AnyStr]], ContextManager[_ScandirIterator[AnyStr]]): + def __next__(self) -> DirEntry[AnyStr]: ... + def close(self) -> None: ... + @overload + def scandir() -> _ScandirIterator[str]: ... + @overload + def scandir(path: Union[AnyStr, PathLike[AnyStr]]) -> _ScandirIterator[AnyStr]: ... +elif sys.version_info >= (3, 5): + @overload + def scandir() -> Iterator[DirEntry[str]]: ... + @overload + def scandir(path: AnyStr) -> Iterator[DirEntry[AnyStr]]: ... +if sys.version_info >= (3, 3): + def stat(path: _FdOrPathType, *, dir_fd: Optional[int] = ..., + follow_symlinks: bool = ...) -> stat_result: ... +else: + def stat(path: _PathType) -> stat_result: ... +if sys.version_info < (3, 7): + @overload + def stat_float_times() -> bool: ... + @overload + def stat_float_times(__newvalue: bool) -> None: ... +if sys.platform != 'win32': + def statvfs(path: _FdOrPathType) -> statvfs_result: ... # Unix only +if sys.version_info >= (3, 3): + def symlink(source: _PathType, link_name: _PathType, + target_is_directory: bool = ..., *, dir_fd: Optional[int] = ...) -> None: ... + if sys.platform != 'win32': + def sync() -> None: ... # Unix only + def truncate(path: _FdOrPathType, length: int) -> None: ... # Unix only up to version 3.4 + def unlink(path: _PathType, *, dir_fd: Optional[int] = ...) -> None: ... + def utime(path: _FdOrPathType, times: Optional[Union[Tuple[int, int], Tuple[float, float]]] = ..., *, + ns: Tuple[int, int] = ..., dir_fd: Optional[int] = ..., + follow_symlinks: bool = ...) -> None: ... +else: + def symlink(source: _PathType, link_name: _PathType, + target_is_directory: bool = ...) -> None: + ... # final argument in Windows only + def unlink(path: _PathType) -> None: ... + def utime(path: _PathType, times: Optional[Tuple[float, float]]) -> None: ... + +if sys.version_info >= (3, 6): + def walk(top: Union[AnyStr, PathLike[AnyStr]], topdown: bool = ..., + onerror: Optional[Callable[[OSError], Any]] = ..., + followlinks: bool = ...) -> Iterator[Tuple[AnyStr, List[AnyStr], + List[AnyStr]]]: ... +else: + def walk(top: AnyStr, topdown: bool = ..., onerror: Optional[Callable[[OSError], Any]] = ..., + followlinks: bool = ...) -> Iterator[Tuple[AnyStr, List[AnyStr], + List[AnyStr]]]: ... +if sys.platform != 'win32' and sys.version_info >= (3, 3): + if sys.version_info >= (3, 7): + @overload + def fwalk(top: Union[str, PathLike[str]] = ..., topdown: bool = ..., + onerror: Optional[Callable] = ..., *, follow_symlinks: bool = ..., + dir_fd: Optional[int] = ...) -> Iterator[Tuple[str, List[str], List[str], int]]: ... + @overload + def fwalk(top: bytes, topdown: bool = ..., + onerror: Optional[Callable] = ..., *, follow_symlinks: bool = ..., + dir_fd: Optional[int] = ...) -> Iterator[Tuple[bytes, List[bytes], List[bytes], int]]: ... + elif sys.version_info >= (3, 6): + def fwalk(top: Union[str, PathLike[str]] = ..., topdown: bool = ..., + onerror: Optional[Callable] = ..., *, follow_symlinks: bool = ..., + dir_fd: Optional[int] = ...) -> Iterator[Tuple[str, List[str], List[str], int]]: ... + else: + def fwalk(top: str = ..., topdown: bool = ..., + onerror: Optional[Callable] = ..., *, follow_symlinks: bool = ..., + dir_fd: Optional[int] = ...) -> Iterator[Tuple[str, List[str], List[str], int]]: ... + def getxattr(path: _FdOrPathType, attribute: _PathType, *, follow_symlinks: bool = ...) -> bytes: ... # Linux only + def listxattr(path: _FdOrPathType, *, follow_symlinks: bool = ...) -> List[str]: ... # Linux only + def removexattr(path: _FdOrPathType, attribute: _PathType, *, follow_symlinks: bool = ...) -> None: ... # Linux only + def setxattr(path: _FdOrPathType, attribute: _PathType, value: bytes, flags: int = ..., *, + follow_symlinks: bool = ...) -> None: ... # Linux only + +def abort() -> NoReturn: ... +# These are defined as execl(file, *args) but the first *arg is mandatory. +def execl(file: _PathType, __arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> NoReturn: ... +def execlp(file: _PathType, __arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> NoReturn: ... + +# These are: execle(file, *args, env) but env is pulled from the last element of the args. +def execle(file: _PathType, __arg0: Union[bytes, Text], *args: Any) -> NoReturn: ... +def execlpe(file: _PathType, __arg0: Union[bytes, Text], *args: Any) -> NoReturn: ... + +# The docs say `args: tuple or list of strings` +# The implementation enforces tuple or list so we can't use Sequence. +_ExecVArgs = Union[Tuple[Union[bytes, Text], ...], List[bytes], List[Text], List[Union[bytes, Text]]] +def execv(path: _PathType, args: _ExecVArgs) -> NoReturn: ... +def execve(path: _FdOrPathType, args: _ExecVArgs, env: Mapping[str, str]) -> NoReturn: ... +def execvp(file: _PathType, args: _ExecVArgs) -> NoReturn: ... +def execvpe(file: _PathType, args: _ExecVArgs, env: Mapping[str, str]) -> NoReturn: ... + +def _exit(n: int) -> NoReturn: ... +def kill(pid: int, sig: int) -> None: ... +if sys.platform != 'win32': + # Unix only + def fork() -> int: ... + def forkpty() -> Tuple[int, int]: ... # some flavors of Unix + def killpg(pgid: int, sig: int) -> None: ... + def nice(increment: int) -> int: ... + def plock(op: int) -> None: ... # ???op is int? + +if sys.version_info >= (3, 0): + class _wrap_close(_TextIOWrapper): + def close(self) -> Optional[int]: ... # type: ignore + def popen(command: str, mode: str = ..., buffering: int = ...) -> _wrap_close: ... +else: + class _wrap_close(IO[Text]): + def close(self) -> Optional[int]: ... + def popen(__cmd: Text, __mode: Text = ..., __bufsize: int = ...) -> _wrap_close: ... + def popen2(__cmd: Text, __mode: Text = ..., __bufsize: int = ...) -> Tuple[IO[Text], IO[Text]]: ... + def popen3(__cmd: Text, __mode: Text = ..., __bufsize: int = ...) -> Tuple[IO[Text], IO[Text], IO[Text]]: ... + def popen4(__cmd: Text, __mode: Text = ..., __bufsize: int = ...) -> Tuple[IO[Text], IO[Text]]: ... + +def spawnl(mode: int, path: _PathType, arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> int: ... +def spawnle(mode: int, path: _PathType, arg0: Union[bytes, Text], + *args: Any) -> int: ... # Imprecise sig +def spawnv(mode: int, path: _PathType, args: List[Union[bytes, Text]]) -> int: ... +def spawnve(mode: int, path: _PathType, args: List[Union[bytes, Text]], + env: Mapping[str, str]) -> int: ... +def system(command: _PathType) -> int: ... +if sys.version_info >= (3, 3): + from posix import times_result + def times() -> times_result: ... +else: + def times() -> Tuple[float, float, float, float, float]: ... +def waitpid(pid: int, options: int) -> Tuple[int, int]: ... + +if sys.platform == 'win32': + def startfile(path: _PathType, operation: Optional[str] = ...) -> None: ... +else: + # Unix only + def spawnlp(mode: int, file: _PathType, arg0: Union[bytes, Text], *args: Union[bytes, Text]) -> int: ... + def spawnlpe(mode: int, file: _PathType, arg0: Union[bytes, Text], *args: Any) -> int: ... # Imprecise signature + def spawnvp(mode: int, file: _PathType, args: List[Union[bytes, Text]]) -> int: ... + def spawnvpe(mode: int, file: _PathType, args: List[Union[bytes, Text]], env: Mapping[str, str]) -> int: ... + def wait() -> Tuple[int, int]: ... # Unix only + if sys.version_info >= (3, 3): + from posix import waitid_result + def waitid(idtype: int, ident: int, options: int) -> waitid_result: ... + def wait3(options: int) -> Tuple[int, int, Any]: ... + def wait4(pid: int, options: int) -> Tuple[int, int, Any]: ... + def WCOREDUMP(status: int) -> bool: ... + def WIFCONTINUED(status: int) -> bool: ... + def WIFSTOPPED(status: int) -> bool: ... + def WIFSIGNALED(status: int) -> bool: ... + def WIFEXITED(status: int) -> bool: ... + def WEXITSTATUS(status: int) -> int: ... + def WSTOPSIG(status: int) -> int: ... + def WTERMSIG(status: int) -> int: ... + +if sys.platform != 'win32' and sys.version_info >= (3, 3): + from posix import sched_param + def sched_get_priority_min(policy: int) -> int: ... # some flavors of Unix + def sched_get_priority_max(policy: int) -> int: ... # some flavors of Unix + def sched_setscheduler(pid: int, policy: int, param: sched_param) -> None: ... # some flavors of Unix + def sched_getscheduler(pid: int) -> int: ... # some flavors of Unix + def sched_setparam(pid: int, param: sched_param) -> None: ... # some flavors of Unix + def sched_getparam(pid: int) -> sched_param: ... # some flavors of Unix + def sched_rr_get_interval(pid: int) -> float: ... # some flavors of Unix + def sched_yield() -> None: ... # some flavors of Unix + def sched_setaffinity(pid: int, mask: Iterable[int]) -> None: ... # some flavors of Unix + def sched_getaffinity(pid: int) -> Set[int]: ... # some flavors of Unix + +if sys.version_info >= (3, 4): + def cpu_count() -> Optional[int]: ... +if sys.platform != 'win32': + # Unix only + def confstr(name: Union[str, int]) -> Optional[str]: ... + def getloadavg() -> Tuple[float, float, float]: ... + def sysconf(name: Union[str, int]) -> int: ... +if sys.version_info >= (3, 6): + def getrandom(size: int, flags: int = ...) -> bytes: ... + def urandom(size: int) -> bytes: ... +else: + def urandom(n: int) -> bytes: ... + +if sys.version_info >= (3, 7): + def register_at_fork(func: Callable[..., object], when: str) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/os/path.pyi b/client/typeshed-fallback/stdlib/3/os/path.pyi new file mode 100644 index 000000000..09663afa4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/os/path.pyi @@ -0,0 +1,177 @@ +# NB: path.pyi and stdlib/2 and stdlib/3 must remain consistent! +# Stubs for os.path +# Ron Murawski + +import os +import sys +from typing import ( + overload, List, Any, AnyStr, Sequence, Tuple, BinaryIO, TextIO, + TypeVar, Union, Text, Callable, Optional +) + +_T = TypeVar('_T') + +if sys.version_info >= (3, 6): + from builtins import _PathLike + _PathType = Union[bytes, Text, _PathLike] + _StrPath = Union[Text, _PathLike[Text]] + _BytesPath = Union[bytes, _PathLike[bytes]] +else: + _PathType = Union[bytes, Text] + _StrPath = Text + _BytesPath = bytes + +# ----- os.path variables ----- +supports_unicode_filenames: bool +# aliases (also in os) +curdir: str +pardir: str +sep: str +altsep: str +extsep: str +pathsep: str +defpath: str +devnull: str + +# ----- os.path function stubs ----- +if sys.version_info >= (3, 6): + # Overloads are necessary to work around python/mypy#3644. + @overload + def abspath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def abspath(path: AnyStr) -> AnyStr: ... + @overload + def basename(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def basename(path: AnyStr) -> AnyStr: ... + @overload + def dirname(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def dirname(path: AnyStr) -> AnyStr: ... + @overload + def expanduser(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expanduser(path: AnyStr) -> AnyStr: ... + @overload + def expandvars(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def expandvars(path: AnyStr) -> AnyStr: ... + @overload + def normcase(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normcase(path: AnyStr) -> AnyStr: ... + @overload + def normpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + @overload + def realpath(path: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(path: AnyStr) -> AnyStr: ... + else: + @overload + def realpath(filename: _PathLike[AnyStr]) -> AnyStr: ... + @overload + def realpath(filename: AnyStr) -> AnyStr: ... + +else: + def abspath(path: AnyStr) -> AnyStr: ... + def basename(path: AnyStr) -> AnyStr: ... + def dirname(path: AnyStr) -> AnyStr: ... + def expanduser(path: AnyStr) -> AnyStr: ... + def expandvars(path: AnyStr) -> AnyStr: ... + def normcase(path: AnyStr) -> AnyStr: ... + def normpath(path: AnyStr) -> AnyStr: ... + if sys.platform == 'win32': + def realpath(path: AnyStr) -> AnyStr: ... + else: + def realpath(filename: AnyStr) -> AnyStr: ... + +if sys.version_info >= (3, 6): + # In reality it returns str for sequences of _StrPath and bytes for sequences + # of _BytesPath, but mypy does not accept such a signature. + def commonpath(paths: Sequence[_PathType]) -> Any: ... +elif sys.version_info >= (3, 5): + def commonpath(paths: Sequence[AnyStr]) -> AnyStr: ... + +# NOTE: Empty lists results in '' (str) regardless of contained type. +# Also, in Python 2 mixed sequences of Text and bytes results in either Text or bytes +# So, fall back to Any +def commonprefix(list: Sequence[_PathType]) -> Any: ... + +if sys.version_info >= (3, 3): + def exists(path: Union[_PathType, int]) -> bool: ... +else: + def exists(path: _PathType) -> bool: ... +def lexists(path: _PathType) -> bool: ... + +# These return float if os.stat_float_times() == True, +# but int is a subclass of float. +def getatime(path: _PathType) -> float: ... +def getmtime(path: _PathType) -> float: ... +def getctime(path: _PathType) -> float: ... + +def getsize(path: _PathType) -> int: ... +def isabs(path: _PathType) -> bool: ... +def isfile(path: _PathType) -> bool: ... +def isdir(path: _PathType) -> bool: ... +def islink(path: _PathType) -> bool: ... +def ismount(path: _PathType) -> bool: ... + +if sys.version_info < (3, 0): + # Make sure signatures are disjunct, and allow combinations of bytes and unicode. + # (Since Python 2 allows that, too) + # Note that e.g. os.path.join("a", "b", "c", "d", u"e") will still result in + # a type error. + @overload + def join(__p1: bytes, *p: bytes) -> bytes: ... + @overload + def join(__p1: bytes, __p2: bytes, __p3: bytes, __p4: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: bytes, __p2: bytes, __p3: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: bytes, __p2: Text, *p: _PathType) -> Text: ... + @overload + def join(__p1: Text, *p: _PathType) -> Text: ... +elif sys.version_info >= (3, 6): + # Mypy complains that the signatures overlap (same for relpath below), but things seem to behave correctly anyway. + @overload + def join(path: _StrPath, *paths: _StrPath) -> Text: ... + @overload + def join(path: _BytesPath, *paths: _BytesPath) -> bytes: ... +else: + def join(path: AnyStr, *paths: AnyStr) -> AnyStr: ... + +@overload +def relpath(path: _BytesPath, start: Optional[_BytesPath] = ...) -> bytes: ... +@overload +def relpath(path: _StrPath, start: Optional[_StrPath] = ...) -> Text: ... + +def samefile(path1: _PathType, path2: _PathType) -> bool: ... +def sameopenfile(fp1: int, fp2: int) -> bool: ... +def samestat(stat1: os.stat_result, stat2: os.stat_result) -> bool: ... + +if sys.version_info >= (3, 6): + @overload + def split(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def split(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(path: _PathLike[AnyStr]) -> Tuple[AnyStr, AnyStr]: ... + @overload + def splitext(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +else: + def split(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitdrive(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + def splitext(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... + +if sys.platform == 'win32': + def splitunc(path: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + +if sys.version_info < (3,): + def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/pathlib.pyi b/client/typeshed-fallback/stdlib/3/pathlib.pyi new file mode 100644 index 000000000..7ec0d24f3 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/pathlib.pyi @@ -0,0 +1,122 @@ +from typing import Any, Generator, IO, Optional, Sequence, Tuple, Type, TypeVar, Union, List +from types import TracebackType +import os +import sys + +_P = TypeVar('_P', bound='PurePath') + +if sys.version_info >= (3, 6): + _PurePathBase = os.PathLike[str] +else: + _PurePathBase = object + +class PurePath(_PurePathBase): + parts = ... # type: Tuple[str, ...] + drive = ... # type: str + root = ... # type: str + anchor = ... # type: str + name = ... # type: str + suffix = ... # type: str + suffixes = ... # type: List[str] + stem = ... # type: str + if sys.version_info < (3, 5): + def __init__(self, *pathsegments: str) -> None: ... + elif sys.version_info < (3, 6): + def __new__(cls: Type[_P], *args: Union[str, PurePath]) -> _P: ... + else: + def __new__(cls: Type[_P], *args: Union[str, os.PathLike[str]]) -> _P: ... + def __hash__(self) -> int: ... + def __lt__(self, other: PurePath) -> bool: ... + def __le__(self, other: PurePath) -> bool: ... + def __gt__(self, other: PurePath) -> bool: ... + def __ge__(self, other: PurePath) -> bool: ... + def __truediv__(self: _P, key: Union[str, PurePath]) -> _P: ... + if sys.version_info < (3,): + def __div__(self: _P, key: Union[str, PurePath]) -> _P: ... + def __bytes__(self) -> bytes: ... + def as_posix(self) -> str: ... + def as_uri(self) -> str: ... + def is_absolute(self) -> bool: ... + def is_reserved(self) -> bool: ... + def match(self, path_pattern: str) -> bool: ... + def relative_to(self: _P, *other: Union[str, PurePath]) -> _P: ... + def with_name(self: _P, name: str) -> _P: ... + def with_suffix(self: _P, suffix: str) -> _P: ... + def joinpath(self: _P, *other: Union[str, PurePath]) -> _P: ... + + @property + def parents(self: _P) -> Sequence[_P]: ... + @property + def parent(self: _P) -> _P: ... + +class PurePosixPath(PurePath): ... +class PureWindowsPath(PurePath): ... + +class Path(PurePath): + def __enter__(self) -> Path: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType]) -> Optional[bool]: ... + @classmethod + def cwd(cls: Type[_P]) -> _P: ... + def stat(self) -> os.stat_result: ... + def chmod(self, mode: int) -> None: ... + def exists(self) -> bool: ... + def glob(self, pattern: str) -> Generator[Path, None, None]: ... + def group(self) -> str: ... + def is_dir(self) -> bool: ... + def is_file(self) -> bool: ... + def is_symlink(self) -> bool: ... + def is_socket(self) -> bool: ... + def is_fifo(self) -> bool: ... + def is_block_device(self) -> bool: ... + def is_char_device(self) -> bool: ... + def iterdir(self) -> Generator[Path, None, None]: ... + def lchmod(self, mode: int) -> None: ... + def lstat(self) -> os.stat_result: ... + if sys.version_info < (3, 5): + def mkdir(self, mode: int = ..., + parents: bool = ...) -> None: ... + else: + def mkdir(self, mode: int = ..., parents: bool = ..., + exist_ok: bool = ...) -> None: ... + def open(self, mode: str = ..., buffering: int = ..., + encoding: Optional[str] = ..., errors: Optional[str] = ..., + newline: Optional[str] = ...) -> IO[Any]: ... + def owner(self) -> str: ... + def rename(self, target: Union[str, PurePath]) -> None: ... + def replace(self, target: Union[str, PurePath]) -> None: ... + if sys.version_info < (3, 6): + def resolve(self: _P) -> _P: ... + else: + def resolve(self: _P, strict: bool = ...) -> _P: ... + def rglob(self, pattern: str) -> Generator[Path, None, None]: ... + def rmdir(self) -> None: ... + def symlink_to(self, target: Union[str, Path], + target_is_directory: bool = ...) -> None: ... + def touch(self, mode: int = ..., exist_ok: bool = ...) -> None: ... + def unlink(self) -> None: ... + + if sys.version_info >= (3, 5): + @classmethod + def home(cls: Type[_P]) -> _P: ... + if sys.version_info < (3, 6): + def __new__(cls: Type[_P], *args: Union[str, PurePath], + **kwargs: Any) -> _P: ... + else: + def __new__(cls: Type[_P], *args: Union[str, os.PathLike[str]], + **kwargs: Any) -> _P: ... + + def absolute(self: _P) -> _P: ... + def expanduser(self: _P) -> _P: ... + def read_bytes(self) -> bytes: ... + def read_text(self, encoding: Optional[str] = ..., + errors: Optional[str] = ...) -> str: ... + def samefile(self, other_path: Union[str, bytes, int, Path]) -> bool: ... + def write_bytes(self, data: bytes) -> int: ... + def write_text(self, data: str, encoding: Optional[str] = ..., + errors: Optional[str] = ...) -> int: ... + + +class PosixPath(Path, PurePosixPath): ... +class WindowsPath(Path, PureWindowsPath): ... diff --git a/client/typeshed-fallback/stdlib/3/pipes.pyi b/client/typeshed-fallback/stdlib/3/pipes.pyi new file mode 100644 index 000000000..658373e4c --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/pipes.pyi @@ -0,0 +1,19 @@ +# Stubs for pipes + +# Based on http://docs.python.org/3.5/library/pipes.html + +import os + +class Template: + def __init__(self) -> None: ... + def reset(self) -> None: ... + def clone(self) -> Template: ... + def debug(self, flag: bool) -> None: ... + def append(self, cmd: str, kind: str) -> None: ... + def prepend(self, cmd: str, kind: str) -> None: ... + def open(self, file: str, rw: str) -> os._wrap_close: ... + def copy(self, file: str, rw: str) -> os._wrap_close: ... + +# Not documented, but widely used. +# Documented as shlex.quote since 3.3. +def quote(s: str) -> str: ... diff --git a/client/typeshed-fallback/stdlib/3/platform.pyi b/client/typeshed-fallback/stdlib/3/platform.pyi new file mode 100644 index 000000000..728e259fe --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/platform.pyi @@ -0,0 +1,34 @@ +# Stubs for platform (Python 3.5) + +from os import devnull as DEV_NULL +from os import popen +from typing import Tuple, NamedTuple + +def libc_ver(executable: str = ..., lib: str = ..., version: str = ..., chunksize: int = ...) -> Tuple[str, str]: ... +def linux_distribution(distname: str = ..., version: str = ..., id: str = ..., supported_dists: Tuple[str, ...] = ..., full_distribution_name: bool = ...) -> Tuple[str, str, str]: ... +def dist(distname: str = ..., version: str = ..., id: str = ..., supported_dists: Tuple[str, ...] = ...) -> Tuple[str, str, str]: ... +def win32_ver(release: str = ..., version: str = ..., csd: str = ..., ptype: str = ...) -> Tuple[str, str, str, str]: ... +def mac_ver(release: str = ..., versioninfo: Tuple[str, str, str] = ..., machine: str = ...) -> Tuple[str, Tuple[str, str, str], str]: ... +def java_ver(release: str = ..., vendor: str = ..., vminfo: Tuple[str, str, str] = ..., osinfo: Tuple[str, str, str] = ...) -> Tuple[str, str, Tuple[str, str, str], Tuple[str, str, str]]: ... +def system_alias(system: str, release: str, version: str) -> Tuple[str, str, str]: ... +def architecture(executable: str = ..., bits: str = ..., linkage: str = ...) -> Tuple[str, str]: ... + +uname_result = NamedTuple('uname_result', [('system', str), ('node', str), ('release', str), ('version', str), ('machine', str), ('processor', str)]) + +def uname() -> uname_result: ... +def system() -> str: ... +def node() -> str: ... +def release() -> str: ... +def version() -> str: ... +def machine() -> str: ... +def processor() -> str: ... + +def python_implementation() -> str: ... +def python_version() -> str: ... +def python_version_tuple() -> Tuple[str, str, str]: ... +def python_branch() -> str: ... +def python_revision() -> str: ... +def python_build() -> Tuple[str, str]: ... +def python_compiler() -> str: ... + +def platform(aliased: bool = ..., terse: bool = ...) -> str: ... diff --git a/client/typeshed-fallback/stdlib/3/posix.pyi b/client/typeshed-fallback/stdlib/3/posix.pyi new file mode 100644 index 000000000..6902e5f23 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/posix.pyi @@ -0,0 +1,112 @@ +# Stubs for posix + +# NOTE: These are incomplete! + +import sys +from typing import NamedTuple, Tuple + +from os import stat_result as stat_result + +uname_result = NamedTuple('uname_result', [ + ('sysname', str), + ('nodename', str), + ('release', str), + ('version', str), + ('machine', str), +]) + +times_result = NamedTuple('times_result', [ + ('user', float), + ('system', float), + ('children_user', float), + ('children_system', float), + ('elapsed', float), +]) + +waitid_result = NamedTuple('waitid_result', [ + ('si_pid', int), + ('si_uid', int), + ('si_signo', int), + ('si_status', int), + ('si_code', int), +]) + +sched_param = NamedTuple('sched_param', [ + ('sched_priority', int), +]) + + +EX_CANTCREAT: int +EX_CONFIG: int +EX_DATAERR: int +EX_IOERR: int +EX_NOHOST: int +EX_NOINPUT: int +EX_NOPERM: int +EX_NOTFOUND: int +EX_NOUSER: int +EX_OK: int +EX_OSERR: int +EX_OSFILE: int +EX_PROTOCOL: int +EX_SOFTWARE: int +EX_TEMPFAIL: int +EX_UNAVAILABLE: int +EX_USAGE: int + +F_OK: int +R_OK: int +W_OK: int +X_OK: int + +if sys.version_info >= (3, 6): + GRND_NONBLOCK: int + GRND_RANDOM: int +NGROUPS_MAX: int + +O_APPEND: int +if sys.version_info >= (3, 4): + O_ACCMODE: int +O_ASYNC: int +O_CREAT: int +O_DIRECT: int +O_DIRECTORY: int +O_DSYNC: int +O_EXCL: int +O_LARGEFILE: int +O_NDELAY: int +O_NOATIME: int +O_NOCTTY: int +O_NOFOLLOW: int +O_NONBLOCK: int +O_RDONLY: int +O_RDWR: int +O_RSYNC: int +O_SYNC: int +O_TRUNC: int +O_WRONLY: int + +ST_APPEND: int +ST_MANDLOCK: int +ST_NOATIME: int +ST_NODEV: int +ST_NODIRATIME: int +ST_NOEXEC: int +ST_NOSUID: int +ST_RDONLY: int +ST_RELATIME: int +ST_SYNCHRONOUS: int +ST_WRITE: int + +TMP_MAX: int +WCONTINUED: int +WCOREDUMP: int +WEXITSTATUS: int +WIFCONTINUED: int +WIFEXITED: int +WIFSIGNALED: int +WIFSTOPPED: int +WNOHANG: int +WSTOPSIG: int +WTERMSIG: int +WUNTRACED: int diff --git a/client/typeshed-fallback/stdlib/3/queue.pyi b/client/typeshed-fallback/stdlib/3/queue.pyi new file mode 100644 index 000000000..1eb7360fa --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/queue.pyi @@ -0,0 +1,30 @@ +# Stubs for queue + +# NOTE: These are incomplete! + +from typing import Any, TypeVar, Generic, Optional + +_T = TypeVar('_T') + +class Empty(Exception): ... +class Full(Exception): ... + +class Queue(Generic[_T]): + maxsize = ... # type: int + def __init__(self, maxsize: int = ...) -> None: ... + def _init(self, maxsize: int) -> None: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def get(self, block: bool = ..., timeout: Optional[float] = ...) -> _T: ... + def get_nowait(self) -> _T: ... + def _get(self) -> _T: ... + def put(self, item: _T, block: bool = ..., timeout: Optional[float] = ...) -> None: ... + def put_nowait(self, item: _T) -> None: ... + def _put(self, item: _T) -> None: ... + def join(self) -> None: ... + def qsize(self) -> int: ... + def _qsize(self) -> int: ... + def task_done(self) -> None: ... + +class PriorityQueue(Queue[_T]): ... +class LifoQueue(Queue[_T]): ... diff --git a/client/typeshed-fallback/stdlib/3/random.pyi b/client/typeshed-fallback/stdlib/3/random.pyi new file mode 100644 index 000000000..35ee63488 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/random.pyi @@ -0,0 +1,71 @@ +# Stubs for random +# Ron Murawski +# Updated by Jukka Lehtosalo + +# based on http://docs.python.org/3.2/library/random.html + +# ----- random classes ----- + +import _random +import sys +from typing import ( + Any, TypeVar, Sequence, List, Callable, AbstractSet, Union, Optional +) + +_T = TypeVar('_T') + +class Random(_random.Random): + def __init__(self, x: Any = ...) -> None: ... + def seed(self, a: Any = ..., version: int = ...) -> None: ... + def getstate(self) -> tuple: ... + def setstate(self, state: tuple) -> None: ... + def getrandbits(self, k: int) -> int: ... + def randrange(self, start: int, stop: Union[int, None] = ..., step: int = ...) -> int: ... + def randint(self, a: int, b: int) -> int: ... + def choice(self, seq: Sequence[_T]) -> _T: ... + if sys.version_info >= (3, 6): + def choices(self, population: Sequence[_T], weights: Optional[Sequence[float]] = ..., *, cum_weights: Optional[Sequence[float]] = ..., k: int = ...) -> List[_T]: ... + def shuffle(self, x: List[Any], random: Union[Callable[[], float], None] = ...) -> None: ... + def sample(self, population: Union[Sequence[_T], AbstractSet[_T]], k: int) -> List[_T]: ... + def random(self) -> float: ... + def uniform(self, a: float, b: float) -> float: ... + def triangular(self, low: float = ..., high: float = ..., mode: float = ...) -> float: ... + def betavariate(self, alpha: float, beta: float) -> float: ... + def expovariate(self, lambd: float) -> float: ... + def gammavariate(self, alpha: float, beta: float) -> float: ... + def gauss(self, mu: float, sigma: float) -> float: ... + def lognormvariate(self, mu: float, sigma: float) -> float: ... + def normalvariate(self, mu: float, sigma: float) -> float: ... + def vonmisesvariate(self, mu: float, kappa: float) -> float: ... + def paretovariate(self, alpha: float) -> float: ... + def weibullvariate(self, alpha: float, beta: float) -> float: ... + +# SystemRandom is not implemented for all OS's; good on Windows & Linux +class SystemRandom(Random): + ... + +# ----- random function stubs ----- +def seed(a: Any = ..., version: int = ...) -> None: ... +def getstate() -> object: ... +def setstate(state: object) -> None: ... +def getrandbits(k: int) -> int: ... +def randrange(start: int, stop: Union[None, int] = ..., step: int = ...) -> int: ... +def randint(a: int, b: int) -> int: ... +def choice(seq: Sequence[_T]) -> _T: ... +if sys.version_info >= (3, 6): + def choices(population: Sequence[_T], weights: Optional[Sequence[float]] = ..., *, cum_weights: Optional[Sequence[float]] = ..., k: int = ...) -> List[_T]: ... +def shuffle(x: List[Any], random: Union[Callable[[], float], None] = ...) -> None: ... +def sample(population: Union[Sequence[_T], AbstractSet[_T]], k: int) -> List[_T]: ... +def random() -> float: ... +def uniform(a: float, b: float) -> float: ... +def triangular(low: float = ..., high: float = ..., + mode: float = ...) -> float: ... +def betavariate(alpha: float, beta: float) -> float: ... +def expovariate(lambd: float) -> float: ... +def gammavariate(alpha: float, beta: float) -> float: ... +def gauss(mu: float, sigma: float) -> float: ... +def lognormvariate(mu: float, sigma: float) -> float: ... +def normalvariate(mu: float, sigma: float) -> float: ... +def vonmisesvariate(mu: float, kappa: float) -> float: ... +def paretovariate(alpha: float) -> float: ... +def weibullvariate(alpha: float, beta: float) -> float: ... diff --git a/client/typeshed-fallback/stdlib/3/re.pyi b/client/typeshed-fallback/stdlib/3/re.pyi new file mode 100644 index 000000000..942f9bf6b --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/re.pyi @@ -0,0 +1,151 @@ +# Stubs for re +# Ron Murawski +# 'bytes' support added by Jukka Lehtosalo + +# based on: http://docs.python.org/3.2/library/re.html +# and http://hg.python.org/cpython/file/618ea5612e83/Lib/re.py + +import sys +from typing import ( + List, Iterator, overload, Callable, Tuple, Sequence, Dict, + Generic, AnyStr, Match, Pattern, Any, Optional, Union +) + +# ----- re variables and constants ----- +if sys.version_info >= (3, 6): + import enum + class RegexFlag(enum.IntFlag): + A = 0 + ASCII = 0 + DEBUG = 0 + I = 0 + IGNORECASE = 0 + L = 0 + LOCALE = 0 + M = 0 + MULTILINE = 0 + S = 0 + DOTALL = 0 + X = 0 + VERBOSE = 0 + U = 0 + UNICODE = 0 + T = 0 + TEMPLATE = 0 + + A = RegexFlag.A + ASCII = RegexFlag.ASCII + DEBUG = RegexFlag.DEBUG + I = RegexFlag.I + IGNORECASE = RegexFlag.IGNORECASE + L = RegexFlag.L + LOCALE = RegexFlag.LOCALE + M = RegexFlag.M + MULTILINE = RegexFlag.MULTILINE + S = RegexFlag.S + DOTALL = RegexFlag.DOTALL + X = RegexFlag.X + VERBOSE = RegexFlag.VERBOSE + U = RegexFlag.U + UNICODE = RegexFlag.UNICODE + T = RegexFlag.T + TEMPLATE = RegexFlag.TEMPLATE + _FlagsType = Union[int, RegexFlag] +else: + A = 0 + ASCII = 0 + DEBUG = 0 + I = 0 + IGNORECASE = 0 + L = 0 + LOCALE = 0 + M = 0 + MULTILINE = 0 + S = 0 + DOTALL = 0 + X = 0 + VERBOSE = 0 + U = 0 + UNICODE = 0 + T = 0 + TEMPLATE = 0 + _FlagsType = int + +class error(Exception): ... + +@overload +def compile(pattern: AnyStr, flags: _FlagsType = ...) -> Pattern[AnyStr]: ... +@overload +def compile(pattern: Pattern[AnyStr], flags: _FlagsType = ...) -> Pattern[AnyStr]: ... + +@overload +def search(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Optional[Match[AnyStr]]: ... +@overload +def search(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Optional[Match[AnyStr]]: ... + +@overload +def match(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Optional[Match[AnyStr]]: ... +@overload +def match(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Optional[Match[AnyStr]]: ... + +# New in Python 3.4 +@overload +def fullmatch(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> Optional[Match[AnyStr]]: ... +@overload +def fullmatch(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> Optional[Match[AnyStr]]: ... + +@overload +def split(pattern: AnyStr, string: AnyStr, + maxsplit: int = ..., flags: _FlagsType = ...) -> List[AnyStr]: ... +@overload +def split(pattern: Pattern[AnyStr], string: AnyStr, + maxsplit: int = ..., flags: _FlagsType = ...) -> List[AnyStr]: ... + +@overload +def findall(pattern: AnyStr, string: AnyStr, flags: _FlagsType = ...) -> List[Any]: ... +@overload +def findall(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType = ...) -> List[Any]: ... + +# Return an iterator yielding match objects over all non-overlapping matches +# for the RE pattern in string. The string is scanned left-to-right, and +# matches are returned in the order found. Empty matches are included in the +# result unless they touch the beginning of another match. +@overload +def finditer(pattern: AnyStr, string: AnyStr, + flags: _FlagsType = ...) -> Iterator[Match[AnyStr]]: ... +@overload +def finditer(pattern: Pattern[AnyStr], string: AnyStr, + flags: _FlagsType = ...) -> Iterator[Match[AnyStr]]: ... + +@overload +def sub(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ..., + flags: _FlagsType = ...) -> AnyStr: ... +@overload +def sub(pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, count: int = ..., flags: _FlagsType = ...) -> AnyStr: ... +@overload +def sub(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int = ..., + flags: _FlagsType = ...) -> AnyStr: ... +@overload +def sub(pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, count: int = ..., flags: _FlagsType = ...) -> AnyStr: ... + +@overload +def subn(pattern: AnyStr, repl: AnyStr, string: AnyStr, count: int = ..., + flags: _FlagsType = ...) -> Tuple[AnyStr, int]: ... +@overload +def subn(pattern: AnyStr, repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, count: int = ..., + flags: _FlagsType = ...) -> Tuple[AnyStr, int]: ... +@overload +def subn(pattern: Pattern[AnyStr], repl: AnyStr, string: AnyStr, count: int = ..., + flags: _FlagsType = ...) -> Tuple[AnyStr, int]: ... +@overload +def subn(pattern: Pattern[AnyStr], repl: Callable[[Match[AnyStr]], AnyStr], + string: AnyStr, count: int = ..., + flags: _FlagsType = ...) -> Tuple[AnyStr, int]: ... + +def escape(string: AnyStr) -> AnyStr: ... + +def purge() -> None: ... +def template(pattern: Union[AnyStr, Pattern[AnyStr]], flags: _FlagsType = ...) -> Pattern[AnyStr]: ... diff --git a/client/typeshed-fallback/stdlib/3/reprlib.pyi b/client/typeshed-fallback/stdlib/3/reprlib.pyi new file mode 100644 index 000000000..462251875 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/reprlib.pyi @@ -0,0 +1,37 @@ +# Stubs for reprlib (Python 3) + +from array import array +from typing import Any, Callable, Deque, Dict, FrozenSet, List, Set, Tuple + +_ReprFunc = Callable[[Any], str] + +def recursive_repr(fillvalue: str = ...) -> Callable[[_ReprFunc], _ReprFunc]: ... + +class Repr: + maxlevel: int + maxdict: int + maxlist: int + maxtuple: int + maxset: int + maxfrozenset: int + maxdeque: int + maxarray: int + maxlong: int + maxstring: int + maxother: int + def __init__(self) -> None: ... + def repr(self, x: Any) -> str: ... + def repr1(self, x: Any, level: int) -> str: ... + def repr_tuple(self, x: Tuple[Any, ...], level: int) -> str: ... + def repr_list(self, x: List[Any], level: int) -> str: ... + def repr_array(self, x: array, level: int) -> str: ... + def repr_set(self, x: Set[Any], level: int) -> str: ... + def repr_frozenset(self, x: FrozenSet[Any], level: int) -> str: ... + def repr_deque(self, x: Deque[Any], level: int) -> str: ... + def repr_dict(self, x: Dict[Any, Any], level: int) -> str: ... + def repr_str(self, x: str, level: int) -> str: ... + def repr_int(self, x: int, level: int) -> str: ... + def repr_instance(self, x: Any, level: int) -> str: ... + +aRepr: Repr +def repr(x: object) -> str: ... diff --git a/client/typeshed-fallback/stdlib/3/resource.pyi b/client/typeshed-fallback/stdlib/3/resource.pyi new file mode 100644 index 000000000..b4c74d620 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/resource.pyi @@ -0,0 +1,42 @@ +# Stubs for resource + +# NOTE: These are incomplete! + +from typing import Tuple, Optional, NamedTuple + +RLIMIT_AS = ... # type: int +RLIMIT_CORE = ... # type: int +RLIMIT_CPU = ... # type: int +RLIMIT_DATA = ... # type: int +RLIMIT_FSIZE = ... # type: int +RLIMIT_MEMLOCK = ... # type: int +RLIMIT_MSGQUEUE = ... # type: int +RLIMIT_NICE = ... # type: int +RLIMIT_NOFILE = ... # type: int +RLIMIT_NPROC = ... # type: int +RLIMIT_OFILE = ... # type: int +RLIMIT_RSS = ... # type: int +RLIMIT_RTPRIO = ... # type: int +RLIMIT_RTTIME = ... # type: int +RLIMIT_SIGPENDING = ... # type: int +RLIMIT_STACK = ... # type: int +RLIM_INFINITY = ... # type: int +RUSAGE_CHILDREN = ... # type: int +RUSAGE_SELF = ... # type: int +RUSAGE_THREAD = ... # type: int + +_RUsage = NamedTuple('_RUsage', [('ru_utime', float), ('ru_stime', float), ('ru_maxrss', int), + ('ru_ixrss', int), ('ru_idrss', int), ('ru_isrss', int), + ('ru_minflt', int), ('ru_majflt', int), ('ru_nswap', int), + ('ru_inblock', int), ('ru_oublock', int), ('ru_msgsnd', int), + ('ru_msgrcv', int), ('ru_nsignals', int), ('ru_nvcsw', int), + ('ru_nivcsw', int)]) + +def getpagesize() -> int: ... +def getrlimit(resource: int) -> Tuple[int, int]: ... +def getrusage(who: int) -> _RUsage: ... +def prlimit(pid: int, resource: int, limits: Optional[Tuple[int, int]]) -> Tuple[int, int]: ... +def setrlimit(resource: int, limits: Tuple[int, int]) -> None: ... + +# NOTE: This is an alias of OSError in Python 3.3. +class error(Exception): ... diff --git a/client/typeshed-fallback/stdlib/3/runpy.pyi b/client/typeshed-fallback/stdlib/3/runpy.pyi new file mode 100644 index 000000000..654c53c8e --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/runpy.pyi @@ -0,0 +1,23 @@ +from types import ModuleType +from typing import Dict, Optional, Any + +class _TempModule: + mod_name: str = ... + module: ModuleType = ... + def __init__(self, mod_name): ... + def __enter__(self): ... + def __exit__(self, *args): ... + +class _ModifiedArgv0: + value: Any = ... + def __init__(self, value): ... + def __enter__(self): ... + def __exit__(self, *args): ... + +def run_module(mod_name: str, + init_globals: Optional[Dict[str, Any]] = ..., + run_name: Optional[str] = ..., + alter_sys: bool = ...): ... +def run_path(path_name: str, + init_globals: Optional[Dict[str, Any]] = ..., + run_name: str = ...): ... diff --git a/client/typeshed-fallback/stdlib/3/selectors.pyi b/client/typeshed-fallback/stdlib/3/selectors.pyi new file mode 100644 index 000000000..38f49fe38 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/selectors.pyi @@ -0,0 +1,90 @@ +# Stubs for selector +# See https://docs.python.org/3/library/selectors.html + +from typing import Any, List, NamedTuple, Mapping, Tuple, Optional, Union +from abc import ABCMeta, abstractmethod +import socket + + +# Type aliases added mainly to preserve some context +# +# See https://github.com/python/typeshed/issues/482 +# for details regarding how _FileObject is typed. +_FileObject = Union[int, socket.socket] +_FileDescriptor = int +_EventMask = int + + +EVENT_READ = ... # type: _EventMask +EVENT_WRITE = ... # type: _EventMask + + +SelectorKey = NamedTuple('SelectorKey', [ + ('fileobj', _FileObject), + ('fd', _FileDescriptor), + ('events', _EventMask), + ('data', Any) +]) + + +class BaseSelector(metaclass=ABCMeta): + @abstractmethod + def register(self, fileobj: _FileObject, events: _EventMask, data: Any = ...) -> SelectorKey: ... + + @abstractmethod + def unregister(self, fileobj: _FileObject) -> SelectorKey: ... + + def modify(self, fileobj: _FileObject, events: _EventMask, data: Any = ...) -> SelectorKey: ... + + @abstractmethod + def select(self, timeout: Optional[float] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ... + + def close(self) -> None: ... + + def get_key(self, fileobj: _FileObject) -> SelectorKey: ... + + @abstractmethod + def get_map(self) -> Mapping[_FileObject, SelectorKey]: ... + + def __enter__(self) -> BaseSelector: ... + + def __exit__(self, *args: Any) -> None: ... + +class SelectSelector(BaseSelector): + def register(self, fileobj: _FileObject, events: _EventMask, data: Any = ...) -> SelectorKey: ... + def unregister(self, fileobj: _FileObject) -> SelectorKey: ... + def select(self, timeout: Optional[float] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ... + def get_map(self) -> Mapping[_FileObject, SelectorKey]: ... + +class PollSelector(BaseSelector): + def register(self, fileobj: _FileObject, events: _EventMask, data: Any = ...) -> SelectorKey: ... + def unregister(self, fileobj: _FileObject) -> SelectorKey: ... + def select(self, timeout: Optional[float] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ... + def get_map(self) -> Mapping[_FileObject, SelectorKey]: ... + +class EpollSelector(BaseSelector): + def fileno(self) -> int: ... + def register(self, fileobj: _FileObject, events: _EventMask, data: Any = ...) -> SelectorKey: ... + def unregister(self, fileobj: _FileObject) -> SelectorKey: ... + def select(self, timeout: Optional[float] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ... + def get_map(self) -> Mapping[_FileObject, SelectorKey]: ... + +class DevpollSelector(BaseSelector): + def fileno(self) -> int: ... + def register(self, fileobj: _FileObject, events: _EventMask, data: Any = ...) -> SelectorKey: ... + def unregister(self, fileobj: _FileObject) -> SelectorKey: ... + def select(self, timeout: Optional[float] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ... + def get_map(self) -> Mapping[_FileObject, SelectorKey]: ... + +class KqueueSelector(BaseSelector): + def fileno(self) -> int: ... + def register(self, fileobj: _FileObject, events: _EventMask, data: Any = ...) -> SelectorKey: ... + def unregister(self, fileobj: _FileObject) -> SelectorKey: ... + def select(self, timeout: Optional[float] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ... + def get_map(self) -> Mapping[_FileObject, SelectorKey]: ... + +class DefaultSelector(BaseSelector): + def register(self, fileobj: _FileObject, events: _EventMask, data: Any = ...) -> SelectorKey: ... + def unregister(self, fileobj: _FileObject) -> SelectorKey: ... + def select(self, timeout: Optional[float] = ...) -> List[Tuple[SelectorKey, _EventMask]]: ... + def get_map(self) -> Mapping[_FileObject, SelectorKey]: ... diff --git a/client/typeshed-fallback/stdlib/3/shelve.pyi b/client/typeshed-fallback/stdlib/3/shelve.pyi new file mode 100644 index 000000000..4a339692c --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/shelve.pyi @@ -0,0 +1,31 @@ +from typing import Any, Dict, Iterator, Optional, Tuple +import collections + + +class Shelf(collections.MutableMapping): + def __init__(self, dict: Dict[bytes, Any], protocol: Optional[int] = ..., writeback: bool = ..., keyencoding: str = ...) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __contains__(self, key: Any) -> bool: ... # key should be str, but it would conflict with superclass's type signature + def get(self, key: str, default: Any = ...) -> Any: ... + def __getitem__(self, key: str) -> Any: ... + def __setitem__(self, key: str, value: Any) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __enter__(self) -> Shelf: ... + def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... + def close(self) -> None: ... + def __del__(self) -> None: ... + def sync(self) -> None: ... + +class BsdDbShelf(Shelf): + def __init__(self, dict: Dict[bytes, Any], protocol: Optional[int] = ..., writeback: bool = ..., keyencoding: str = ...) -> None: ... + def set_location(self, key: Any) -> Tuple[str, Any]: ... + def next(self) -> Tuple[str, Any]: ... + def previous(self) -> Tuple[str, Any]: ... + def first(self) -> Tuple[str, Any]: ... + def last(self) -> Tuple[str, Any]: ... + +class DbfilenameShelf(Shelf): + def __init__(self, filename: str, flag: str = ..., protocol: Optional[int] = ..., writeback: bool = ...) -> None: ... + +def open(filename: str, flag: str = ..., protocol: Optional[int] = ..., writeback: bool = ...) -> DbfilenameShelf: ... diff --git a/client/typeshed-fallback/stdlib/3/shlex.pyi b/client/typeshed-fallback/stdlib/3/shlex.pyi new file mode 100644 index 000000000..891d10698 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/shlex.pyi @@ -0,0 +1,50 @@ +# Stubs for shlex + +# Based on http://docs.python.org/3.2/library/shlex.html + +from typing import List, Tuple, Any, TextIO, Union, Optional, Iterable, TypeVar +import sys + +def split(s: str, comments: bool = ..., + posix: bool = ...) -> List[str]: ... + +# Added in 3.3, use (undocumented) pipes.quote in previous versions. +def quote(s: str) -> str: ... + +_SLT = TypeVar('_SLT', bound=shlex) + +class shlex(Iterable[str]): + commenters = ... # type: str + wordchars = ... # type: str + whitespace = ... # type: str + escape = ... # type: str + quotes = ... # type: str + escapedquotes = ... # type: str + whitespace_split = ... # type: bool + infile = ... # type: str + instream = ... # type: TextIO + source = ... # type: str + debug = 0 + lineno = 0 + token = ... # type: str + eof = ... # type: str + if sys.version_info >= (3, 6): + punctuation_chars = ... # type: str + + if sys.version_info >= (3, 6): + def __init__(self, instream: Union[str, TextIO] = ..., infile: Optional[str] = ..., + posix: bool = ..., punctuation_chars: Union[bool, str] = ...) -> None: ... + else: + def __init__(self, instream: Union[str, TextIO] = ..., infile: Optional[str] = ..., + posix: bool = ...) -> None: ... + def get_token(self) -> str: ... + def push_token(self, tok: str) -> None: ... + def read_token(self) -> str: ... + def sourcehook(self, filename: str) -> Tuple[str, TextIO]: ... + # TODO argument types + def push_source(self, newstream: Any, newfile: Any = ...) -> None: ... + def pop_source(self) -> None: ... + def error_leader(self, infile: str = ..., + lineno: int = ...) -> None: ... + def __iter__(self: _SLT) -> _SLT: ... + def __next__(self) -> str: ... diff --git a/client/typeshed-fallback/stdlib/3/signal.pyi b/client/typeshed-fallback/stdlib/3/signal.pyi new file mode 100644 index 000000000..34a8cdd07 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/signal.pyi @@ -0,0 +1,187 @@ +"""Stub file for the 'signal' module.""" + +import sys +from enum import IntEnum +from typing import Any, Callable, List, Tuple, Dict, Generic, Union, Optional, Iterable, Set +from types import FrameType + +class ItimerError(IOError): ... + +ITIMER_PROF: int = ... +ITIMER_REAL: int = ... +ITIMER_VIRTUAL: int = ... + +NSIG: int = ... + +if sys.version_info >= (3, 5): + class Signals(IntEnum): + SIGABRT = ... + SIGALRM = ... + SIGBREAK = ... # Windows + SIGBUS = ... + SIGCHLD = ... + SIGCLD = ... + SIGCONT = ... + SIGEMT = ... + SIGFPE = ... + SIGHUP = ... + SIGILL = ... + SIGINFO = ... + SIGINT = ... + SIGIO = ... + SIGIOT = ... + SIGKILL = ... + SIGPIPE = ... + SIGPOLL = ... + SIGPROF = ... + SIGPWR = ... + SIGQUIT = ... + SIGRTMAX = ... + SIGRTMIN = ... + SIGSEGV = ... + SIGSTOP = ... + SIGSYS = ... + SIGTERM = ... + SIGTRAP = ... + SIGTSTP = ... + SIGTTIN = ... + SIGTTOU = ... + SIGURG = ... + SIGUSR1 = ... + SIGUSR2 = ... + SIGVTALRM = ... + SIGWINCH = ... + SIGXCPU = ... + SIGXFSZ = ... + + class Handlers(IntEnum): + SIG_DFL = ... + SIG_IGN = ... + + SIG_DFL = Handlers.SIG_DFL + SIG_IGN = Handlers.SIG_IGN + + class Sigmasks(IntEnum): + SIG_BLOCK = ... + SIG_UNBLOCK = ... + SIG_SETMASK = ... + + SIG_BLOCK = Sigmasks.SIG_BLOCK + SIG_UNBLOCK = Sigmasks.SIG_UNBLOCK + SIG_SETMASK = Sigmasks.SIG_SETMASK + + _SIG = Signals + _SIGNUM = Union[int, Signals] + _HANDLER = Union[Callable[[Signals, FrameType], None], int, Handlers, None] +else: + SIG_DFL: int = ... + SIG_IGN: int = ... + + SIG_BLOCK: int = ... + SIG_UNBLOCK: int = ... + SIG_SETMASK: int = ... + + _SIG = int + _SIGNUM = int + _HANDLER = Union[Callable[[int, FrameType], None], int, None] + +SIGABRT: _SIG = ... +SIGALRM: _SIG = ... +SIGBREAK: _SIG = ... # Windows +SIGBUS: _SIG = ... +SIGCHLD: _SIG = ... +SIGCLD: _SIG = ... +SIGCONT: _SIG = ... +SIGEMT: _SIG = ... +SIGFPE: _SIG = ... +SIGHUP: _SIG = ... +SIGILL: _SIG = ... +SIGINFO: _SIG = ... +SIGINT: _SIG = ... +SIGIO: _SIG = ... +SIGIOT: _SIG = ... +SIGKILL: _SIG = ... +SIGPIPE: _SIG = ... +SIGPOLL: _SIG = ... +SIGPROF: _SIG = ... +SIGPWR: _SIG = ... +SIGQUIT: _SIG = ... +SIGRTMAX: _SIG = ... +SIGRTMIN: _SIG = ... +SIGSEGV: _SIG = ... +SIGSTOP: _SIG = ... +SIGSYS: _SIG = ... +SIGTERM: _SIG = ... +SIGTRAP: _SIG = ... +SIGTSTP: _SIG = ... +SIGTTIN: _SIG = ... +SIGTTOU: _SIG = ... +SIGURG: _SIG = ... +SIGUSR1: _SIG = ... +SIGUSR2: _SIG = ... +SIGVTALRM: _SIG = ... +SIGWINCH: _SIG = ... +SIGXCPU: _SIG = ... +SIGXFSZ: _SIG = ... + +# Windows +CTRL_C_EVENT: _SIG = ... +CTRL_BREAK_EVENT: _SIG = ... + +class struct_siginfo(Tuple[int, int, int, int, int, int, int]): + def __init__(self, sequence: Iterable[int]) -> None: ... + @property + def si_signo(self) -> int: ... + @property + def si_code(self) -> int: ... + @property + def si_errno(self) -> int: ... + @property + def si_pid(self) -> int: ... + @property + def si_uid(self) -> int: ... + @property + def si_status(self) -> int: ... + @property + def si_band(self) -> int: ... + +def alarm(time: int) -> int: ... + +def default_int_handler(signum: int, frame: FrameType) -> None: + raise KeyboardInterrupt() + +def getitimer(which: int) -> Tuple[float, float]: ... + +def getsignal(signalnum: _SIGNUM) -> _HANDLER: + raise ValueError() + +def pause() -> None: ... + +def pthread_kill(thread_id: int, signum: int) -> None: + raise OSError() + +def pthread_sigmask(how: int, mask: Iterable[int]) -> Set[_SIGNUM]: + raise OSError() + +def set_wakeup_fd(fd: int) -> int: ... + +def setitimer(which: int, seconds: float, interval: float = ...) -> Tuple[float, float]: ... + +def siginterrupt(signalnum: int, flag: bool) -> None: + raise OSError() + +def signal(signalnum: _SIGNUM, handler: _HANDLER) -> _HANDLER: + raise OSError() + +def sigpending() -> Any: + raise OSError() + +def sigtimedwait(sigset: Iterable[int], timeout: float) -> Optional[struct_siginfo]: + raise OSError() + raise ValueError() + +def sigwait(sigset: Iterable[int]) -> _SIGNUM: + raise OSError() + +def sigwaitinfo(sigset: Iterable[int]) -> struct_siginfo: + raise OSError() diff --git a/client/typeshed-fallback/stdlib/3/smtplib.pyi b/client/typeshed-fallback/stdlib/3/smtplib.pyi new file mode 100644 index 000000000..9711f8ffb --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/smtplib.pyi @@ -0,0 +1,140 @@ +from email.message import Message as _Message +from socket import socket +from ssl import SSLContext +from types import TracebackType +from typing import ( + Any, AnyStr, Dict, Generic, List, Optional, Sequence, Tuple, Union, + Pattern, Type, Callable, Protocol, overload) +import sys + +_Reply = Tuple[int, bytes] +_SendErrs = Dict[str, _Reply] +# Should match source_address for socket.create_connection +_SourceAddress = Tuple[Union[bytearray, bytes, str], int] + +SMTP_PORT: int +SMTP_SSL_PORT: int +CRLF: str +bCRLF: bytes + +OLDSTYLE_AUTH: Pattern[str] + +class SMTPException(OSError): ... +class SMTPServerDisconnected(SMTPException): ... + +class SMTPResponseException(SMTPException): + smtp_code: int + smtp_error: Union[bytes, str] + args: Union[Tuple[int, Union[bytes, str]], Tuple[int, bytes, str]] + def __init__(self, code: int, msg: Union[bytes, str]) -> None: ... + +class SMTPSenderRefused(SMTPResponseException): + smtp_code: int + smtp_error: bytes + sender: str + args: Tuple[int, bytes, str] + def __init__(self, code: int, msg: bytes, sender: str) -> None: ... + +class SMTPRecipientsRefused(SMTPException): + recipients: _SendErrs + args: Tuple[_SendErrs] + def __init__(self, recipients: _SendErrs) -> None: ... + +class SMTPDataError(SMTPResponseException): ... +class SMTPConnectError(SMTPResponseException): ... +class SMTPHeloError(SMTPResponseException): ... +class SMTPAuthenticationError(SMTPResponseException): ... + +def quoteaddr(addrstring: str) -> str: ... +def quotedata(data: str) -> str: ... + +class _AuthObject(Protocol): + @overload + def __call__(self, challenge: None = ...) -> Optional[str]: ... + @overload + def __call__(self, challenge: bytes) -> str: ... + +class SMTP: + debuglevel: int = ... + # Type of file should match what socket.makefile() returns + file: Any = ... + helo_resp: Optional[bytes] = ... + ehlo_msg: str = ... + ehlo_resp: Optional[bytes] = ... + does_esmtp: int = ... + default_port: int = ... + timeout: float + esmtp_features: Dict[str, str] + command_encoding: str + source_address: Optional[_SourceAddress] + local_hostname: str + def __init__(self, host: str = ..., port: int = ..., + local_hostname: Optional[str] = ..., timeout: float = ..., + source_address: Optional[_SourceAddress] = ...) -> None: ... + def __enter__(self) -> SMTP: ... + def __exit__(self, exc_type: Optional[Type[Exception]], exc_value: Optional[Exception], + tb: Optional[TracebackType]) -> None: ... + def set_debuglevel(self, debuglevel: int) -> None: ... + sock: Optional[socket] + def connect(self, host: str = ..., port: int = ..., + source_address: Optional[_SourceAddress] = ...) -> _Reply: ... + def send(self, s: Union[bytes, str]) -> None: ... + def putcmd(self, cmd: str, args: str = ...) -> None: ... + def getreply(self) -> _Reply: ... + def docmd(self, cmd: str, args: str = ...) -> _Reply: ... + def helo(self, name: str = ...) -> _Reply: ... + def ehlo(self, name: str = ...) -> _Reply: ... + def has_extn(self, opt: str) -> bool: ... + def help(self, args: str = ...) -> bytes: ... + def rset(self) -> _Reply: ... + def noop(self) -> _Reply: ... + def mail(self, sender: str, options: Sequence[str] = ...) -> _Reply: ... + def rcpt(self, recip: str, options: Sequence[str] = ...) -> _Reply: ... + def data(self, msg: Union[bytes, str]) -> _Reply: ... + def verify(self, address: str) -> _Reply: ... + vrfy = verify + def expn(self, address: str) -> _Reply: ... + def ehlo_or_helo_if_needed(self) -> None: ... + if sys.version_info >= (3, 5): + user: str + password: str + def auth(self, mechanism: str, authobject: _AuthObject, *, initial_response_ok: bool = ...) -> _Reply: ... + @overload + def auth_cram_md5(self, challenge: None = ...) -> None: ... + @overload + def auth_cram_md5(self, challenge: bytes) -> str: ... + def auth_plain(self, challenge: Optional[bytes] = ...) -> str: ... + def auth_login(self, challenge: Optional[bytes] = ...) -> str: ... + def login(self, user: str, password: str, *, + initial_response_ok: bool = ...) -> _Reply: ... + else: + def login(self, user: str, password: str) -> _Reply: ... + def starttls(self, keyfile: Optional[str] = ..., certfile: Optional[str] = ..., + context: Optional[SSLContext] = ...) -> _Reply: ... + def sendmail(self, from_addr: str, to_addrs: Union[str, Sequence[str]], + msg: Union[bytes, str], mail_options: Sequence[str] = ..., + rcpt_options: List[str] = ...) -> _SendErrs: ... + def send_message(self, msg: _Message, from_addr: Optional[str] = ..., + to_addrs: Optional[Union[str, Sequence[str]]] = ..., + mail_options: List[str] = ..., + rcpt_options: Sequence[str] = ...) -> _SendErrs: ... + def close(self) -> None: ... + def quit(self) -> _Reply: ... + +class SMTP_SSL(SMTP): + keyfile: Optional[str] + certfile: Optional[str] + context: SSLContext + def __init__(self, host: str = ..., port: int = ..., + local_hostname: Optional[str] = ..., + keyfile: Optional[str] = ..., certfile: Optional[str] = ..., + timeout: float = ..., + source_address: Optional[_SourceAddress] = ..., + context: Optional[SSLContext] = ...) -> None: ... + +LMTP_PORT: int + +class LMTP(SMTP): + def __init__(self, host: str = ..., port: int = ..., + local_hostname: Optional[str] = ..., + source_address: Optional[_SourceAddress] = ...) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/socketserver.pyi b/client/typeshed-fallback/stdlib/3/socketserver.pyi new file mode 100644 index 000000000..9e6c10b5d --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/socketserver.pyi @@ -0,0 +1,99 @@ +# NB: SocketServer.pyi and socketserver.pyi must remain consistent! +# Stubs for socketserver + +from typing import Any, BinaryIO, Optional, Tuple, Type +from socket import SocketType +import sys +import types + +class BaseServer: + address_family = ... # type: int + RequestHandlerClass = ... # type: type + server_address = ... # type: Tuple[str, int] + socket = ... # type: SocketType + allow_reuse_address = ... # type: bool + request_queue_size = ... # type: int + socket_type = ... # type: int + timeout = ... # type: Optional[float] + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: type) -> None: ... + def fileno(self) -> int: ... + def handle_request(self) -> None: ... + def serve_forever(self, poll_interval: float = ...) -> None: ... + def shutdown(self) -> None: ... + def server_close(self) -> None: ... + def finish_request(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... + def get_request(self) -> None: ... + def handle_error(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... + def handle_timeout(self) -> None: ... + def process_request(self, request: bytes, + client_address: Tuple[str, int]) -> None: ... + def server_activate(self) -> None: ... + def server_bind(self) -> None: ... + def verify_request(self, request: bytes, + client_address: Tuple[str, int]) -> bool: ... + if sys.version_info >= (3, 6): + def __enter__(self) -> BaseServer: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[types.TracebackType]) -> bool: ... + if sys.version_info >= (3, 3): + def service_actions(self) -> None: ... + +class TCPServer(BaseServer): + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: type, + bind_and_activate: bool = ...) -> None: ... + +class UDPServer(BaseServer): + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: type, + bind_and_activate: bool = ...) -> None: ... + +if sys.platform != 'win32': + class UnixStreamServer(BaseServer): + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: type, + bind_and_activate: bool = ...) -> None: ... + + class UnixDatagramServer(BaseServer): + def __init__(self, server_address: Tuple[str, int], + RequestHandlerClass: type, + bind_and_activate: bool = ...) -> None: ... + +class ForkingMixIn: ... +class ThreadingMixIn: ... + +class ForkingTCPServer(ForkingMixIn, TCPServer): ... +class ForkingUDPServer(ForkingMixIn, UDPServer): ... +class ThreadingTCPServer(ThreadingMixIn, TCPServer): ... +class ThreadingUDPServer(ThreadingMixIn, UDPServer): ... +if sys.platform != 'win32': + class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): ... + class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): ... + + +class BaseRequestHandler: + # Those are technically of types, respectively: + # * Union[SocketType, Tuple[bytes, SocketType]] + # * Union[Tuple[str, int], str] + # But there are some concerns that having unions here would cause + # too much inconvenience to people using it (see + # https://github.com/python/typeshed/pull/384#issuecomment-234649696) + request = ... # type: Any + client_address = ... # type: Any + + server = ... # type: BaseServer + def setup(self) -> None: ... + def handle(self) -> None: ... + def finish(self) -> None: ... + +class StreamRequestHandler(BaseRequestHandler): + rfile = ... # type: BinaryIO + wfile = ... # type: BinaryIO + +class DatagramRequestHandler(BaseRequestHandler): + rfile = ... # type: BinaryIO + wfile = ... # type: BinaryIO diff --git a/client/typeshed-fallback/stdlib/3/spwd.pyi b/client/typeshed-fallback/stdlib/3/spwd.pyi new file mode 100644 index 000000000..0e55d7421 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/spwd.pyi @@ -0,0 +1,14 @@ +from typing import List, NamedTuple + +struct_spwd = NamedTuple("struct_spwd", [("sp_namp", str), + ("sp_pwdp", str), + ("sp_lstchg", int), + ("sp_min", int), + ("sp_max", int), + ("sp_warn", int), + ("sp_inact", int), + ("sp_expire", int), + ("sp_flag", int)]) + +def getspall() -> List[struct_spwd]: ... +def getspnam(name: str) -> struct_spwd: ... diff --git a/client/typeshed-fallback/stdlib/3/sre_constants.pyi b/client/typeshed-fallback/stdlib/3/sre_constants.pyi new file mode 100644 index 000000000..10e393cc7 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/sre_constants.pyi @@ -0,0 +1,114 @@ +# Source: https://github.com/python/cpython/blob/master/Lib/sre_constants.py + +from typing import Any, Dict, List, Optional, Union + +MAGIC = ... # type: int + +class error(Exception): + msg = ... # type: str + pattern = ... # type: Optional[Union[str, bytes]] + pos = ... # type: Optional[int] + lineno = ... # type: int + colno = ... # type: int + def __init__(self, msg: str, pattern: Union[str, bytes] = ..., pos: int = ...) -> None: ... + +class _NamedIntConstant(int): + name = ... # type: Any + def __new__(cls, value: int, name: str): ... + +MAXREPEAT = ... # type: _NamedIntConstant +OPCODES = ... # type: List[_NamedIntConstant] +ATCODES = ... # type: List[_NamedIntConstant] +CHCODES = ... # type: List[_NamedIntConstant] +OP_IGNORE = ... # type: Dict[_NamedIntConstant, _NamedIntConstant] +AT_MULTILINE = ... # type: Dict[_NamedIntConstant, _NamedIntConstant] +AT_LOCALE = ... # type: Dict[_NamedIntConstant, _NamedIntConstant] +AT_UNICODE = ... # type: Dict[_NamedIntConstant, _NamedIntConstant] +CH_LOCALE = ... # type: Dict[_NamedIntConstant, _NamedIntConstant] +CH_UNICODE = ... # type: Dict[_NamedIntConstant, _NamedIntConstant] +SRE_FLAG_TEMPLATE = ... # type: int +SRE_FLAG_IGNORECASE = ... # type: int +SRE_FLAG_LOCALE = ... # type: int +SRE_FLAG_MULTILINE = ... # type: int +SRE_FLAG_DOTALL = ... # type: int +SRE_FLAG_UNICODE = ... # type: int +SRE_FLAG_VERBOSE = ... # type: int +SRE_FLAG_DEBUG = ... # type: int +SRE_FLAG_ASCII = ... # type: int +SRE_INFO_PREFIX = ... # type: int +SRE_INFO_LITERAL = ... # type: int +SRE_INFO_CHARSET = ... # type: int + + +# Stubgen above; manually defined constants below (dynamic at runtime) + +# from OPCODES +FAILURE = ... # type: _NamedIntConstant +SUCCESS = ... # type: _NamedIntConstant +ANY = ... # type: _NamedIntConstant +ANY_ALL = ... # type: _NamedIntConstant +ASSERT = ... # type: _NamedIntConstant +ASSERT_NOT = ... # type: _NamedIntConstant +AT = ... # type: _NamedIntConstant +BRANCH = ... # type: _NamedIntConstant +CALL = ... # type: _NamedIntConstant +CATEGORY = ... # type: _NamedIntConstant +CHARSET = ... # type: _NamedIntConstant +BIGCHARSET = ... # type: _NamedIntConstant +GROUPREF = ... # type: _NamedIntConstant +GROUPREF_EXISTS = ... # type: _NamedIntConstant +GROUPREF_IGNORE = ... # type: _NamedIntConstant +IN = ... # type: _NamedIntConstant +IN_IGNORE = ... # type: _NamedIntConstant +INFO = ... # type: _NamedIntConstant +JUMP = ... # type: _NamedIntConstant +LITERAL = ... # type: _NamedIntConstant +LITERAL_IGNORE = ... # type: _NamedIntConstant +MARK = ... # type: _NamedIntConstant +MAX_UNTIL = ... # type: _NamedIntConstant +MIN_UNTIL = ... # type: _NamedIntConstant +NOT_LITERAL = ... # type: _NamedIntConstant +NOT_LITERAL_IGNORE = ... # type: _NamedIntConstant +NEGATE = ... # type: _NamedIntConstant +RANGE = ... # type: _NamedIntConstant +REPEAT = ... # type: _NamedIntConstant +REPEAT_ONE = ... # type: _NamedIntConstant +SUBPATTERN = ... # type: _NamedIntConstant +MIN_REPEAT_ONE = ... # type: _NamedIntConstant +RANGE_IGNORE = ... # type: _NamedIntConstant +MIN_REPEAT = ... # type: _NamedIntConstant +MAX_REPEAT = ... # type: _NamedIntConstant + +# from ATCODES +AT_BEGINNING = ... # type: _NamedIntConstant +AT_BEGINNING_LINE = ... # type: _NamedIntConstant +AT_BEGINNING_STRING = ... # type: _NamedIntConstant +AT_BOUNDARY = ... # type: _NamedIntConstant +AT_NON_BOUNDARY = ... # type: _NamedIntConstant +AT_END = ... # type: _NamedIntConstant +AT_END_LINE = ... # type: _NamedIntConstant +AT_END_STRING = ... # type: _NamedIntConstant +AT_LOC_BOUNDARY = ... # type: _NamedIntConstant +AT_LOC_NON_BOUNDARY = ... # type: _NamedIntConstant +AT_UNI_BOUNDARY = ... # type: _NamedIntConstant +AT_UNI_NON_BOUNDARY = ... # type: _NamedIntConstant + +# from CHCODES +CATEGORY_DIGIT = ... # type: _NamedIntConstant +CATEGORY_NOT_DIGIT = ... # type: _NamedIntConstant +CATEGORY_SPACE = ... # type: _NamedIntConstant +CATEGORY_NOT_SPACE = ... # type: _NamedIntConstant +CATEGORY_WORD = ... # type: _NamedIntConstant +CATEGORY_NOT_WORD = ... # type: _NamedIntConstant +CATEGORY_LINEBREAK = ... # type: _NamedIntConstant +CATEGORY_NOT_LINEBREAK = ... # type: _NamedIntConstant +CATEGORY_LOC_WORD = ... # type: _NamedIntConstant +CATEGORY_LOC_NOT_WORD = ... # type: _NamedIntConstant +CATEGORY_UNI_DIGIT = ... # type: _NamedIntConstant +CATEGORY_UNI_NOT_DIGIT = ... # type: _NamedIntConstant +CATEGORY_UNI_SPACE = ... # type: _NamedIntConstant +CATEGORY_UNI_NOT_SPACE = ... # type: _NamedIntConstant +CATEGORY_UNI_WORD = ... # type: _NamedIntConstant +CATEGORY_UNI_NOT_WORD = ... # type: _NamedIntConstant +CATEGORY_UNI_LINEBREAK = ... # type: _NamedIntConstant +CATEGORY_UNI_NOT_LINEBREAK = ... # type: _NamedIntConstant diff --git a/client/typeshed-fallback/stdlib/3/sre_parse.pyi b/client/typeshed-fallback/stdlib/3/sre_parse.pyi new file mode 100644 index 000000000..0c9859d26 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/sre_parse.pyi @@ -0,0 +1,81 @@ +# Source: https://github.com/python/cpython/blob/master/Lib/sre_parse.py + +from typing import ( + Any, Dict, FrozenSet, Iterable, List, Match, + Optional, Pattern as _Pattern, Tuple, Union +) +from sre_constants import _NamedIntConstant as NIC, error as _Error + +SPECIAL_CHARS = ... # type: str +REPEAT_CHARS = ... # type: str +DIGITS = ... # type: FrozenSet[str] +OCTDIGITS = ... # type: FrozenSet[str] +HEXDIGITS = ... # type: FrozenSet[str] +ASCIILETTERS = ... # type: FrozenSet[str] +WHITESPACE = ... # type: FrozenSet[str] +ESCAPES = ... # type: Dict[str, Tuple[NIC, int]] +CATEGORIES = ... # type: Dict[str, Union[Tuple[NIC, NIC], Tuple[NIC, List[Tuple[NIC, NIC]]]]] +FLAGS = ... # type: Dict[str, int] +GLOBAL_FLAGS = ... # type: int + +class Verbose(Exception): ... + +class Pattern: + flags = ... # type: int + groupdict = ... # type: Dict[str, int] + groupwidths = ... # type: List[Optional[int]] + lookbehindgroups = ... # type: Optional[int] + def __init__(self) -> None: ... + @property + def groups(self) -> int: ... + def opengroup(self, name: str = ...) -> int: ... + def closegroup(self, gid: int, p: SubPattern) -> None: ... + def checkgroup(self, gid: int) -> bool: ... + def checklookbehindgroup(self, gid: int, source: Tokenizer) -> None: ... + + +_OpSubpatternType = Tuple[Optional[int], int, int, SubPattern] +_OpGroupRefExistsType = Tuple[int, SubPattern, SubPattern] +_OpInType = List[Tuple[NIC, int]] +_OpBranchType = Tuple[None, List[SubPattern]] +_AvType = Union[_OpInType, _OpBranchType, Iterable[SubPattern], _OpGroupRefExistsType, _OpSubpatternType] +_CodeType = Tuple[NIC, _AvType] + + +class SubPattern: + pattern = ... # type: Pattern + data = ... # type: List[_CodeType] + width = ... # type: Optional[int] + def __init__(self, pattern: Pattern, data: List[_CodeType] = ...) -> None: ... + def dump(self, level: int = ...) -> None: ... + def __len__(self) -> int: ... + def __delitem__(self, index: Union[int, slice]) -> None: ... + def __getitem__(self, index: Union[int, slice]) -> Union[SubPattern, _CodeType]: ... + def __setitem__(self, index: Union[int, slice], code: _CodeType) -> None: ... + def insert(self, index: int, code: _CodeType) -> None: ... + def append(self, code: _CodeType) -> None: ... + def getwidth(self) -> int: ... + + +class Tokenizer: + istext = ... # type: bool + string = ... # type: Any + decoded_string = ... # type: str + index = ... # type: int + next = ... # type: Optional[str] + def __init__(self, string: Any) -> None: ... + def match(self, char: str) -> bool: ... + def get(self) -> Optional[str]: ... + def getwhile(self, n: int, charset: Iterable[str]) -> str: ... + def getuntil(self, terminator: str) -> str: ... + @property + def pos(self) -> int: ... + def tell(self) -> int: ... + def seek(self, index: int) -> None: ... + def error(self, msg: str, offset: int = ...) -> _Error: ... + +def fix_flags(src: Union[str, bytes], flag: int) -> int: ... +def parse(str: str, flags: int = ..., pattern: Pattern = ...) -> SubPattern: ... +_TemplateType = Tuple[List[Tuple[int, int]], List[str]] +def parse_template(source: str, pattern: _Pattern) -> _TemplateType: ... +def expand_template(template: _TemplateType, match: Match) -> str: ... diff --git a/client/typeshed-fallback/stdlib/3/stat.pyi b/client/typeshed-fallback/stdlib/3/stat.pyi new file mode 100644 index 000000000..c45a06863 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/stat.pyi @@ -0,0 +1,75 @@ +# Stubs for stat + +# Based on http://docs.python.org/3.2/library/stat.html + +import sys +import typing + +def S_ISDIR(mode: int) -> bool: ... +def S_ISCHR(mode: int) -> bool: ... +def S_ISBLK(mode: int) -> bool: ... +def S_ISREG(mode: int) -> bool: ... +def S_ISFIFO(mode: int) -> bool: ... +def S_ISLNK(mode: int) -> bool: ... +def S_ISSOCK(mode: int) -> bool: ... + +def S_IMODE(mode: int) -> int: ... +def S_IFMT(mode: int) -> int: ... + +def filemode(mode: int) -> str: ... + +ST_MODE = 0 +ST_INO = 0 +ST_DEV = 0 +ST_NLINK = 0 +ST_UID = 0 +ST_GID = 0 +ST_SIZE = 0 +ST_ATIME = 0 +ST_MTIME = 0 +ST_CTIME = 0 + +S_IFSOCK = 0 +S_IFLNK = 0 +S_IFREG = 0 +S_IFBLK = 0 +S_IFDIR = 0 +S_IFCHR = 0 +S_IFIFO = 0 +S_ISUID = 0 +S_ISGID = 0 +S_ISVTX = 0 + +S_IRWXU = 0 +S_IRUSR = 0 +S_IWUSR = 0 +S_IXUSR = 0 + +S_IRWXG = 0 +S_IRGRP = 0 +S_IWGRP = 0 +S_IXGRP = 0 + +S_IRWXO = 0 +S_IROTH = 0 +S_IWOTH = 0 +S_IXOTH = 0 + +S_ENFMT = 0 +S_IREAD = 0 +S_IWRITE = 0 +S_IEXEC = 0 + +UF_NODUMP = 0 +UF_IMMUTABLE = 0 +UF_APPEND = 0 +UF_OPAQUE = 0 +UF_NOUNLINK = 0 +if sys.platform == 'darwin': + UF_COMPRESSED = 0 # OS X 10.6+ only + UF_HIDDEN = 0 # OX X 10.5+ only +SF_ARCHIVED = 0 +SF_IMMUTABLE = 0 +SF_APPEND = 0 +SF_NOUNLINK = 0 +SF_SNAPSHOT = 0 diff --git a/client/typeshed-fallback/stdlib/3/statistics.pyi b/client/typeshed-fallback/stdlib/3/statistics.pyi new file mode 100644 index 000000000..d9116e587 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/statistics.pyi @@ -0,0 +1,24 @@ +# Stubs for statistics + +from decimal import Decimal +from fractions import Fraction +import sys +from typing import Iterable, Optional, TypeVar + +# Most functions in this module accept homogeneous collections of one of these types +_Number = TypeVar('_Number', float, Decimal, Fraction) + +class StatisticsError(ValueError): ... + +def mean(data: Iterable[_Number]) -> _Number: ... +if sys.version_info >= (3, 6): + def harmonic_mean(data: Iterable[_Number]) -> _Number: ... +def median(data: Iterable[_Number]) -> _Number: ... +def median_low(data: Iterable[_Number]) -> _Number: ... +def median_high(data: Iterable[_Number]) -> _Number: ... +def median_grouped(data: Iterable[_Number]) -> _Number: ... +def mode(data: Iterable[_Number]) -> _Number: ... +def pstdev(data: Iterable[_Number], mu: Optional[_Number] = ...) -> _Number: ... +def pvariance(data: Iterable[_Number], mu: Optional[_Number] = ...) -> _Number: ... +def stdev(data: Iterable[_Number], xbar: Optional[_Number] = ...) -> _Number: ... +def variance(data: Iterable[_Number], xbar: Optional[_Number] = ...) -> _Number: ... diff --git a/client/typeshed-fallback/stdlib/3/string.pyi b/client/typeshed-fallback/stdlib/3/string.pyi new file mode 100644 index 000000000..c07c186d1 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/string.pyi @@ -0,0 +1,42 @@ +# Stubs for string + +# Based on http://docs.python.org/3.2/library/string.html + +from typing import Mapping, Sequence, Any, Optional, Union, List, Tuple, Iterable + +ascii_letters = ... # type: str +ascii_lowercase = ... # type: str +ascii_uppercase = ... # type: str +digits = ... # type: str +hexdigits = ... # type: str +octdigits = ... # type: str +punctuation = ... # type: str +printable = ... # type: str +whitespace = ... # type: str + +def capwords(s: str, sep: str = ...) -> str: ... + +class Template: + template = ... # type: str + + def __init__(self, template: str) -> None: ... + def substitute(self, mapping: Mapping[str, str] = ..., **kwds: str) -> str: ... + def safe_substitute(self, mapping: Mapping[str, str] = ..., + **kwds: str) -> str: ... + +# TODO(MichalPokorny): This is probably badly and/or loosely typed. +class Formatter: + def format(self, format_string: str, *args: Any, **kwargs: Any) -> str: ... + def vformat(self, format_string: str, args: Sequence[Any], + kwargs: Mapping[str, Any]) -> str: ... + def parse(self, format_string: str) -> Iterable[Tuple[str, Optional[str], Optional[str], Optional[str]]]: ... + def get_field(self, field_name: str, args: Sequence[Any], + kwargs: Mapping[str, Any]) -> Any: ... + def get_value(self, key: Union[int, str], args: Sequence[Any], + kwargs: Mapping[str, Any]) -> Any: + raise IndexError() + raise KeyError() + def check_unused_args(self, used_args: Sequence[Union[int, str]], args: Sequence[Any], + kwargs: Mapping[str, Any]) -> None: ... + def format_field(self, value: Any, format_spec: str) -> Any: ... + def convert_field(self, value: Any, conversion: str) -> Any: ... diff --git a/client/typeshed-fallback/stdlib/3/subprocess.pyi b/client/typeshed-fallback/stdlib/3/subprocess.pyi new file mode 100644 index 000000000..5284a1ded --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/subprocess.pyi @@ -0,0 +1,365 @@ +# Stubs for subprocess + +# Based on http://docs.python.org/3.6/library/subprocess.html +import sys +from typing import Sequence, Any, Mapping, Callable, Tuple, IO, Optional, Union, List, Type, Text +from types import TracebackType + +# We prefer to annotate inputs to methods (eg subprocess.check_call) with these +# union types. However, outputs (eg check_call return) and class attributes +# (eg TimeoutError.cmd) we prefer to annotate with Any, so the caller does not +# have to use an assertion to confirm which type. +# +# For example: +# +# try: +# x = subprocess.check_output(["ls", "-l"]) +# reveal_type(x) # Any, but morally is _TXT +# except TimeoutError as e: +# reveal_type(e.cmd) # Any, but morally is _CMD +_FILE = Union[None, int, IO[Any]] +_TXT = Union[bytes, Text] +if sys.version_info >= (3, 6): + from builtins import _PathLike + _PATH = Union[bytes, Text, _PathLike] +else: + _PATH = Union[bytes, Text] +# Python 3.6 does't support _CMD being a single PathLike. +# See: https://bugs.python.org/issue31961 +_CMD = Union[_TXT, Sequence[_PATH]] +_ENV = Union[Mapping[bytes, _TXT], Mapping[Text, _TXT]] + +if sys.version_info >= (3, 5): + class CompletedProcess: + # morally: _CMD + args = ... # type: Any + returncode = ... # type: int + # morally: Optional[_TXT] + stdout = ... # type: Any + stderr = ... # type: Any + def __init__(self, args: _CMD, + returncode: int, + stdout: Optional[_TXT] = ..., + stderr: Optional[_TXT] = ...) -> None: ... + def check_returncode(self) -> None: ... + + if sys.version_info >= (3, 7): + # Nearly the same args as for 3.6, except for capture_output and text + def run(args: _CMD, + bufsize: int = ..., + executable: _PATH = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_PATH] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + capture_output: bool = ..., + check: bool = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + input: Optional[_TXT] = ..., + text: Optional[bool] = ..., + timeout: Optional[float] = ...) -> CompletedProcess: ... + elif sys.version_info >= (3, 6): + # Nearly same args as Popen.__init__ except for timeout, input, and check + def run(args: _CMD, + bufsize: int = ..., + executable: _PATH = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_PATH] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + check: bool = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + input: Optional[_TXT] = ..., + timeout: Optional[float] = ...) -> CompletedProcess: ... + else: + # Nearly same args as Popen.__init__ except for timeout, input, and check + def run(args: _CMD, + timeout: Optional[float] = ..., + input: Optional[_TXT] = ..., + check: bool = ..., + bufsize: int = ..., + executable: _PATH = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_PATH] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ...) -> CompletedProcess: ... + +# Same args as Popen.__init__ +def call(args: _CMD, + bufsize: int = ..., + executable: _PATH = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_PATH] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + timeout: float = ...) -> int: ... + +# Same args as Popen.__init__ +def check_call(args: _CMD, + bufsize: int = ..., + executable: _PATH = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_PATH] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + timeout: float = ...) -> int: ... + +if sys.version_info >= (3, 7): + # 3.7 added text + def check_output(args: _CMD, + bufsize: int = ..., + executable: _PATH = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_PATH] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: float = ..., + input: _TXT = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + text: Optional[bool] = ..., + ) -> Any: ... # morally: -> _TXT +elif sys.version_info >= (3, 6): + # 3.6 added encoding and errors + def check_output(args: _CMD, + bufsize: int = ..., + executable: _PATH = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_PATH] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: float = ..., + input: _TXT = ..., + encoding: Optional[str] = ..., + errors: Optional[str] = ..., + ) -> Any: ... # morally: -> _TXT +else: + def check_output(args: _CMD, + bufsize: int = ..., + executable: _PATH = ..., + stdin: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_PATH] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + timeout: float = ..., + input: _TXT = ..., + ) -> Any: ... # morally: -> _TXT + + +PIPE = ... # type: int +STDOUT = ... # type: int +DEVNULL = ... # type: int +class SubprocessError(Exception): ... +class TimeoutExpired(SubprocessError): + def __init__(self, cmd: _CMD, timeout: float, output: Optional[_TXT] = ..., stderr: Optional[_TXT] = ...) -> None: ... + # morally: _CMD + cmd = ... # type: Any + timeout = ... # type: float + # morally: Optional[_TXT] + output = ... # type: Any + stdout = ... # type: Any + stderr = ... # type: Any + + +class CalledProcessError(Exception): + returncode = 0 + # morally: _CMD + cmd = ... # type: Any + # morally: Optional[_TXT] + output = ... # type: Any + + if sys.version_info >= (3, 5): + # morally: Optional[_TXT] + stdout = ... # type: Any + stderr = ... # type: Any + + def __init__(self, + returncode: int, + cmd: _CMD, + output: Optional[_TXT] = ..., + stderr: Optional[_TXT] = ...) -> None: ... + +class Popen: + args = ... # type: _CMD + stdin = ... # type: IO[Any] + stdout = ... # type: IO[Any] + stderr = ... # type: IO[Any] + pid = 0 + returncode = 0 + + if sys.version_info >= (3, 6): + def __init__(self, + args: _CMD, + bufsize: int = ..., + executable: Optional[_PATH] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_PATH] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + encoding: Optional[str] = ..., + errors: Optional[str] = ...) -> None: ... + else: + def __init__(self, + args: _CMD, + bufsize: int = ..., + executable: Optional[_PATH] = ..., + stdin: Optional[_FILE] = ..., + stdout: Optional[_FILE] = ..., + stderr: Optional[_FILE] = ..., + preexec_fn: Optional[Callable[[], Any]] = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: Optional[_PATH] = ..., + env: Optional[_ENV] = ..., + universal_newlines: bool = ..., + startupinfo: Optional[Any] = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ...) -> None: ... + + def poll(self) -> int: ... + def wait(self, timeout: Optional[float] = ...) -> int: ... + # Return str/bytes + def communicate(self, + input: Optional[_TXT] = ..., + timeout: Optional[float] = ..., + # morally: -> Tuple[Optional[_TXT], Optional[_TXT]] + ) -> Tuple[Any, Any]: ... + def send_signal(self, signal: int) -> None: ... + def terminate(self) -> None: ... + def kill(self) -> None: ... + def __enter__(self) -> Popen: ... + def __exit__(self, type: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType]) -> bool: ... + +# The result really is always a str. +def getstatusoutput(cmd: _TXT) -> Tuple[int, str]: ... +def getoutput(cmd: _TXT) -> str: ... + +def list2cmdline(seq: Sequence[str]) -> str: ... # undocumented + +if sys.platform == 'win32': + class STARTUPINFO: + if sys.version_info >= (3, 7): + def __init__(self, *, dwFlags: int = ..., hStdInput: Optional[Any] = ..., hStdOutput: Optional[Any] = ..., hStdError: Optional[Any] = ..., wShowWindow: int = ..., lpAttributeList: Optional[Mapping[str, Any]] = ...) -> None: ... + dwFlags: int + hStdInput: Optional[Any] + hStdOutput: Optional[Any] + hStdError: Optional[Any] + wShowWindow: int + if sys.version_info >= (3, 7): + lpAttributeList: Mapping[str, Any] + + STD_INPUT_HANDLE: Any + STD_OUTPUT_HANDLE: Any + STD_ERROR_HANDLE: Any + SW_HIDE: int + STARTF_USESTDHANDLES: int + STARTF_USESHOWWINDOW: int + CREATE_NEW_CONSOLE: int + CREATE_NEW_PROCESS_GROUP: int + if sys.version_info >= (3, 7): + ABOVE_NORMAL_PRIORITY_CLASS: int + BELOW_NORMAL_PRIORITY_CLASS: int + HIGH_PRIORITY_CLASS: int + IDLE_PRIORITY_CLASS: int + NORMAL_PRIORITY_CLASS: int + REALTIME_PRIORITY_CLASS: int + CREATE_NO_WINDOW: int + DETACHED_PROCESS: int + CREATE_DEFAULT_ERROR_MODE: int + CREATE_BREAKAWAY_FROM_JOB: int diff --git a/client/typeshed-fallback/stdlib/3/symbol.pyi b/client/typeshed-fallback/stdlib/3/symbol.pyi new file mode 100644 index 000000000..f228cf7ba --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/symbol.pyi @@ -0,0 +1,97 @@ +# Stubs for symbol (Python 3) + +import sys +from typing import Dict + +single_input = ... # type: int +file_input = ... # type: int +eval_input = ... # type: int +decorator = ... # type: int +decorators = ... # type: int +decorated = ... # type: int +if sys.version_info >= (3, 5): + async_funcdef = ... # type: int +funcdef = ... # type: int +parameters = ... # type: int +typedargslist = ... # type: int +tfpdef = ... # type: int +varargslist = ... # type: int +vfpdef = ... # type: int +stmt = ... # type: int +simple_stmt = ... # type: int +small_stmt = ... # type: int +expr_stmt = ... # type: int +if sys.version_info >= (3, 6): + annassign = ... # type: int +testlist_star_expr = ... # type: int +augassign = ... # type: int +del_stmt = ... # type: int +pass_stmt = ... # type: int +flow_stmt = ... # type: int +break_stmt = ... # type: int +continue_stmt = ... # type: int +return_stmt = ... # type: int +yield_stmt = ... # type: int +raise_stmt = ... # type: int +import_stmt = ... # type: int +import_name = ... # type: int +import_from = ... # type: int +import_as_name = ... # type: int +dotted_as_name = ... # type: int +import_as_names = ... # type: int +dotted_as_names = ... # type: int +dotted_name = ... # type: int +global_stmt = ... # type: int +nonlocal_stmt = ... # type: int +assert_stmt = ... # type: int +compound_stmt = ... # type: int +if sys.version_info >= (3, 5): + async_stmt = ... # type: int +if_stmt = ... # type: int +while_stmt = ... # type: int +for_stmt = ... # type: int +try_stmt = ... # type: int +with_stmt = ... # type: int +with_item = ... # type: int +except_clause = ... # type: int +suite = ... # type: int +test = ... # type: int +test_nocond = ... # type: int +lambdef = ... # type: int +lambdef_nocond = ... # type: int +or_test = ... # type: int +and_test = ... # type: int +not_test = ... # type: int +comparison = ... # type: int +comp_op = ... # type: int +star_expr = ... # type: int +expr = ... # type: int +xor_expr = ... # type: int +and_expr = ... # type: int +shift_expr = ... # type: int +arith_expr = ... # type: int +term = ... # type: int +factor = ... # type: int +power = ... # type: int +if sys.version_info >= (3, 5): + atom_expr = ... # type: int +atom = ... # type: int +testlist_comp = ... # type: int +trailer = ... # type: int +subscriptlist = ... # type: int +subscript = ... # type: int +sliceop = ... # type: int +exprlist = ... # type: int +testlist = ... # type: int +dictorsetmaker = ... # type: int +classdef = ... # type: int +arglist = ... # type: int +argument = ... # type: int +comp_iter = ... # type: int +comp_for = ... # type: int +comp_if = ... # type: int +encoding_decl = ... # type: int +yield_expr = ... # type: int +yield_arg = ... # type: int + +sym_name = ... # type: Dict[int, str] diff --git a/client/typeshed-fallback/stdlib/3/sys.pyi b/client/typeshed-fallback/stdlib/3/sys.pyi new file mode 100644 index 000000000..0e7b47600 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/sys.pyi @@ -0,0 +1,197 @@ +# Stubs for sys +# Ron Murawski + +# based on http://docs.python.org/3.2/library/sys.html + +from typing import ( + List, NoReturn, Sequence, Any, Dict, Tuple, TextIO, overload, Optional, + Union, TypeVar, Callable, Type +) +import sys +from types import FrameType, ModuleType, TracebackType + +from importlib.abc import MetaPathFinder + +_T = TypeVar('_T') + +# The following type alias are stub-only and do not exist during runtime +_ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType] +_OptExcInfo = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] + +# ----- sys variables ----- +abiflags: str +argv: List[str] +base_exec_prefix: str +base_prefix: str +byteorder: str +builtin_module_names: Sequence[str] # actually a tuple of strings +copyright: str +# dllhandle = 0 # Windows only +dont_write_bytecode: bool +__displayhook__: Any # contains the original value of displayhook +__excepthook__: Any # contains the original value of excepthook +exec_prefix: str +executable: str +float_repr_style: str +hexversion: int +last_type: Optional[Type[BaseException]] +last_value: Optional[BaseException] +last_traceback: Optional[TracebackType] +maxsize: int +maxunicode: int +meta_path: List[MetaPathFinder] +modules: Dict[str, ModuleType] +path: List[str] +path_hooks: List[Any] # TODO precise type; function, path to finder +path_importer_cache: Dict[str, Any] # TODO precise type +platform: str +prefix: str +ps1: str +ps2: str +stdin: TextIO +stdout: TextIO +stderr: TextIO +__stdin__: TextIO +__stdout__: TextIO +__stderr__: TextIO +# deprecated and removed in Python 3.3: +subversion: Tuple[str, str, str] +tracebacklimit: int +version: str +api_version: int +warnoptions: Any +# Each entry is a tuple of the form (action, message, category, module, +# lineno) +# winver = '' # Windows only +_xoptions: Dict[Any, Any] + + +flags: _flags +class _flags: + debug: int + division_warning: int + inspect: int + interactive: int + optimize: int + dont_write_bytecode: int + no_user_site: int + no_site: int + ignore_environment: int + verbose: int + bytes_warning: int + quiet: int + hash_randomization: int + if sys.version_info >= (3, 7): + dev_mode: int + +float_info: _float_info +class _float_info: + epsilon: float # DBL_EPSILON + dig: int # DBL_DIG + mant_dig: int # DBL_MANT_DIG + max: float # DBL_MAX + max_exp: int # DBL_MAX_EXP + max_10_exp: int # DBL_MAX_10_EXP + min: float # DBL_MIN + min_exp: int # DBL_MIN_EXP + min_10_exp: int # DBL_MIN_10_EXP + radix: int # FLT_RADIX + rounds: int # FLT_ROUNDS + +hash_info: _hash_info +class _hash_info: + width: int + modulus: int + inf: int + nan: int + imag: int + +implementation: _implementation +class _implementation: + name: str + version: _version_info + hexversion: int + cache_tag: str + +int_info: _int_info +class _int_info: + bits_per_digit: int + sizeof_digit: int + +class _version_info(Tuple[int, int, int, str, int]): + major: int + minor: int + micro: int + releaselevel: str + serial: int +version_info: _version_info + +def call_tracing(fn: Callable[..., _T], args: Any) -> _T: ... +def _clear_type_cache() -> None: ... +def _current_frames() -> Dict[int, Any]: ... +def displayhook(value: Optional[int]) -> None: ... +def excepthook(type_: Type[BaseException], value: BaseException, + traceback: TracebackType) -> None: ... +def exc_info() -> _OptExcInfo: ... +# sys.exit() accepts an optional argument of anything printable +def exit(arg: object = ...) -> NoReturn: + raise SystemExit() +def getcheckinterval() -> int: ... # deprecated +def getdefaultencoding() -> str: ... +if sys.platform != 'win32': + # Unix only + def getdlopenflags() -> int: ... +def getfilesystemencoding() -> str: ... +def getrefcount(arg: Any) -> int: ... +def getrecursionlimit() -> int: ... + +@overload +def getsizeof(obj: object) -> int: ... +@overload +def getsizeof(obj: object, default: int) -> int: ... + +def getswitchinterval() -> float: ... + +@overload +def _getframe() -> FrameType: ... +@overload +def _getframe(depth: int) -> FrameType: ... + +_ProfileFunc = Callable[[FrameType, str, Any], Any] +def getprofile() -> Optional[_ProfileFunc]: ... +def setprofile(profilefunc: Optional[_ProfileFunc]) -> None: ... + +_TraceFunc = Callable[[FrameType, str, Any], Optional[Callable[[FrameType, str, Any], Any]]] +def gettrace() -> Optional[_TraceFunc]: ... +def settrace(tracefunc: Optional[_TraceFunc]) -> None: ... + + +class _WinVersion(Tuple[int, int, int, int, + str, int, int, int, int, + Tuple[int, int, int]]): + major: int + minor: int + build: int + platform: int + service_pack: str + service_pack_minor: int + service_pack_major: int + suite_mast: int + product_type: int + platform_version: Tuple[int, int, int] + + +def getwindowsversion() -> _WinVersion: ... # Windows only + +def intern(string: str) -> str: ... + +if sys.version_info >= (3, 5): + def is_finalizing() -> bool: ... + +def setcheckinterval(interval: int) -> None: ... # deprecated +def setdlopenflags(n: int) -> None: ... # Linux only +def setrecursionlimit(limit: int) -> None: ... +def setswitchinterval(interval: float) -> None: ... +def settscdump(on_flag: bool) -> None: ... + +def gettotalrefcount() -> int: ... # Debug builds only diff --git a/client/typeshed-fallback/stdlib/3/tempfile.pyi b/client/typeshed-fallback/stdlib/3/tempfile.pyi new file mode 100644 index 000000000..c3e296327 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/tempfile.pyi @@ -0,0 +1,120 @@ +# Stubs for tempfile +# Ron Murawski + +# based on http://docs.python.org/3.3/library/tempfile.html + +import sys +from types import TracebackType +from typing import Any, AnyStr, Generic, IO, Iterable, Iterator, List, Optional, Tuple, Type + +# global variables +TMP_MAX: int +tempdir = ... # type: Optional[str] +template = ... # type: str + + +if sys.version_info >= (3, 5): + def TemporaryFile( + mode: str = ..., buffering: int = ..., encoding: Optional[str] = ..., + newline: Optional[str] = ..., suffix: Optional[AnyStr] = ..., prefix: Optional[AnyStr] = ..., + dir: Optional[AnyStr] = ... + ) -> IO[Any]: + ... + def NamedTemporaryFile( + mode: str = ..., buffering: int = ..., encoding: Optional[str] = ..., + newline: Optional[str] = ..., suffix: Optional[AnyStr] = ..., prefix: Optional[AnyStr] = ..., + dir: Optional[AnyStr] = ..., delete: bool = ... + ) -> IO[Any]: + ... + + # It does not actually derive from IO[AnyStr], but it does implement the + # protocol. + class SpooledTemporaryFile(IO[AnyStr]): + def __init__(self, max_size: int = ..., mode: str = ..., + buffering: int = ..., encoding: Optional[str] = ..., + newline: Optional[str] = ..., suffix: Optional[str] = ..., + prefix: Optional[str] = ..., dir: Optional[str] = ... + ) -> None: ... + def rollover(self) -> None: ... + def __enter__(self) -> SpooledTemporaryFile: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType]) -> bool: ... + + # These methods are copied from the abstract methods of IO, because + # SpooledTemporaryFile implements IO. + # See also https://github.com/python/typeshed/pull/2452#issuecomment-420657918. + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def read(self, n: int = ...) -> AnyStr: ... + def readable(self) -> bool: ... + def readline(self, limit: int = ...) -> AnyStr: ... + def readlines(self, hint: int = ...) -> List[AnyStr]: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def writable(self) -> bool: ... + def write(self, s: AnyStr) -> int: ... + def writelines(self, lines: Iterable[AnyStr]) -> None: ... + def __next__(self) -> AnyStr: ... + def __iter__(self) -> Iterator[AnyStr]: ... + + class TemporaryDirectory(Generic[AnyStr]): + name = ... # type: str + def __init__(self, suffix: Optional[AnyStr] = ..., prefix: Optional[AnyStr] = ..., + dir: Optional[AnyStr] = ...) -> None: ... + def cleanup(self) -> None: ... + def __enter__(self) -> AnyStr: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType]) -> bool: ... + + def mkstemp(suffix: Optional[AnyStr] = ..., prefix: Optional[AnyStr] = ..., dir: Optional[AnyStr] = ..., + text: bool = ...) -> Tuple[int, AnyStr]: ... + def mkdtemp(suffix: Optional[AnyStr] = ..., prefix: Optional[AnyStr] = ..., + dir: Optional[str] = ...) -> AnyStr: ... + def mktemp(suffix: Optional[AnyStr] = ..., prefix: Optional[AnyStr] = ..., dir: Optional[AnyStr] = ...) -> AnyStr: ... + + def gettempdirb() -> bytes: ... + def gettempprefixb() -> bytes: ... +else: + def TemporaryFile( + mode: str = ..., buffering: int = ..., encoding: Optional[str] = ..., + newline: Optional[str] = ..., suffix: str = ..., prefix: str = ..., + dir: Optional[str] = ... + ) -> IO[Any]: + ... + def NamedTemporaryFile( + mode: str = ..., buffering: int = ..., encoding: Optional[str] = ..., + newline: Optional[str] = ..., suffix: str = ..., prefix: str = ..., + dir: Optional[str] = ..., delete: bool = ... + ) -> IO[Any]: + ... + def SpooledTemporaryFile( + max_size: int = ..., mode: str = ..., buffering: int = ..., + encoding: str = ..., newline: str = ..., suffix: str = ..., + prefix: str = ..., dir: Optional[str] = ... + ) -> IO[Any]: + ... + + class TemporaryDirectory: + name = ... # type: str + def __init__(self, suffix: str = ..., prefix: str = ..., + dir: Optional[str] = ...) -> None: ... + def cleanup(self) -> None: ... + def __enter__(self) -> str: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType]) -> bool: ... + + def mkstemp(suffix: str = ..., prefix: str = ..., dir: Optional[str] = ..., + text: bool = ...) -> Tuple[int, str]: ... + def mkdtemp(suffix: str = ..., prefix: str = ..., + dir: Optional[str] = ...) -> str: ... + def mktemp(suffix: str = ..., prefix: str = ..., dir: Optional[str] = ...) -> str: ... + +def gettempdir() -> str: ... +def gettempprefix() -> str: ... diff --git a/client/typeshed-fallback/stdlib/3/textwrap.pyi b/client/typeshed-fallback/stdlib/3/textwrap.pyi new file mode 100644 index 000000000..f61f975bb --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/textwrap.pyi @@ -0,0 +1,113 @@ +from typing import Callable, List, Optional, Dict, Pattern + +class TextWrapper: + width: int = ... + initial_indent: str = ... + subsequent_indent: str = ... + expand_tabs: bool = ... + replace_whitespace: bool = ... + fix_sentence_endings: bool = ... + drop_whitespace: bool = ... + break_long_words: bool = ... + break_on_hyphens: bool = ... + tabsize: int = ... + max_lines: Optional[int] = ... + placeholder: str = ... + + # Attributes not present in documentation + sentence_end_re: Pattern[str] = ... + wordsep_re: Pattern[str] = ... + wordsep_simple_re: Pattern[str] = ... + whitespace_trans: str = ... + unicode_whitespace_trans: Dict[int, int] = ... + uspace: int = ... + x: int = ... + + def __init__( + self, + width: int = ..., + initial_indent: str = ..., + subsequent_indent: str = ..., + expand_tabs: bool = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + drop_whitespace: bool = ..., + break_on_hyphens: bool = ..., + tabsize: int = ..., + *, + max_lines: Optional[int] = ..., + placeholder: str = ...) -> None: + ... + + # Private methods *are* part of the documented API for subclasses. + def _munge_whitespace(self, text: str) -> str: ... + def _split(self, text: str) -> List[str]: ... + def _fix_sentence_endings(self, chunks: List[str]) -> None: ... + def _handle_long_word(self, reversed_chunks: List[str], cur_line: List[str], cur_len: int, width: int) -> None: ... + def _wrap_chunks(self, chunks: List[str]) -> List[str]: ... + def _split_chunks(self, text: str) -> List[str]: ... + + def wrap(self, text: str) -> List[str]: ... + def fill(self, text: str) -> str: ... + + +def wrap( + text: str = ..., + width: int = ..., + *, + initial_indent: str = ..., + subsequent_indent: str = ..., + expand_tabs: bool = ..., + tabsize: int = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + break_on_hyphens: bool = ..., + drop_whitespace: bool = ..., + max_lines: int = ..., + placeholder: str = ... +) -> List[str]: + ... + +def fill( + text: str, + width: int = ..., + *, + initial_indent: str = ..., + subsequent_indent: str = ..., + expand_tabs: bool = ..., + tabsize: int = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + break_on_hyphens: bool = ..., + drop_whitespace: bool = ..., + max_lines: int = ..., + placeholder: str = ... +) -> str: + ... + +def shorten( + text: str, + width: int, + *, + initial_indent: str = ..., + subsequent_indent: str = ..., + expand_tabs: bool = ..., + tabsize: int = ..., + replace_whitespace: bool = ..., + fix_sentence_endings: bool = ..., + break_long_words: bool = ..., + break_on_hyphens: bool = ..., + drop_whitespace: bool = ..., + # Omit `max_lines: int = None`, it is forced to 1 here. + placeholder: str = ... +) -> str: + ... + +def dedent(text: str) -> str: + ... + +def indent(text: str, prefix: str, predicate: Callable[[str], bool] = ...) -> str: + ... diff --git a/client/typeshed-fallback/stdlib/3/tkinter/__init__.pyi b/client/typeshed-fallback/stdlib/3/tkinter/__init__.pyi new file mode 100644 index 000000000..f0a457980 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/tkinter/__init__.pyi @@ -0,0 +1,663 @@ +from types import TracebackType +from typing import Any, Optional, Dict, Callable, Type +from tkinter.constants import * # noqa: F403 + +TclError = ... # type: Any +wantobjects = ... # type: Any +TkVersion = ... # type: Any +TclVersion = ... # type: Any +READABLE = ... # type: Any +WRITABLE = ... # type: Any +EXCEPTION = ... # type: Any + +class Event: ... + +def NoDefaultRoot(): ... + +class Variable: + def __init__(self, master: Optional[Any] = ..., value: Optional[Any] = ..., name: Optional[Any] = ...): ... + def __del__(self): ... + def set(self, value): ... + initialize = ... # type: Any + def get(self): ... + def trace_variable(self, mode, callback): ... + trace = ... # type: Any + def trace_vdelete(self, mode, cbname): ... + def trace_vinfo(self): ... + def __eq__(self, other): ... + +class StringVar(Variable): + def __init__(self, master: Optional[Any] = ..., value: Optional[Any] = ..., name: Optional[Any] = ...): ... + def get(self): ... + +class IntVar(Variable): + def __init__(self, master: Optional[Any] = ..., value: Optional[Any] = ..., name: Optional[Any] = ...): ... + def get(self): ... + +class DoubleVar(Variable): + def __init__(self, master: Optional[Any] = ..., value: Optional[Any] = ..., name: Optional[Any] = ...): ... + def get(self): ... + +class BooleanVar(Variable): + def __init__(self, master: Optional[Any] = ..., value: Optional[Any] = ..., name: Optional[Any] = ...): ... + def set(self, value): ... + initialize = ... # type: Any + def get(self): ... + +def mainloop(n: int = ...): ... + +getint = ... # type: Any +getdouble = ... # type: Any + +def getboolean(s): ... + +class Misc: + def destroy(self): ... + def deletecommand(self, name): ... + def tk_strictMotif(self, boolean: Optional[Any] = ...): ... + def tk_bisque(self): ... + def tk_setPalette(self, *args, **kw): ... + def tk_menuBar(self, *args): ... + def wait_variable(self, name: str = ...): ... + waitvar = ... # type: Any + def wait_window(self, window: Optional[Any] = ...): ... + def wait_visibility(self, window: Optional[Any] = ...): ... + def setvar(self, name: str = ..., value: str = ...): ... + def getvar(self, name: str = ...): ... + def getint(self, s): ... + def getdouble(self, s): ... + def getboolean(self, s): ... + def focus_set(self): ... + focus = ... # type: Any + def focus_force(self): ... + def focus_get(self): ... + def focus_displayof(self): ... + def focus_lastfor(self): ... + def tk_focusFollowsMouse(self): ... + def tk_focusNext(self): ... + def tk_focusPrev(self): ... + def after(self, ms, func: Optional[Any] = ..., *args): ... + def after_idle(self, func, *args): ... + def after_cancel(self, id): ... + def bell(self, displayof: int = ...): ... + def clipboard_get(self, **kw): ... + def clipboard_clear(self, **kw): ... + def clipboard_append(self, string, **kw): ... + def grab_current(self): ... + def grab_release(self): ... + def grab_set(self): ... + def grab_set_global(self): ... + def grab_status(self): ... + def option_add(self, pattern, value, priority: Optional[Any] = ...): ... + def option_clear(self): ... + def option_get(self, name, className): ... + def option_readfile(self, fileName, priority: Optional[Any] = ...): ... + def selection_clear(self, **kw): ... + def selection_get(self, **kw): ... + def selection_handle(self, command, **kw): ... + def selection_own(self, **kw): ... + def selection_own_get(self, **kw): ... + def send(self, interp, cmd, *args): ... + def lower(self, belowThis: Optional[Any] = ...): ... + def tkraise(self, aboveThis: Optional[Any] = ...): ... + lift = ... # type: Any + def winfo_atom(self, name, displayof: int = ...): ... + def winfo_atomname(self, id, displayof: int = ...): ... + def winfo_cells(self): ... + def winfo_children(self): ... + def winfo_class(self): ... + def winfo_colormapfull(self): ... + def winfo_containing(self, rootX, rootY, displayof: int = ...): ... + def winfo_depth(self): ... + def winfo_exists(self): ... + def winfo_fpixels(self, number): ... + def winfo_geometry(self): ... + def winfo_height(self): ... + def winfo_id(self): ... + def winfo_interps(self, displayof: int = ...): ... + def winfo_ismapped(self): ... + def winfo_manager(self): ... + def winfo_name(self): ... + def winfo_parent(self): ... + def winfo_pathname(self, id, displayof: int = ...): ... + def winfo_pixels(self, number): ... + def winfo_pointerx(self): ... + def winfo_pointerxy(self): ... + def winfo_pointery(self): ... + def winfo_reqheight(self): ... + def winfo_reqwidth(self): ... + def winfo_rgb(self, color): ... + def winfo_rootx(self): ... + def winfo_rooty(self): ... + def winfo_screen(self): ... + def winfo_screencells(self): ... + def winfo_screendepth(self): ... + def winfo_screenheight(self): ... + def winfo_screenmmheight(self): ... + def winfo_screenmmwidth(self): ... + def winfo_screenvisual(self): ... + def winfo_screenwidth(self): ... + def winfo_server(self): ... + def winfo_toplevel(self): ... + def winfo_viewable(self): ... + def winfo_visual(self): ... + def winfo_visualid(self): ... + def winfo_visualsavailable(self, includeids: int = ...): ... + def winfo_vrootheight(self): ... + def winfo_vrootwidth(self): ... + def winfo_vrootx(self): ... + def winfo_vrooty(self): ... + def winfo_width(self): ... + def winfo_x(self): ... + def winfo_y(self): ... + def update(self): ... + def update_idletasks(self): ... + def bindtags(self, tagList: Optional[Any] = ...): ... + def bind(self, sequence: Optional[Any] = ..., func: Optional[Any] = ..., add: Optional[Any] = ...): ... + def unbind(self, sequence, funcid: Optional[Any] = ...): ... + def bind_all(self, sequence: Optional[Any] = ..., func: Optional[Any] = ..., add: Optional[Any] = ...): ... + def unbind_all(self, sequence): ... + def bind_class(self, className, sequence: Optional[Any] = ..., func: Optional[Any] = ..., add: Optional[Any] = ...): ... + def unbind_class(self, className, sequence): ... + def mainloop(self, n: int = ...): ... + def quit(self): ... + def nametowidget(self, name): ... + register = ... # type: Any + def configure(self, cnf: Optional[Any] = ..., **kw): ... + config = ... # type: Any + def cget(self, key): ... + __getitem__ = ... # type: Any + def __setitem__(self, key, value): ... + def keys(self): ... + def pack_propagate(self, flag=...): ... + propagate = ... # type: Any + def pack_slaves(self): ... + slaves = ... # type: Any + def place_slaves(self): ... + def grid_anchor(self, anchor: Optional[Any] = ...): ... + anchor = ... # type: Any + def grid_bbox(self, column: Optional[Any] = ..., row: Optional[Any] = ..., col2: Optional[Any] = ..., + row2: Optional[Any] = ...): ... + bbox = ... # type: Any + def grid_columnconfigure(self, index, cnf=..., **kw): ... + columnconfigure = ... # type: Any + def grid_location(self, x, y): ... + def grid_propagate(self, flag=...): ... + def grid_rowconfigure(self, index, cnf=..., **kw): ... + rowconfigure = ... # type: Any + def grid_size(self): ... + size = ... # type: Any + def grid_slaves(self, row: Optional[Any] = ..., column: Optional[Any] = ...): ... + def event_add(self, virtual, *sequences): ... + def event_delete(self, virtual, *sequences): ... + def event_generate(self, sequence, **kw): ... + def event_info(self, virtual: Optional[Any] = ...): ... + def image_names(self): ... + def image_types(self): ... + +class CallWrapper: + func = ... # type: Any + subst = ... # type: Any + widget = ... # type: Any + def __init__(self, func, subst, widget): ... + def __call__(self, *args): ... + +class XView: + def xview(self, *args): ... + def xview_moveto(self, fraction): ... + def xview_scroll(self, number, what): ... + +class YView: + def yview(self, *args): ... + def yview_moveto(self, fraction): ... + def yview_scroll(self, number, what): ... + +class Wm: + def wm_aspect(self, minNumer: Optional[Any] = ..., minDenom: Optional[Any] = ..., maxNumer: Optional[Any] = ..., + maxDenom: Optional[Any] = ...): ... + aspect = ... # type: Any + def wm_attributes(self, *args): ... + attributes = ... # type: Any + def wm_client(self, name: Optional[Any] = ...): ... + client = ... # type: Any + def wm_colormapwindows(self, *wlist): ... + colormapwindows = ... # type: Any + def wm_command(self, value: Optional[Any] = ...): ... + command = ... # type: Any + def wm_deiconify(self): ... + deiconify = ... # type: Any + def wm_focusmodel(self, model: Optional[Any] = ...): ... + focusmodel = ... # type: Any + def wm_forget(self, window): ... + forget = ... # type: Any + def wm_frame(self): ... + frame = ... # type: Any + def wm_geometry(self, newGeometry: Optional[Any] = ...): ... + geometry = ... # type: Any + def wm_grid(self, baseWidth: Optional[Any] = ..., baseHeight: Optional[Any] = ..., widthInc: Optional[Any] = ..., + heightInc: Optional[Any] = ...): ... + grid = ... # type: Any + def wm_group(self, pathName: Optional[Any] = ...): ... + group = ... # type: Any + def wm_iconbitmap(self, bitmap: Optional[Any] = ..., default: Optional[Any] = ...): ... + iconbitmap = ... # type: Any + def wm_iconify(self): ... + iconify = ... # type: Any + def wm_iconmask(self, bitmap: Optional[Any] = ...): ... + iconmask = ... # type: Any + def wm_iconname(self, newName: Optional[Any] = ...): ... + iconname = ... # type: Any + def wm_iconphoto(self, default: bool = ..., *args): ... + iconphoto = ... # type: Any + def wm_iconposition(self, x: Optional[Any] = ..., y: Optional[Any] = ...): ... + iconposition = ... # type: Any + def wm_iconwindow(self, pathName: Optional[Any] = ...): ... + iconwindow = ... # type: Any + def wm_manage(self, widget): ... + manage = ... # type: Any + def wm_maxsize(self, width: Optional[Any] = ..., height: Optional[Any] = ...): ... + maxsize = ... # type: Any + def wm_minsize(self, width: Optional[Any] = ..., height: Optional[Any] = ...): ... + minsize = ... # type: Any + def wm_overrideredirect(self, boolean: Optional[Any] = ...): ... + overrideredirect = ... # type: Any + def wm_positionfrom(self, who: Optional[Any] = ...): ... + positionfrom = ... # type: Any + def wm_protocol(self, name: Optional[Any] = ..., func: Optional[Any] = ...): ... + protocol = ... # type: Any + def wm_resizable(self, width: Optional[Any] = ..., height: Optional[Any] = ...): ... + resizable = ... # type: Any + def wm_sizefrom(self, who: Optional[Any] = ...): ... + sizefrom = ... # type: Any + def wm_state(self, newstate: Optional[Any] = ...): ... + state = ... # type: Any + def wm_title(self, string: Optional[Any] = ...): ... + title = ... # type: Any + def wm_transient(self, master: Optional[Any] = ...): ... + transient = ... # type: Any + def wm_withdraw(self): ... + withdraw = ... # type: Any + +class Tk(Misc, Wm): + master: Optional[Any] + children: Dict[str, Any] + tk: Any + def __init__(self, screenName: Optional[str] = ..., baseName: Optional[str] = ..., className: str = ..., useTk: bool = ..., + sync: bool = ..., use: Optional[str] = ...) -> None: ... + def loadtk(self) -> None: ... + def destroy(self) -> None: ... + def readprofile(self, baseName: str, className: str) -> None: ... + report_callback_exception: Callable[[Type[BaseException], BaseException, TracebackType], Any] + def __getattr__(self, attr: str) -> Any: ... + +def Tcl(screenName: Optional[Any] = ..., baseName: Optional[Any] = ..., className: str = ..., useTk: bool = ...): ... + +class Pack: + def pack_configure(self, cnf=..., **kw): ... + pack = ... # type: Any + def pack_forget(self): ... + forget = ... # type: Any + def pack_info(self): ... + info = ... # type: Any + propagate = ... # type: Any + slaves = ... # type: Any + +class Place: + def place_configure(self, cnf=..., **kw): ... + place = ... # type: Any + def place_forget(self): ... + forget = ... # type: Any + def place_info(self): ... + info = ... # type: Any + slaves = ... # type: Any + +class Grid: + def grid_configure(self, cnf=..., **kw): ... + grid = ... # type: Any + bbox = ... # type: Any + columnconfigure = ... # type: Any + def grid_forget(self): ... + forget = ... # type: Any + def grid_remove(self): ... + def grid_info(self): ... + info = ... # type: Any + location = ... # type: Any + propagate = ... # type: Any + rowconfigure = ... # type: Any + size = ... # type: Any + slaves = ... # type: Any + +class BaseWidget(Misc): + widgetName = ... # type: Any + def __init__(self, master, widgetName, cnf=..., kw=..., extra=...): ... + def destroy(self): ... + +class Widget(BaseWidget, Pack, Place, Grid): ... + +class Toplevel(BaseWidget, Wm): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + +class Button(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def flash(self): ... + def invoke(self): ... + +class Canvas(Widget, XView, YView): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def addtag(self, *args): ... + def addtag_above(self, newtag, tagOrId): ... + def addtag_all(self, newtag): ... + def addtag_below(self, newtag, tagOrId): ... + def addtag_closest(self, newtag, x, y, halo: Optional[Any] = ..., start: Optional[Any] = ...): ... + def addtag_enclosed(self, newtag, x1, y1, x2, y2): ... + def addtag_overlapping(self, newtag, x1, y1, x2, y2): ... + def addtag_withtag(self, newtag, tagOrId): ... + def bbox(self, *args): ... + def tag_unbind(self, tagOrId, sequence, funcid: Optional[Any] = ...): ... + def tag_bind(self, tagOrId, sequence: Optional[Any] = ..., func: Optional[Any] = ..., add: Optional[Any] = ...): ... + def canvasx(self, screenx, gridspacing: Optional[Any] = ...): ... + def canvasy(self, screeny, gridspacing: Optional[Any] = ...): ... + def coords(self, *args): ... + def create_arc(self, *args, **kw): ... + def create_bitmap(self, *args, **kw): ... + def create_image(self, *args, **kw): ... + def create_line(self, *args, **kw): ... + def create_oval(self, *args, **kw): ... + def create_polygon(self, *args, **kw): ... + def create_rectangle(self, *args, **kw): ... + def create_text(self, *args, **kw): ... + def create_window(self, *args, **kw): ... + def dchars(self, *args): ... + def delete(self, *args): ... + def dtag(self, *args): ... + def find(self, *args): ... + def find_above(self, tagOrId): ... + def find_all(self): ... + def find_below(self, tagOrId): ... + def find_closest(self, x, y, halo: Optional[Any] = ..., start: Optional[Any] = ...): ... + def find_enclosed(self, x1, y1, x2, y2): ... + def find_overlapping(self, x1, y1, x2, y2): ... + def find_withtag(self, tagOrId): ... + def focus(self, *args): ... + def gettags(self, *args): ... + def icursor(self, *args): ... + def index(self, *args): ... + def insert(self, *args): ... + def itemcget(self, tagOrId, option): ... + def itemconfigure(self, tagOrId, cnf: Optional[Any] = ..., **kw): ... + itemconfig = ... # type: Any + def tag_lower(self, *args): ... + lower = ... # type: Any + def move(self, *args): ... + def postscript(self, cnf=..., **kw): ... + def tag_raise(self, *args): ... + lift = ... # type: Any + def scale(self, *args): ... + def scan_mark(self, x, y): ... + def scan_dragto(self, x, y, gain: int = ...): ... + def select_adjust(self, tagOrId, index): ... + def select_clear(self): ... + def select_from(self, tagOrId, index): ... + def select_item(self): ... + def select_to(self, tagOrId, index): ... + def type(self, tagOrId): ... + +class Checkbutton(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def deselect(self): ... + def flash(self): ... + def invoke(self): ... + def select(self): ... + def toggle(self): ... + +class Entry(Widget, XView): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def delete(self, first, last: Optional[Any] = ...): ... + def get(self): ... + def icursor(self, index): ... + def index(self, index): ... + def insert(self, index, string): ... + def scan_mark(self, x): ... + def scan_dragto(self, x): ... + def selection_adjust(self, index): ... + select_adjust = ... # type: Any + def selection_clear(self): ... + select_clear = ... # type: Any + def selection_from(self, index): ... + select_from = ... # type: Any + def selection_present(self): ... + select_present = ... # type: Any + def selection_range(self, start, end): ... + select_range = ... # type: Any + def selection_to(self, index): ... + select_to = ... # type: Any + +class Frame(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + +class Label(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + +class Listbox(Widget, XView, YView): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def activate(self, index): ... + def bbox(self, index): ... + def curselection(self): ... + def delete(self, first, last: Optional[Any] = ...): ... + def get(self, first, last: Optional[Any] = ...): ... + def index(self, index): ... + def insert(self, index, *elements): ... + def nearest(self, y): ... + def scan_mark(self, x, y): ... + def scan_dragto(self, x, y): ... + def see(self, index): ... + def selection_anchor(self, index): ... + select_anchor = ... # type: Any + def selection_clear(self, first, last: Optional[Any] = ...): ... # type: ignore + select_clear = ... # type: Any + def selection_includes(self, index): ... + select_includes = ... # type: Any + def selection_set(self, first, last: Optional[Any] = ...): ... + select_set = ... # type: Any + def size(self): ... + def itemcget(self, index, option): ... + def itemconfigure(self, index, cnf: Optional[Any] = ..., **kw): ... + itemconfig = ... # type: Any + +class Menu(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def tk_popup(self, x, y, entry: str = ...): ... + def tk_bindForTraversal(self): ... + def activate(self, index): ... + def add(self, itemType, cnf=..., **kw): ... + def add_cascade(self, cnf=..., **kw): ... + def add_checkbutton(self, cnf=..., **kw): ... + def add_command(self, cnf=..., **kw): ... + def add_radiobutton(self, cnf=..., **kw): ... + def add_separator(self, cnf=..., **kw): ... + def insert(self, index, itemType, cnf=..., **kw): ... + def insert_cascade(self, index, cnf=..., **kw): ... + def insert_checkbutton(self, index, cnf=..., **kw): ... + def insert_command(self, index, cnf=..., **kw): ... + def insert_radiobutton(self, index, cnf=..., **kw): ... + def insert_separator(self, index, cnf=..., **kw): ... + def delete(self, index1, index2: Optional[Any] = ...): ... + def entrycget(self, index, option): ... + def entryconfigure(self, index, cnf: Optional[Any] = ..., **kw): ... + entryconfig = ... # type: Any + def index(self, index): ... + def invoke(self, index): ... + def post(self, x, y): ... + def type(self, index): ... + def unpost(self): ... + def xposition(self, index): ... + def yposition(self, index): ... + +class Menubutton(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + +class Message(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + +class Radiobutton(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def deselect(self): ... + def flash(self): ... + def invoke(self): ... + def select(self): ... + +class Scale(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def get(self): ... + def set(self, value): ... + def coords(self, value: Optional[Any] = ...): ... + def identify(self, x, y): ... + +class Scrollbar(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def activate(self, index: Optional[Any] = ...): ... + def delta(self, deltax, deltay): ... + def fraction(self, x, y): ... + def identify(self, x, y): ... + def get(self): ... + def set(self, first, last): ... + +class Text(Widget, XView, YView): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def bbox(self, index): ... + def compare(self, index1, op, index2): ... + def count(self, index1, index2, *args): ... + def debug(self, boolean: Optional[Any] = ...): ... + def delete(self, index1, index2: Optional[Any] = ...): ... + def dlineinfo(self, index): ... + def dump(self, index1, index2: Optional[Any] = ..., command: Optional[Any] = ..., **kw): ... + def edit(self, *args): ... + def edit_modified(self, arg: Optional[Any] = ...): ... + def edit_redo(self): ... + def edit_reset(self): ... + def edit_separator(self): ... + def edit_undo(self): ... + def get(self, index1, index2: Optional[Any] = ...): ... + def image_cget(self, index, option): ... + def image_configure(self, index, cnf: Optional[Any] = ..., **kw): ... + def image_create(self, index, cnf=..., **kw): ... + def image_names(self): ... + def index(self, index): ... + def insert(self, index, chars, *args): ... + def mark_gravity(self, markName, direction: Optional[Any] = ...): ... + def mark_names(self): ... + def mark_set(self, markName, index): ... + def mark_unset(self, *markNames): ... + def mark_next(self, index): ... + def mark_previous(self, index): ... + def peer_create(self, newPathName, cnf=..., **kw): ... + def peer_names(self): ... + def replace(self, index1, index2, chars, *args): ... + def scan_mark(self, x, y): ... + def scan_dragto(self, x, y): ... + def search(self, pattern, index, stopindex: Optional[Any] = ..., forwards: Optional[Any] = ..., + backwards: Optional[Any] = ..., exact: Optional[Any] = ..., regexp: Optional[Any] = ..., + nocase: Optional[Any] = ..., count: Optional[Any] = ..., elide: Optional[Any] = ...): ... + def see(self, index): ... + def tag_add(self, tagName, index1, *args): ... + def tag_unbind(self, tagName, sequence, funcid: Optional[Any] = ...): ... + def tag_bind(self, tagName, sequence, func, add: Optional[Any] = ...): ... + def tag_cget(self, tagName, option): ... + def tag_configure(self, tagName, cnf: Optional[Any] = ..., **kw): ... + tag_config = ... # type: Any + def tag_delete(self, *tagNames): ... + def tag_lower(self, tagName, belowThis: Optional[Any] = ...): ... + def tag_names(self, index: Optional[Any] = ...): ... + def tag_nextrange(self, tagName, index1, index2: Optional[Any] = ...): ... + def tag_prevrange(self, tagName, index1, index2: Optional[Any] = ...): ... + def tag_raise(self, tagName, aboveThis: Optional[Any] = ...): ... + def tag_ranges(self, tagName): ... + def tag_remove(self, tagName, index1, index2: Optional[Any] = ...): ... + def window_cget(self, index, option): ... + def window_configure(self, index, cnf: Optional[Any] = ..., **kw): ... + window_config = ... # type: Any + def window_create(self, index, cnf=..., **kw): ... + def window_names(self): ... + def yview_pickplace(self, *what): ... + +class _setit: + def __init__(self, var, value, callback: Optional[Any] = ...): ... + def __call__(self, *args): ... + +class OptionMenu(Menubutton): + widgetName = ... # type: Any + menuname = ... # type: Any + def __init__(self, master, variable, value, *values, **kwargs): ... + def __getitem__(self, name): ... + def destroy(self): ... + +class Image: + name = ... # type: Any + tk = ... # type: Any + def __init__(self, imgtype, name: Optional[Any] = ..., cnf=..., master: Optional[Any] = ..., **kw): ... + def __del__(self): ... + def __setitem__(self, key, value): ... + def __getitem__(self, key): ... + def configure(self, **kw): ... + config = ... # type: Any + def height(self): ... + def type(self): ... + def width(self): ... + +class PhotoImage(Image): + def __init__(self, name: Optional[Any] = ..., cnf=..., master: Optional[Any] = ..., **kw): ... + def blank(self): ... + def cget(self, option): ... + def __getitem__(self, key): ... + def copy(self): ... + def zoom(self, x, y: str = ...): ... + def subsample(self, x, y: str = ...): ... + def get(self, x, y): ... + def put(self, data, to: Optional[Any] = ...): ... + def write(self, filename, format: Optional[Any] = ..., from_coords: Optional[Any] = ...): ... + +class BitmapImage(Image): + def __init__(self, name: Optional[Any] = ..., cnf=..., master: Optional[Any] = ..., **kw): ... + +def image_names(): ... +def image_types(): ... + +class Spinbox(Widget, XView): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def bbox(self, index): ... + def delete(self, first, last: Optional[Any] = ...): ... + def get(self): ... + def icursor(self, index): ... + def identify(self, x, y): ... + def index(self, index): ... + def insert(self, index, s): ... + def invoke(self, element): ... + def scan(self, *args): ... + def scan_mark(self, x): ... + def scan_dragto(self, x): ... + def selection(self, *args): ... + def selection_adjust(self, index): ... + def selection_clear(self): ... + def selection_element(self, element: Optional[Any] = ...): ... + +class LabelFrame(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + +class PanedWindow(Widget): + def __init__(self, master: Optional[Any] = ..., cnf=..., **kw): ... + def add(self, child, **kw): ... + def remove(self, child): ... + forget = ... # type: Any + def identify(self, x, y): ... + def proxy(self, *args): ... + def proxy_coord(self): ... + def proxy_forget(self): ... + def proxy_place(self, x, y): ... + def sash(self, *args): ... + def sash_coord(self, index): ... + def sash_mark(self, index): ... + def sash_place(self, index, x, y): ... + def panecget(self, child, option): ... + def paneconfigure(self, tagOrId, cnf: Optional[Any] = ..., **kw): ... + paneconfig = ... # type: Any + def panes(self): ... diff --git a/client/typeshed-fallback/stdlib/3/tkinter/commondialog.pyi b/client/typeshed-fallback/stdlib/3/tkinter/commondialog.pyi new file mode 100644 index 000000000..d6a8a0d1f --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/tkinter/commondialog.pyi @@ -0,0 +1,8 @@ +from typing import Any, Mapping, Optional + +class Dialog: + command: Optional[Any] = ... + master: Optional[Any] = ... + options: Mapping[str, Any] = ... + def __init__(self, master: Optional[Any] = ..., **options) -> None: ... + def show(self, **options) -> Any: ... diff --git a/client/typeshed-fallback/stdlib/3/tkinter/constants.pyi b/client/typeshed-fallback/stdlib/3/tkinter/constants.pyi new file mode 100644 index 000000000..d613dc628 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/tkinter/constants.pyi @@ -0,0 +1,79 @@ +from typing import Any + +NO = ... # type: Any +YES = ... # type: Any +TRUE = ... # type: Any +FALSE = ... # type: Any +ON = ... # type: Any +OFF = ... # type: Any +N = ... # type: Any +S = ... # type: Any +W = ... # type: Any +E = ... # type: Any +NW = ... # type: Any +SW = ... # type: Any +NE = ... # type: Any +SE = ... # type: Any +NS = ... # type: Any +EW = ... # type: Any +NSEW = ... # type: Any +CENTER = ... # type: Any +NONE = ... # type: Any +X = ... # type: Any +Y = ... # type: Any +BOTH = ... # type: Any +LEFT = ... # type: Any +TOP = ... # type: Any +RIGHT = ... # type: Any +BOTTOM = ... # type: Any +RAISED = ... # type: Any +SUNKEN = ... # type: Any +FLAT = ... # type: Any +RIDGE = ... # type: Any +GROOVE = ... # type: Any +SOLID = ... # type: Any +HORIZONTAL = ... # type: Any +VERTICAL = ... # type: Any +NUMERIC = ... # type: Any +CHAR = ... # type: Any +WORD = ... # type: Any +BASELINE = ... # type: Any +INSIDE = ... # type: Any +OUTSIDE = ... # type: Any +SEL = ... # type: Any +SEL_FIRST = ... # type: Any +SEL_LAST = ... # type: Any +END = ... # type: Any +INSERT = ... # type: Any +CURRENT = ... # type: Any +ANCHOR = ... # type: Any +ALL = ... # type: Any +NORMAL = ... # type: Any +DISABLED = ... # type: Any +ACTIVE = ... # type: Any +HIDDEN = ... # type: Any +CASCADE = ... # type: Any +CHECKBUTTON = ... # type: Any +COMMAND = ... # type: Any +RADIOBUTTON = ... # type: Any +SEPARATOR = ... # type: Any +SINGLE = ... # type: Any +BROWSE = ... # type: Any +MULTIPLE = ... # type: Any +EXTENDED = ... # type: Any +DOTBOX = ... # type: Any +UNDERLINE = ... # type: Any +PIESLICE = ... # type: Any +CHORD = ... # type: Any +ARC = ... # type: Any +FIRST = ... # type: Any +LAST = ... # type: Any +BUTT = ... # type: Any +PROJECTING = ... # type: Any +ROUND = ... # type: Any +BEVEL = ... # type: Any +MITER = ... # type: Any +MOVETO = ... # type: Any +SCROLL = ... # type: Any +UNITS = ... # type: Any +PAGES = ... # type: Any diff --git a/client/typeshed-fallback/stdlib/3/tkinter/dialog.pyi b/client/typeshed-fallback/stdlib/3/tkinter/dialog.pyi new file mode 100644 index 000000000..3136f21e6 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/tkinter/dialog.pyi @@ -0,0 +1,10 @@ +from typing import Any, Mapping, Optional +from tkinter import Widget + +DIALOG_ICON: str + +class Dialog(Widget): + widgetName: str = ... + num: int = ... + def __init__(self, master: Optional[Any] = ..., cnf: Mapping[str, Any] = ..., **kw) -> None: ... + def destroy(self) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/tkinter/filedialog.pyi b/client/typeshed-fallback/stdlib/3/tkinter/filedialog.pyi new file mode 100644 index 000000000..6d5f16513 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/tkinter/filedialog.pyi @@ -0,0 +1,65 @@ +from typing import Any, Dict, Optional, Tuple +from tkinter import Button, commondialog, Entry, Frame, Listbox, Scrollbar, Toplevel + +dialogstates: Dict[Any, Tuple[Any, Any]] + +class FileDialog: + title: str = ... + master: Any = ... + directory: Optional[Any] = ... + top: Toplevel = ... + botframe: Frame = ... + selection: Entry = ... + filter: Entry = ... + midframe: Entry = ... + filesbar: Scrollbar = ... + files: Listbox = ... + dirsbar: Scrollbar = ... + dirs: Listbox = ... + ok_button: Button = ... + filter_button: Button = ... + cancel_button: Button = ... + def __init__(self, master, title: Optional[Any] = ...) -> None: ... # title is usually a str or None, but e.g. int doesn't raise en exception either + how: Optional[Any] = ... + def go(self, dir_or_file: Any = ..., pattern: str = ..., default: str = ..., key: Optional[Any] = ...): ... + def quit(self, how: Optional[Any] = ...) -> None: ... + def dirs_double_event(self, event) -> None: ... + def dirs_select_event(self, event) -> None: ... + def files_double_event(self, event) -> None: ... + def files_select_event(self, event) -> None: ... + def ok_event(self, event) -> None: ... + def ok_command(self) -> None: ... + def filter_command(self, event: Optional[Any] = ...) -> None: ... + def get_filter(self): ... + def get_selection(self): ... + def cancel_command(self, event: Optional[Any] = ...) -> None: ... + def set_filter(self, dir, pat) -> None: ... + def set_selection(self, file) -> None: ... + +class LoadFileDialog(FileDialog): + title: str = ... + def ok_command(self) -> None: ... + +class SaveFileDialog(FileDialog): + title: str = ... + def ok_command(self): ... + +class _Dialog(commondialog.Dialog): ... + +class Open(_Dialog): + command: str = ... + +class SaveAs(_Dialog): + command: str = ... + +class Directory(commondialog.Dialog): + command: str = ... + +def askopenfilename(**options): ... +def asksaveasfilename(**options): ... +def askopenfilenames(**options): ... +def askopenfile(mode: str = ..., **options): ... +def askopenfiles(mode: str = ..., **options): ... +def asksaveasfile(mode: str = ..., **options): ... +def askdirectory(**options): ... +def test() -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/tkinter/messagebox.pyi b/client/typeshed-fallback/stdlib/3/tkinter/messagebox.pyi new file mode 100644 index 000000000..b44e66081 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/tkinter/messagebox.pyi @@ -0,0 +1,31 @@ +from tkinter.commondialog import Dialog +from typing import Any, Optional + +ERROR: str +INFO: str +QUESTION: str +WARNING: str +ABORTRETRYIGNORE: str +OK: str +OKCANCEL: str +RETRYCANCEL: str +YESNO: str +YESNOCANCEL: str +ABORT: str +RETRY: str +IGNORE: str +CANCEL: str +YES: str +NO: str + +class Message(Dialog): + command: str = ... + +def showinfo(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> str: ... +def showwarning(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> str: ... +def showerror(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> str: ... +def askquestion(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> str: ... +def askokcancel(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> bool: ... +def askyesno(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> bool: ... +def askyesnocancel(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> Optional[bool]: ... +def askretrycancel(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> bool: ... diff --git a/client/typeshed-fallback/stdlib/3/tkinter/ttk.pyi b/client/typeshed-fallback/stdlib/3/tkinter/ttk.pyi new file mode 100644 index 000000000..8e690c473 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/tkinter/ttk.pyi @@ -0,0 +1,160 @@ +import sys +from typing import Any, Optional +import tkinter + +def tclobjs_to_py(adict): ... +def setup_master(master: Optional[Any] = ...): ... + +class Style: + master = ... # type: Any + tk = ... # type: Any + def __init__(self, master: Optional[Any] = ...): ... + def configure(self, style, query_opt: Optional[Any] = ..., **kw): ... + def map(self, style, query_opt: Optional[Any] = ..., **kw): ... + def lookup(self, style, option, state: Optional[Any] = ..., default: Optional[Any] = ...): ... + def layout(self, style, layoutspec: Optional[Any] = ...): ... + def element_create(self, elementname, etype, *args, **kw): ... + def element_names(self): ... + def element_options(self, elementname): ... + def theme_create(self, themename, parent: Optional[Any] = ..., settings: Optional[Any] = ...): ... + def theme_settings(self, themename, settings): ... + def theme_names(self): ... + def theme_use(self, themename: Optional[Any] = ...): ... + +class Widget(tkinter.Widget): + def __init__(self, master, widgetname, kw: Optional[Any] = ...): ... + def identify(self, x, y): ... + def instate(self, statespec, callback: Optional[Any] = ..., *args, **kw): ... + def state(self, statespec: Optional[Any] = ...): ... + +class Button(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + def invoke(self): ... + +class Checkbutton(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + def invoke(self): ... + +class Entry(Widget, tkinter.Entry): + def __init__(self, master: Optional[Any] = ..., widget: Optional[Any] = ..., **kw): ... + def bbox(self, index): ... + def identify(self, x, y): ... + def validate(self): ... + +class Combobox(Entry): + def __init__(self, master: Optional[Any] = ..., **kw): ... + def current(self, newindex: Optional[Any] = ...): ... + def set(self, value): ... + +class Frame(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + +class Label(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + +class Labelframe(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + +LabelFrame = ... # type: Any + +class Menubutton(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + +class Notebook(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + def add(self, child, **kw): ... + def forget(self, tab_id): ... + def hide(self, tab_id): ... + def identify(self, x, y): ... + def index(self, tab_id): ... + def insert(self, pos, child, **kw): ... + def select(self, tab_id: Optional[Any] = ...): ... + def tab(self, tab_id, option: Optional[Any] = ..., **kw): ... + def tabs(self): ... + def enable_traversal(self): ... + +class Panedwindow(Widget, tkinter.PanedWindow): + def __init__(self, master: Optional[Any] = ..., **kw): ... + forget = ... # type: Any + def insert(self, pos, child, **kw): ... + def pane(self, pane, option: Optional[Any] = ..., **kw): ... + def sashpos(self, index, newpos: Optional[Any] = ...): ... + +PanedWindow = ... # type: Any + +class Progressbar(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + def start(self, interval: Optional[Any] = ...): ... + def step(self, amount: Optional[Any] = ...): ... + def stop(self): ... + +class Radiobutton(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + def invoke(self): ... + +class Scale(Widget, tkinter.Scale): + def __init__(self, master: Optional[Any] = ..., **kw): ... + def configure(self, cnf: Optional[Any] = ..., **kw): ... + def get(self, x: Optional[Any] = ..., y: Optional[Any] = ...): ... + +class Scrollbar(Widget, tkinter.Scrollbar): + def __init__(self, master: Optional[Any] = ..., **kw): ... + +class Separator(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + +class Sizegrip(Widget): + def __init__(self, master: Optional[Any] = ..., **kw): ... + +if sys.version_info >= (3, 7): + class Spinbox(Entry): + def __init__(self, master: Any = ..., **kw: Any) -> None: ... + def set(self, value: Any) -> None: ... + +class Treeview(Widget, tkinter.XView, tkinter.YView): + def __init__(self, master: Optional[Any] = ..., **kw): ... + def bbox(self, item, column: Optional[Any] = ...): ... + def get_children(self, item: Optional[Any] = ...): ... + def set_children(self, item, *newchildren): ... + def column(self, column, option: Optional[Any] = ..., **kw): ... + def delete(self, *items): ... + def detach(self, *items): ... + def exists(self, item): ... + def focus(self, item: Optional[Any] = ...): ... + def heading(self, column, option: Optional[Any] = ..., **kw): ... + def identify(self, component, x, y): ... + def identify_row(self, y): ... + def identify_column(self, x): ... + def identify_region(self, x, y): ... + def identify_element(self, x, y): ... + def index(self, item): ... + def insert(self, parent, index, iid: Optional[Any] = ..., **kw): ... + def item(self, item, option: Optional[Any] = ..., **kw): ... + def move(self, item, parent, index): ... + reattach = ... # type: Any + def next(self, item): ... + def parent(self, item): ... + def prev(self, item): ... + def see(self, item): ... + def selection(self, selop: Optional[Any] = ..., items: Optional[Any] = ...): ... + def selection_set(self, items): ... + def selection_add(self, items): ... + def selection_remove(self, items): ... + def selection_toggle(self, items): ... + def set(self, item, column: Optional[Any] = ..., value: Optional[Any] = ...): ... + def tag_bind(self, tagname, sequence: Optional[Any] = ..., callback: Optional[Any] = ...): ... + def tag_configure(self, tagname, option: Optional[Any] = ..., **kw): ... + def tag_has(self, tagname, item: Optional[Any] = ...): ... + +class LabeledScale(Frame): + label = ... # type: Any + scale = ... # type: Any + def __init__(self, master: Optional[Any] = ..., variable: Optional[Any] = ..., from_: int = ..., to: int = ..., **kw): ... + def destroy(self): ... + value = ... # type: Any + +class OptionMenu(Menubutton): + def __init__(self, master, variable, default: Optional[Any] = ..., *values, **kwargs): ... + def __getitem__(self, item): ... + def set_menu(self, default: Optional[Any] = ..., *values): ... + def destroy(self): ... diff --git a/client/typeshed-fallback/stdlib/3/tokenize.pyi b/client/typeshed-fallback/stdlib/3/tokenize.pyi new file mode 100644 index 000000000..7a17ca2c2 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/tokenize.pyi @@ -0,0 +1,114 @@ +from typing import Any, Callable, Generator, Iterable, List, NamedTuple, Optional, Union, Sequence, TextIO, Tuple +from builtins import open as _builtin_open +import sys +from token import * # noqa: F403 + +COMMENT = ... # type: int +NL = ... # type: int +ENCODING = ... # type: int + +_Position = Tuple[int, int] + +_TokenInfo = NamedTuple('TokenInfo', [ + ('type', int), + ('string', str), + ('start', _Position), + ('end', _Position), + ('line', str) +]) + +class TokenInfo(_TokenInfo): + @property + def exact_type(self) -> int: ... + +# Backwards compatible tokens can be sequences of a shorter length too +_Token = Union[TokenInfo, Sequence[Union[int, str, _Position]]] + +class TokenError(Exception): ... +class StopTokenizing(Exception): ... + +class Untokenizer: + tokens = ... # type: List[str] + prev_row = ... # type: int + prev_col = ... # type: int + encoding = ... # type: Optional[str] + def __init__(self) -> None: ... + def add_whitespace(self, start: _Position) -> None: ... + def untokenize(self, iterable: Iterable[_Token]) -> str: ... + def compat(self, token: Sequence[Union[int, str]], iterable: Iterable[_Token]) -> None: ... + +def untokenize(iterable: Iterable[_Token]) -> Any: ... +def detect_encoding(readline: Callable[[], bytes]) -> Tuple[str, Sequence[bytes]]: ... +def tokenize(readline: Callable[[], bytes]) -> Generator[TokenInfo, None, None]: ... +def generate_tokens(readline: Callable[[], str]) -> Generator[TokenInfo, None, None]: ... + +if sys.version_info >= (3, 6): + from os import PathLike + def open(filename: Union[str, bytes, int, PathLike]) -> TextIO: ... +else: + def open(filename: Union[str, bytes, int]) -> TextIO: ... + +# Names in __all__ with no definition: +# AMPER +# AMPEREQUAL +# ASYNC +# AT +# ATEQUAL +# AWAIT +# CIRCUMFLEX +# CIRCUMFLEXEQUAL +# COLON +# COMMA +# DEDENT +# DOT +# DOUBLESLASH +# DOUBLESLASHEQUAL +# DOUBLESTAR +# DOUBLESTAREQUAL +# ELLIPSIS +# ENDMARKER +# EQEQUAL +# EQUAL +# ERRORTOKEN +# GREATER +# GREATEREQUAL +# INDENT +# ISEOF +# ISNONTERMINAL +# ISTERMINAL +# LBRACE +# LEFTSHIFT +# LEFTSHIFTEQUAL +# LESS +# LESSEQUAL +# LPAR +# LSQB +# MINEQUAL +# MINUS +# NAME +# NEWLINE +# NOTEQUAL +# NT_OFFSET +# NUMBER +# N_TOKENS +# OP +# PERCENT +# PERCENTEQUAL +# PLUS +# PLUSEQUAL +# RARROW +# RBRACE +# RIGHTSHIFT +# RIGHTSHIFTEQUAL +# RPAR +# RSQB +# SEMI +# SLASH +# SLASHEQUAL +# STAR +# STAREQUAL +# STRING +# TILDE +# VBAR +# VBAREQUAL +# tok_name diff --git a/client/typeshed-fallback/stdlib/3/tracemalloc.pyi b/client/typeshed-fallback/stdlib/3/tracemalloc.pyi new file mode 100644 index 000000000..4556f04e8 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/tracemalloc.pyi @@ -0,0 +1,70 @@ +# Stubs for tracemalloc (Python 3.4+) + +import sys +from typing import List, Optional, Sequence, Tuple, Union, overload + +def clear_traces() -> None: ... +def get_object_traceback(obj: object) -> Optional[Traceback]: ... +def get_traceback_limit() -> int: ... +def get_traced_memory() -> Tuple[int, int]: ... +def get_tracemalloc_memory() -> int: ... +def is_tracing() -> bool: ... +def start(nframe: int = ...) -> None: ... +def stop() -> None: ... +def take_snapshot() -> Snapshot: ... + +if sys.version_info >= (3, 6): + class DomainFilter: + inclusive = ... # type: bool + domain = ... # type: int + def __init__(self, inclusive: bool, domain: int) -> None: ... + +class Filter: + if sys.version_info >= (3, 6): + domain = ... # type: Optional[int] + inclusive = ... # type: bool + lineno = ... # type: Optional[int] + filename_pattern = ... # type: str + all_frames = ... # type: bool + def __init__(self, inclusive: bool, filename_pattern: str, lineno: Optional[int] = ..., all_frames: bool = ..., domain: Optional[int] = ...) -> None: ... + +class Frame: + filename = ... # type: str + lineno = ... # type: int + +class Snapshot: + def compare_to(self, old_snapshot: Snapshot, key_type: str, cumulative: bool = ...) -> List[StatisticDiff]: ... + def dump(self, filename: str) -> None: ... + if sys.version_info >= (3, 6): + def filter_traces(self, filters: Sequence[Union[DomainFilter, Filter]]) -> Snapshot: ... + else: + def filter_traces(self, filters: Sequence[Filter]) -> Snapshot: ... + @classmethod + def load(cls, filename: str) -> Snapshot: ... + def statistics(self, key_type: str, cumulative: bool = ...) -> List[Statistic]: ... + traceback_limit = ... # type: int + traces = ... # type: Sequence[Trace] + +class Statistic: + count = ... # type: int + size = ... # type: int + traceback = ... # type: Traceback + +class StatisticDiff: + count = ... # type: int + count_diff = ... # type: int + size = ... # type: int + size_diff = ... # type: int + traceback = ... # type: Traceback + +class Trace: + size = ... # type: int + traceback = ... # type: Traceback + +class Traceback(Sequence[Frame]): + def format(self, limit: Optional[int] = ...) -> List[str]: ... + @overload + def __getitem__(self, i: int) -> Frame: ... + @overload + def __getitem__(self, s: slice) -> Sequence[Frame]: ... + def __len__(self) -> int: ... diff --git a/client/typeshed-fallback/stdlib/3/types.pyi b/client/typeshed-fallback/stdlib/3/types.pyi new file mode 100644 index 000000000..9d121d12d --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/types.pyi @@ -0,0 +1,206 @@ +# Stubs for types +# Note, all classes "defined" here require special handling. + +# TODO parts of this should be conditional on version + +import sys +from typing import ( + Any, Awaitable, Callable, Dict, Generic, Iterator, Mapping, Optional, Tuple, TypeVar, + Union, overload, Type +) + +# ModuleType is exported from this module, but for circular import +# reasons exists in its own stub file (with ModuleSpec and Loader). +from _importlib_modulespec import ModuleType as ModuleType # Exported + +_T = TypeVar('_T') +_T_co = TypeVar('_T_co', covariant=True) +_T_contra = TypeVar('_T_contra', contravariant=True) +_KT = TypeVar('_KT') +_VT = TypeVar('_VT') + +class _Cell: + cell_contents = ... # type: Any + +class FunctionType: + __closure__ = ... # type: Optional[Tuple[_Cell, ...]] + __code__ = ... # type: CodeType + __defaults__ = ... # type: Optional[Tuple[Any, ...]] + __dict__ = ... # type: Dict[str, Any] + __globals__ = ... # type: Dict[str, Any] + __name__ = ... # type: str + __qualname__ = ... # type: str + __annotations__ = ... # type: Dict[str, Any] + __kwdefaults__ = ... # type: Dict[str, Any] + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __get__(self, obj: Optional[object], type: Optional[type]) -> MethodType: ... +LambdaType = FunctionType + +class CodeType: + """Create a code object. Not for the faint of heart.""" + co_argcount = ... # type: int + co_kwonlyargcount = ... # type: int + co_nlocals = ... # type: int + co_stacksize = ... # type: int + co_flags = ... # type: int + co_code = ... # type: bytes + co_consts = ... # type: Tuple[Any, ...] + co_names = ... # type: Tuple[str, ...] + co_varnames = ... # type: Tuple[str, ...] + co_filename = ... # type: str + co_name = ... # type: str + co_firstlineno = ... # type: int + co_lnotab = ... # type: bytes + co_freevars = ... # type: Tuple[str, ...] + co_cellvars = ... # type: Tuple[str, ...] + def __init__( + self, + argcount: int, + kwonlyargcount: int, + nlocals: int, + stacksize: int, + flags: int, + codestring: bytes, + constants: Tuple[Any, ...], + names: Tuple[str, ...], + varnames: Tuple[str, ...], + filename: str, + name: str, + firstlineno: int, + lnotab: bytes, + freevars: Tuple[str, ...] = ..., + cellvars: Tuple[str, ...] = ..., + ) -> None: ... + +class MappingProxyType(Mapping[_KT, _VT], Generic[_KT, _VT]): + def __init__(self, mapping: Mapping[_KT, _VT]) -> None: ... + def __getitem__(self, k: _KT) -> _VT: ... + def __iter__(self) -> Iterator[_KT]: ... + def __len__(self) -> int: ... + +class SimpleNamespace: + def __init__(self, **kwargs: Any) -> None: ... + def __getattribute__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __delattr__(self, name: str) -> None: ... + +class GeneratorType: + gi_code = ... # type: CodeType + gi_frame = ... # type: FrameType + gi_running = ... # type: bool + gi_yieldfrom = ... # type: Optional[GeneratorType] + def __iter__(self) -> GeneratorType: ... + def __next__(self) -> Any: ... + def close(self) -> None: ... + def send(self, arg: Any) -> Any: ... + @overload + def throw(self, val: BaseException) -> Any: ... + @overload + def throw(self, typ: type, val: BaseException = ..., tb: TracebackType = ...) -> Any: ... + +if sys.version_info >= (3, 6): + class AsyncGeneratorType(Generic[_T_co, _T_contra]): + ag_await: Optional[Awaitable[Any]] + ag_frame: FrameType + ag_running: bool + ag_code: CodeType + def __aiter__(self) -> Awaitable[AsyncGeneratorType[_T_co, _T_contra]]: ... + def __anext__(self) -> Awaitable[_T_co]: ... + def asend(self, val: _T_contra) -> Awaitable[_T_co]: ... + @overload + def athrow(self, val: BaseException) -> Awaitable[_T_co]: ... + @overload + def athrow(self, typ: Type[BaseException], val: BaseException, tb: TracebackType = ...) -> Awaitable[_T_co]: ... + def aclose(self) -> Awaitable[_T_co]: ... + +class CoroutineType: + cr_await = ... # type: Optional[Any] + cr_code = ... # type: CodeType + cr_frame = ... # type: FrameType + cr_running = ... # type: bool + def close(self) -> None: ... + def send(self, arg: Any) -> Any: ... + @overload + def throw(self, val: BaseException) -> Any: ... + @overload + def throw(self, typ: type, val: BaseException = ..., tb: TracebackType = ...) -> Any: ... + +class _StaticFunctionType: + """Fictional type to correct the type of MethodType.__func__. + + FunctionType is a descriptor, so mypy follows the descriptor protocol and + converts MethodType.__func__ back to MethodType (the return type of + FunctionType.__get__). But this is actually a special case; MethodType is + implemented in C and its attribute access doesn't go through + __getattribute__. + + By wrapping FunctionType in _StaticFunctionType, we get the right result; + similar to wrapping a function in staticmethod() at runtime to prevent it + being bound as a method. + """ + def __get__(self, obj: Optional[object], type: Optional[type]) -> FunctionType: ... + +class MethodType: + __func__ = ... # type: _StaticFunctionType + __self__ = ... # type: object + __name__ = ... # type: str + __qualname__ = ... # type: str + def __init__(self, func: Callable, obj: object) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... +class BuiltinFunctionType: + __self__ = ... # type: Union[object, ModuleType] + __name__ = ... # type: str + __qualname__ = ... # type: str + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... +BuiltinMethodType = BuiltinFunctionType + +class TracebackType: + if sys.version_info >= (3, 7): + def __init__(self, tb_next: Optional[TracebackType], tb_frame: FrameType, tb_lasti: int, tb_lineno: int) -> None: ... + tb_next: Optional[TracebackType] + else: + @property + def tb_next(self) -> Optional[TracebackType]: ... + # the rest are read-only even in 3.7 + @property + def tb_frame(self) -> FrameType: ... + @property + def tb_lasti(self) -> int: ... + @property + def tb_lineno(self) -> int: ... + +class FrameType: + f_back = ... # type: FrameType + f_builtins = ... # type: Dict[str, Any] + f_code = ... # type: CodeType + f_globals = ... # type: Dict[str, Any] + f_lasti = ... # type: int + f_lineno = ... # type: int + f_locals = ... # type: Dict[str, Any] + f_trace = ... # type: Callable[[], None] + if sys.version_info >= (3, 7): + f_frace_lines: bool + f_trace_opcodes: bool + + def clear(self) -> None: ... + +class GetSetDescriptorType: + __name__ = ... # type: str + __objclass__ = ... # type: type + def __get__(self, obj: Any, type: type = ...) -> Any: ... + def __set__(self, obj: Any) -> None: ... + def __delete__(self, obj: Any) -> None: ... +class MemberDescriptorType: + __name__ = ... # type: str + __objclass__ = ... # type: type + def __get__(self, obj: Any, type: type = ...) -> Any: ... + def __set__(self, obj: Any) -> None: ... + def __delete__(self, obj: Any) -> None: ... + +def new_class(name: str, bases: Tuple[type, ...] = ..., kwds: Dict[str, Any] = ..., exec_body: Callable[[Dict[str, Any]], None] = ...) -> type: ... +def prepare_class(name: str, bases: Tuple[type, ...] = ..., kwds: Dict[str, Any] = ...) -> Tuple[type, Dict[str, Any], Dict[str, Any]]: ... + +# Actually a different type, but `property` is special and we want that too. +DynamicClassAttribute = property + +def coroutine(f: Callable[..., Any]) -> CoroutineType: ... diff --git a/client/typeshed-fallback/stdlib/3/typing.pyi b/client/typeshed-fallback/stdlib/3/typing.pyi new file mode 100644 index 000000000..afc21186c --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/typing.pyi @@ -0,0 +1,583 @@ +# Stubs for typing + +import sys +from abc import abstractmethod, ABCMeta +from types import CodeType, FrameType, TracebackType +import collections # Needed by aliases like DefaultDict, see mypy issue 2986 + +# Definitions of special type checking related constructs. Their definition +# are not used, so their value does not matter. + +overload = object() +Any = object() +TypeVar = object() +_promote = object() +no_type_check = object() + +class _SpecialForm: + def __getitem__(self, typeargs: Any) -> Any: ... + +Tuple: _SpecialForm = ... +Generic: _SpecialForm = ... +Protocol: _SpecialForm = ... +Callable: _SpecialForm = ... +Type: _SpecialForm = ... +ClassVar: _SpecialForm = ... + +class GenericMeta(type): ... + +# Return type that indicates a function does not return. +# This type is equivalent to the None type, but the no-op Union is necessary to +# distinguish the None type from the None value. +NoReturn = Union[None] + +# Type aliases and type constructors + +class TypeAlias: + # Class for defining generic aliases for library types. + def __init__(self, target_type: type) -> None: ... + def __getitem__(self, typeargs: Any) -> Any: ... + +Union = TypeAlias(object) +Optional = TypeAlias(object) +List = TypeAlias(object) +Dict = TypeAlias(object) +DefaultDict = TypeAlias(object) +Set = TypeAlias(object) +FrozenSet = TypeAlias(object) +Counter = TypeAlias(object) +Deque = TypeAlias(object) +ChainMap = TypeAlias(object) + +# Predefined type variables. +AnyStr = TypeVar('AnyStr', str, bytes) + +# Abstract base classes. + +# These type variables are used by the container types. +_T = TypeVar('_T') +_S = TypeVar('_S') +_KT = TypeVar('_KT') # Key type. +_VT = TypeVar('_VT') # Value type. +_T_co = TypeVar('_T_co', covariant=True) # Any type covariant containers. +_V_co = TypeVar('_V_co', covariant=True) # Any type covariant containers. +_KT_co = TypeVar('_KT_co', covariant=True) # Key type covariant containers. +_VT_co = TypeVar('_VT_co', covariant=True) # Value type covariant containers. +_T_contra = TypeVar('_T_contra', contravariant=True) # Ditto contravariant. +_TC = TypeVar('_TC', bound=Type[object]) + +def runtime(cls: _TC) -> _TC: ... + +@runtime +class SupportsInt(Protocol, metaclass=ABCMeta): + @abstractmethod + def __int__(self) -> int: ... + +@runtime +class SupportsFloat(Protocol, metaclass=ABCMeta): + @abstractmethod + def __float__(self) -> float: ... + +@runtime +class SupportsComplex(Protocol, metaclass=ABCMeta): + @abstractmethod + def __complex__(self) -> complex: ... + +@runtime +class SupportsBytes(Protocol, metaclass=ABCMeta): + @abstractmethod + def __bytes__(self) -> bytes: ... + +@runtime +class SupportsAbs(Protocol[_T_co]): + @abstractmethod + def __abs__(self) -> _T_co: ... + +@runtime +class SupportsRound(Protocol[_T_co]): + @abstractmethod + def __round__(self, ndigits: int = ...) -> _T_co: ... + +@runtime +class Reversible(Protocol[_T_co]): + @abstractmethod + def __reversed__(self) -> Iterator[_T_co]: ... + +@runtime +class Sized(Protocol, metaclass=ABCMeta): + @abstractmethod + def __len__(self) -> int: ... + +@runtime +class Hashable(Protocol, metaclass=ABCMeta): + # TODO: This is special, in that a subclass of a hashable class may not be hashable + # (for example, list vs. object). It's not obvious how to represent this. This class + # is currently mostly useless for static checking. + @abstractmethod + def __hash__(self) -> int: ... + +@runtime +class Iterable(Protocol[_T_co]): + @abstractmethod + def __iter__(self) -> Iterator[_T_co]: ... + +@runtime +class Iterator(Iterable[_T_co], Protocol[_T_co]): + @abstractmethod + def __next__(self) -> _T_co: ... + def __iter__(self) -> Iterator[_T_co]: ... + +class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]): + @abstractmethod + def __next__(self) -> _T_co: ... + + @abstractmethod + def send(self, value: _T_contra) -> _T_co: ... + + @abstractmethod + def throw(self, typ: Type[BaseException], val: Optional[BaseException] = ..., + tb: Optional[TracebackType] = ...) -> _T_co: ... + + @abstractmethod + def close(self) -> None: ... + + @abstractmethod + def __iter__(self) -> Generator[_T_co, _T_contra, _V_co]: ... + + @property + def gi_code(self) -> CodeType: ... + @property + def gi_frame(self) -> FrameType: ... + @property + def gi_running(self) -> bool: ... + @property + def gi_yieldfrom(self) -> Optional[Generator]: ... + +# TODO: Several types should only be defined if sys.python_version >= (3, 5): +# Awaitable, AsyncIterator, AsyncIterable, Coroutine, Collection. +# See https: //github.com/python/typeshed/issues/655 for why this is not easy. + +@runtime +class Awaitable(Protocol[_T_co]): + @abstractmethod + def __await__(self) -> Generator[Any, None, _T_co]: ... + +class Coroutine(Awaitable[_V_co], Generic[_T_co, _T_contra, _V_co]): + @property + def cr_await(self) -> Optional[Any]: ... + @property + def cr_code(self) -> CodeType: ... + @property + def cr_frame(self) -> FrameType: ... + @property + def cr_running(self) -> bool: ... + + @abstractmethod + def send(self, value: _T_contra) -> _T_co: ... + + @abstractmethod + def throw(self, typ: Type[BaseException], val: Optional[BaseException] = ..., + tb: Optional[TracebackType] = ...) -> _T_co: ... + + @abstractmethod + def close(self) -> None: ... + + +# NOTE: This type does not exist in typing.py or PEP 484. +# The parameters correspond to Generator, but the 4th is the original type. +class AwaitableGenerator(Awaitable[_V_co], Generator[_T_co, _T_contra, _V_co], + Generic[_T_co, _T_contra, _V_co, _S], metaclass=ABCMeta): ... + +@runtime +class AsyncIterable(Protocol[_T_co]): + @abstractmethod + def __aiter__(self) -> AsyncIterator[_T_co]: ... + +@runtime +class AsyncIterator(AsyncIterable[_T_co], + Protocol[_T_co]): + @abstractmethod + def __anext__(self) -> Awaitable[_T_co]: ... + def __aiter__(self) -> AsyncIterator[_T_co]: ... + +if sys.version_info >= (3, 6): + class AsyncGenerator(AsyncIterator[_T_co], Generic[_T_co, _T_contra]): + @abstractmethod + def __anext__(self) -> Awaitable[_T_co]: ... + + @abstractmethod + def asend(self, value: _T_contra) -> Awaitable[_T_co]: ... + + @abstractmethod + def athrow(self, typ: Type[BaseException], val: Optional[BaseException] = ..., + tb: Any = ...) -> Awaitable[_T_co]: ... + + @abstractmethod + def aclose(self) -> Awaitable[None]: ... + + @abstractmethod + def __aiter__(self) -> AsyncGenerator[_T_co, _T_contra]: ... + + @property + def ag_await(self) -> Any: ... + @property + def ag_code(self) -> CodeType: ... + @property + def ag_frame(self) -> FrameType: ... + @property + def ag_running(self) -> bool: ... + +@runtime +class Container(Protocol[_T_co]): + @abstractmethod + def __contains__(self, x: object) -> bool: ... + + +if sys.version_info >= (3, 6): + @runtime + class Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... + + _Collection = Collection +else: + @runtime + class _Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... + +class Sequence(_Collection[_T_co], Reversible[_T_co], Generic[_T_co]): + @overload + @abstractmethod + def __getitem__(self, i: int) -> _T_co: ... + @overload + @abstractmethod + def __getitem__(self, s: slice) -> Sequence[_T_co]: ... + # Mixin methods + if sys.version_info >= (3, 5): + def index(self, x: Any, start: int = ..., end: int = ...) -> int: ... + else: + def index(self, x: Any) -> int: ... + def count(self, x: Any) -> int: ... + def __contains__(self, x: object) -> bool: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __reversed__(self) -> Iterator[_T_co]: ... + +class MutableSequence(Sequence[_T], Generic[_T]): + @abstractmethod + def insert(self, index: int, object: _T) -> None: ... + @overload + @abstractmethod + def __getitem__(self, i: int) -> _T: ... + @overload + @abstractmethod + def __getitem__(self, s: slice) -> MutableSequence[_T]: ... + @overload + @abstractmethod + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + @abstractmethod + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + @overload + @abstractmethod + def __delitem__(self, i: int) -> None: ... + @overload + @abstractmethod + def __delitem__(self, i: slice) -> None: ... + # Mixin methods + def append(self, object: _T) -> None: ... + def clear(self) -> None: ... + def extend(self, iterable: Iterable[_T]) -> None: ... + def reverse(self) -> None: ... + def pop(self, index: int = ...) -> _T: ... + def remove(self, object: _T) -> None: ... + def __iadd__(self, x: Iterable[_T]) -> MutableSequence[_T]: ... + +class AbstractSet(_Collection[_T_co], Generic[_T_co]): + @abstractmethod + def __contains__(self, x: object) -> bool: ... + # Mixin methods + def __le__(self, s: AbstractSet[Any]) -> bool: ... + def __lt__(self, s: AbstractSet[Any]) -> bool: ... + def __gt__(self, s: AbstractSet[Any]) -> bool: ... + def __ge__(self, s: AbstractSet[Any]) -> bool: ... + def __and__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... + def __or__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ... + def __sub__(self, s: AbstractSet[Any]) -> AbstractSet[_T_co]: ... + def __xor__(self, s: AbstractSet[_T]) -> AbstractSet[Union[_T_co, _T]]: ... + # TODO: Argument can be a more general ABC? + def isdisjoint(self, s: AbstractSet[Any]) -> bool: ... + +class MutableSet(AbstractSet[_T], Generic[_T]): + @abstractmethod + def add(self, x: _T) -> None: ... + @abstractmethod + def discard(self, x: _T) -> None: ... + # Mixin methods + def clear(self) -> None: ... + def pop(self) -> _T: ... + def remove(self, element: _T) -> None: ... + def __ior__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: ... + def __iand__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... + def __ixor__(self, s: AbstractSet[_S]) -> MutableSet[Union[_T, _S]]: ... + def __isub__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... + +class MappingView: + def __len__(self) -> int: ... + +class ItemsView(MappingView, AbstractSet[Tuple[_KT_co, _VT_co]], Generic[_KT_co, _VT_co]): + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[Tuple[_KT_co, _VT_co]]: ... + +class KeysView(MappingView, AbstractSet[_KT_co], Generic[_KT_co]): + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_KT_co]: ... + +class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]): + def __contains__(self, o: object) -> bool: ... + def __iter__(self) -> Iterator[_VT_co]: ... + +@runtime +class ContextManager(Protocol[_T_co]): + def __enter__(self) -> _T_co: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType]) -> Optional[bool]: ... + +if sys.version_info >= (3, 5): + @runtime + class AsyncContextManager(Protocol[_T_co]): + def __aenter__(self) -> Awaitable[_T_co]: ... + def __aexit__(self, exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType]) -> Awaitable[Optional[bool]]: ... + +class Mapping(_Collection[_KT], Generic[_KT, _VT_co]): + # TODO: We wish the key type could also be covariant, but that doesn't work, + # see discussion in https: //github.com/python/typing/pull/273. + @abstractmethod + def __getitem__(self, k: _KT) -> _VT_co: + ... + # Mixin methods + @overload + def get(self, k: _KT) -> Optional[_VT_co]: ... + @overload + def get(self, k: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T]: ... + def items(self) -> AbstractSet[Tuple[_KT, _VT_co]]: ... + def keys(self) -> AbstractSet[_KT]: ... + def values(self) -> ValuesView[_VT_co]: ... + def __contains__(self, o: object) -> bool: ... + +class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]): + @abstractmethod + def __setitem__(self, k: _KT, v: _VT) -> None: ... + @abstractmethod + def __delitem__(self, v: _KT) -> None: ... + + def clear(self) -> None: ... + @overload + def pop(self, k: _KT) -> _VT: ... + @overload + def pop(self, k: _KT, default: Union[_VT, _T] = ...) -> Union[_VT, _T]: ... + def popitem(self) -> Tuple[_KT, _VT]: ... + def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ... + # 'update' used to take a Union, but using overloading is better. + # The second overloaded type here is a bit too general, because + # Mapping[Tuple[_KT, _VT], W] is a subclass of Iterable[Tuple[_KT, _VT]], + # but will always have the behavior of the first overloaded type + # at runtime, leading to keys of a mix of types _KT and Tuple[_KT, _VT]. + # We don't currently have any way of forcing all Mappings to use + # the first overload, but by using overloading rather than a Union, + # mypy will commit to using the first overload when the argument is + # known to be a Mapping with unknown type parameters, which is closer + # to the behavior we want. See mypy issue #1430. + @overload + def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + @overload + def update(self, **kwargs: _VT) -> None: ... + +Text = str + +TYPE_CHECKING = True + +class IO(Iterator[AnyStr], Generic[AnyStr]): + # TODO detach + # TODO use abstract properties + @property + def mode(self) -> str: ... + @property + def name(self) -> str: ... + @abstractmethod + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + @abstractmethod + def fileno(self) -> int: ... + @abstractmethod + def flush(self) -> None: ... + @abstractmethod + def isatty(self) -> bool: ... + # TODO what if n is None? + @abstractmethod + def read(self, n: int = ...) -> AnyStr: ... + @abstractmethod + def readable(self) -> bool: ... + @abstractmethod + def readline(self, limit: int = ...) -> AnyStr: ... + @abstractmethod + def readlines(self, hint: int = ...) -> list[AnyStr]: ... + @abstractmethod + def seek(self, offset: int, whence: int = ...) -> int: ... + @abstractmethod + def seekable(self) -> bool: ... + @abstractmethod + def tell(self) -> int: ... + @abstractmethod + def truncate(self, size: Optional[int] = ...) -> int: ... + @abstractmethod + def writable(self) -> bool: ... + # TODO buffer objects + @abstractmethod + def write(self, s: AnyStr) -> int: ... + @abstractmethod + def writelines(self, lines: Iterable[AnyStr]) -> None: ... + + @abstractmethod + def __next__(self) -> AnyStr: ... + @abstractmethod + def __iter__(self) -> Iterator[AnyStr]: ... + @abstractmethod + def __enter__(self) -> IO[AnyStr]: ... + @abstractmethod + def __exit__(self, t: Optional[Type[BaseException]], value: Optional[BaseException], + traceback: Optional[TracebackType]) -> bool: ... + +class BinaryIO(IO[bytes]): + # TODO readinto + # TODO read1? + # TODO peek? + @overload + @abstractmethod + def write(self, s: bytearray) -> int: ... + @overload + @abstractmethod + def write(self, s: bytes) -> int: ... + + @abstractmethod + def __enter__(self) -> BinaryIO: ... + +class TextIO(IO[str]): + # TODO use abstractproperty + @property + def buffer(self) -> BinaryIO: ... + @property + def encoding(self) -> str: ... + @property + def errors(self) -> Optional[str]: ... + @property + def line_buffering(self) -> int: ... # int on PyPy, bool on CPython + @property + def newlines(self) -> Any: ... # None, str or tuple + @abstractmethod + def __enter__(self) -> TextIO: ... + +class ByteString(Sequence[int], metaclass=ABCMeta): ... + +class Match(Generic[AnyStr]): + pos = 0 + endpos = 0 + lastindex = 0 + lastgroup = ... # type: AnyStr + string = ... # type: AnyStr + + # The regular expression object whose match() or search() method produced + # this match instance. + re = ... # type: Pattern[AnyStr] + + def expand(self, template: AnyStr) -> AnyStr: ... + + @overload + def group(self, group1: int = ...) -> AnyStr: ... + @overload + def group(self, group1: str) -> AnyStr: ... + @overload + def group(self, group1: int, group2: int, + *groups: int) -> Sequence[AnyStr]: ... + @overload + def group(self, group1: str, group2: str, + *groups: str) -> Sequence[AnyStr]: ... + + def groups(self, default: AnyStr = ...) -> Sequence[AnyStr]: ... + def groupdict(self, default: AnyStr = ...) -> dict[str, AnyStr]: ... + def start(self, group: Union[int, str] = ...) -> int: ... + def end(self, group: Union[int, str] = ...) -> int: ... + def span(self, group: Union[int, str] = ...) -> Tuple[int, int]: ... + if sys.version_info >= (3, 6): + def __getitem__(self, g: Union[int, str]) -> AnyStr: ... + +class Pattern(Generic[AnyStr]): + flags = 0 + groupindex = ... # type: Mapping[str, int] + groups = 0 + pattern = ... # type: AnyStr + + def search(self, string: AnyStr, pos: int = ..., + endpos: int = ...) -> Optional[Match[AnyStr]]: ... + def match(self, string: AnyStr, pos: int = ..., + endpos: int = ...) -> Optional[Match[AnyStr]]: ... + # New in Python 3.4 + def fullmatch(self, string: AnyStr, pos: int = ..., + endpos: int = ...) -> Optional[Match[AnyStr]]: ... + def split(self, string: AnyStr, maxsplit: int = ...) -> list[AnyStr]: ... + def findall(self, string: AnyStr, pos: int = ..., + endpos: int = ...) -> list[Any]: ... + def finditer(self, string: AnyStr, pos: int = ..., + endpos: int = ...) -> Iterator[Match[AnyStr]]: ... + + @overload + def sub(self, repl: AnyStr, string: AnyStr, + count: int = ...) -> AnyStr: ... + @overload + def sub(self, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, + count: int = ...) -> AnyStr: ... + + @overload + def subn(self, repl: AnyStr, string: AnyStr, + count: int = ...) -> Tuple[AnyStr, int]: ... + @overload + def subn(self, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, + count: int = ...) -> Tuple[AnyStr, int]: ... + +# Functions + +def get_type_hints(obj: Callable, globalns: Optional[dict[str, Any]] = ..., + localns: Optional[dict[str, Any]] = ...) -> dict[str, Any]: ... + +@overload +def cast(tp: Type[_T], obj: Any) -> _T: ... +@overload +def cast(tp: str, obj: Any) -> Any: ... + +# Type constructors + +# NamedTuple is special-cased in the type checker +class NamedTuple(tuple): + _field_types = ... # type: collections.OrderedDict[str, Type[Any]] + _field_defaults: Dict[str, Any] = ... + _fields = ... # type: Tuple[str, ...] + _source = ... # type: str + + def __init__(self, typename: str, fields: Iterable[Tuple[str, Any]] = ..., *, + verbose: bool = ..., rename: bool = ..., **kwargs: Any) -> None: ... + + @classmethod + def _make(cls: Type[_T], iterable: Iterable[Any]) -> _T: ... + + def _asdict(self) -> collections.OrderedDict[str, Any]: ... + def _replace(self: _T, **kwargs: Any) -> _T: ... + +def NewType(name: str, tp: Type[_T]) -> Type[_T]: ... diff --git a/client/typeshed-fallback/stdlib/3/unittest/__init__.pyi b/client/typeshed-fallback/stdlib/3/unittest/__init__.pyi new file mode 100644 index 000000000..782c75056 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/unittest/__init__.pyi @@ -0,0 +1,346 @@ +# Stubs for unittest + +from typing import ( + Any, AnyStr, Callable, Container, ContextManager, Dict, FrozenSet, Generic, Iterable, + Iterator, List, NoReturn, Optional, overload, Pattern, Sequence, Set, TextIO, + Tuple, Type, TypeVar, Union +) +import logging +import sys +from types import ModuleType, TracebackType + + +_T = TypeVar('_T') +_FT = TypeVar('_FT', bound=Callable[..., Any]) +_E = TypeVar('_E', bound=BaseException) + + +def expectedFailure(func: _FT) -> _FT: ... +def skip(reason: str) -> Callable[[_FT], _FT]: ... +def skipIf(condition: object, reason: str) -> Callable[[_FT], _FT]: ... +def skipUnless(condition: object, reason: str) -> Callable[[_FT], _FT]: ... + +class SkipTest(Exception): + def __init__(self, reason: str) -> None: ... + + +class TestCase: + failureException = ... # type: Type[BaseException] + longMessage = ... # type: bool + maxDiff = ... # type: Optional[int] + # undocumented + _testMethodName = ... # type: str + def __init__(self, methodName: str = ...) -> None: ... + def setUp(self) -> None: ... + def tearDown(self) -> None: ... + @classmethod + def setUpClass(cls) -> None: ... + @classmethod + def tearDownClass(cls) -> None: ... + def run(self, result: Optional[TestResult] = ...) -> Optional[TestResult]: ... + def skipTest(self, reason: Any) -> None: ... + def subTest(self, msg: Any = ..., **params: Any) -> ContextManager[None]: ... + def debug(self) -> None: ... + def assertEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... + def assertNotEqual(self, first: Any, second: Any, + msg: Any = ...) -> None: ... + def assertTrue(self, expr: Any, msg: Any = ...) -> None: ... + def assertFalse(self, expr: Any, msg: Any = ...) -> None: ... + def assertIs(self, expr1: Any, expr2: Any, msg: Any = ...) -> None: ... + def assertIsNot(self, expr1: Any, expr2: Any, msg: Any = ...) -> None: ... + def assertIsNone(self, obj: Any, msg: Any = ...) -> None: ... + def assertIsNotNone(self, obj: Any, msg: Any = ...) -> None: ... + def assertIn(self, member: Any, + container: Union[Iterable[Any], Container[Any]], + msg: Any = ...) -> None: ... + def assertNotIn(self, member: Any, + container: Union[Iterable[Any], Container[Any]], + msg: Any = ...) -> None: ... + def assertIsInstance(self, obj: Any, + cls: Union[type, Tuple[type, ...]], + msg: Any = ...) -> None: ... + def assertNotIsInstance(self, obj: Any, + cls: Union[type, Tuple[type, ...]], + msg: Any = ...) -> None: ... + def assertGreater(self, a: Any, b: Any, msg: Any = ...) -> None: ... + def assertGreaterEqual(self, a: Any, b: Any, msg: Any = ...) -> None: ... + def assertLess(self, a: Any, b: Any, msg: Any = ...) -> None: ... + def assertLessEqual(self, a: Any, b: Any, msg: Any = ...) -> None: ... + @overload + def assertRaises(self, # type: ignore + expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], + callable: Callable[..., Any], + *args: Any, **kwargs: Any) -> None: ... + @overload + def assertRaises(self, + expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], + msg: Any = ...) -> _AssertRaisesContext[_E]: ... + @overload + def assertRaisesRegex(self, # type: ignore + expected_exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], + expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], + callable: Callable[..., Any], + *args: Any, **kwargs: Any) -> None: ... + @overload + def assertRaisesRegex(self, + expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], + expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], + msg: Any = ...) -> _AssertRaisesContext[_E]: ... + @overload + def assertWarns(self, # type: ignore + expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]], + callable: Callable[..., Any], + *args: Any, **kwargs: Any) -> None: ... + @overload + def assertWarns(self, + expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]], + msg: Any = ...) -> _AssertWarnsContext: ... + @overload + def assertWarnsRegex(self, # type: ignore + expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]], + expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], + callable: Callable[..., Any], + *args: Any, **kwargs: Any) -> None: ... + @overload + def assertWarnsRegex(self, + expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]], + expected_regex: Union[str, bytes, Pattern[str], Pattern[bytes]], + msg: Any = ...) -> _AssertWarnsContext: ... + def assertLogs( + self, logger: Optional[logging.Logger] = ..., + level: Union[int, str, None] = ... + ) -> _AssertLogsContext: ... + def assertAlmostEqual(self, first: float, second: float, places: int = ..., + msg: Any = ..., delta: float = ...) -> None: ... + @overload + def assertNotAlmostEqual(self, first: float, second: float, *, + msg: Any = ...) -> None: ... + @overload + def assertNotAlmostEqual(self, first: float, second: float, + places: int = ..., msg: Any = ...) -> None: ... + @overload + def assertNotAlmostEqual(self, first: float, second: float, *, + msg: Any = ..., delta: float = ...) -> None: ... + def assertRegex(self, text: AnyStr, expected_regex: Union[AnyStr, Pattern[AnyStr]], + msg: Any = ...) -> None: ... + def assertNotRegex(self, text: AnyStr, unexpected_regex: Union[AnyStr, Pattern[AnyStr]], + msg: Any = ...) -> None: ... + def assertCountEqual(self, first: Iterable[Any], second: Iterable[Any], + msg: Any = ...) -> None: ... + def addTypeEqualityFunc(self, typeobj: Type[Any], + function: Callable[..., None]) -> None: ... + def assertMultiLineEqual(self, first: str, second: str, + msg: Any = ...) -> None: ... + def assertSequenceEqual(self, seq1: Sequence[Any], seq2: Sequence[Any], + msg: Any = ..., + seq_type: Type[Sequence[Any]] = ...) -> None: ... + def assertListEqual(self, list1: List[Any], list2: List[Any], + msg: Any = ...) -> None: ... + def assertTupleEqual(self, tuple1: Tuple[Any, ...], tuple2: Tuple[Any, ...], + msg: Any = ...) -> None: ... + def assertSetEqual(self, set1: Union[Set[Any], FrozenSet[Any]], + set2: Union[Set[Any], FrozenSet[Any]], msg: Any = ...) -> None: ... + def assertDictEqual(self, d1: Dict[Any, Any], d2: Dict[Any, Any], + msg: Any = ...) -> None: ... + def fail(self, msg: Any = ...) -> NoReturn: ... + def countTestCases(self) -> int: ... + def defaultTestResult(self) -> TestResult: ... + def id(self) -> str: ... + def shortDescription(self) -> Optional[str]: ... + def addCleanup(self, function: Callable[..., Any], *args: Any, + **kwargs: Any) -> None: ... + def doCleanups(self) -> None: ... + def _formatMessage(self, msg: Optional[str], standardMsg: str) -> str: ... # undocumented + def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: ... # undocumented + # below is deprecated + def failUnlessEqual(self, first: Any, second: Any, + msg: Any = ...) -> None: ... + def assertEquals(self, first: Any, second: Any, msg: Any = ...) -> None: ... + def failIfEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... + def assertNotEquals(self, first: Any, second: Any, + msg: Any = ...) -> None: ... + def failUnless(self, expr: bool, msg: Any = ...) -> None: ... + def assert_(self, expr: bool, msg: Any = ...) -> None: ... + def failIf(self, expr: bool, msg: Any = ...) -> None: ... + @overload + def failUnlessRaises(self, # type: ignore + exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], + callable: Callable[..., Any] = ..., + *args: Any, **kwargs: Any) -> None: ... + @overload + def failUnlessRaises(self, + exception: Union[Type[_E], Tuple[Type[_E], ...]], + msg: Any = ...) -> _AssertRaisesContext[_E]: ... + def failUnlessAlmostEqual(self, first: float, second: float, + places: int = ..., msg: Any = ...) -> None: ... + def assertAlmostEquals(self, first: float, second: float, places: int = ..., + msg: Any = ..., delta: float = ...) -> None: ... + def failIfAlmostEqual(self, first: float, second: float, places: int = ..., + msg: Any = ...) -> None: ... + def assertNotAlmostEquals(self, first: float, second: float, + places: int = ..., msg: Any = ..., + delta: float = ...) -> None: ... + def assertRegexpMatches(self, text: AnyStr, regex: Union[AnyStr, Pattern[AnyStr]], + msg: Any = ...) -> None: ... + @overload + def assertRaisesRegexp(self, # type: ignore + exception: Union[Type[BaseException], Tuple[Type[BaseException], ...]], + callable: Callable[..., Any] = ..., + *args: Any, **kwargs: Any) -> None: ... + @overload + def assertRaisesRegexp(self, + exception: Union[Type[_E], Tuple[Type[_E], ...]], + msg: Any = ...) -> _AssertRaisesContext[_E]: ... + +class FunctionTestCase(TestCase): + def __init__(self, testFunc: Callable[[], None], + setUp: Optional[Callable[[], None]] = ..., + tearDown: Optional[Callable[[], None]] = ..., + description: Optional[str] = ...) -> None: ... + +class _AssertRaisesContext(Generic[_E]): + exception = ... # type: _E + def __enter__(self) -> _AssertRaisesContext[_E]: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType]) -> bool: ... + +class _AssertWarnsContext: + warning = ... # type: Warning + filename = ... # type: str + lineno = ... # type: int + def __enter__(self) -> _AssertWarnsContext: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType]) -> bool: ... + +class _AssertLogsContext: + records = ... # type: List[logging.LogRecord] + output = ... # type: List[str] + def __enter__(self) -> _AssertLogsContext: ... + def __exit__(self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType]) -> bool: ... + + +_TestType = Union[TestCase, TestSuite] + +class TestSuite(Iterable[_TestType]): + def __init__(self, tests: Iterable[_TestType] = ...) -> None: ... + def addTest(self, test: _TestType) -> None: ... + def addTests(self, tests: Iterable[_TestType]) -> None: ... + def run(self, result: TestResult) -> TestResult: ... + def debug(self) -> None: ... + def countTestCases(self) -> int: ... + def __iter__(self) -> Iterator[_TestType]: ... + + +class TestLoader: + if sys.version_info >= (3, 5): + errors = ... # type: List[Type[BaseException]] + testMethodPrefix = ... # type: str + sortTestMethodsUsing = ... # type: Callable[[str, str], bool] + suiteClass = ... # type: Callable[[List[TestCase]], TestSuite] + def loadTestsFromTestCase(self, + testCaseClass: Type[TestCase]) -> TestSuite: ... + if sys.version_info >= (3, 5): + def loadTestsFromModule(self, module: ModuleType, + *, pattern: Any = ...) -> TestSuite: ... + else: + def loadTestsFromModule(self, + module: ModuleType) -> TestSuite: ... + def loadTestsFromName(self, name: str, + module: Optional[ModuleType] = ...) -> TestSuite: ... + def loadTestsFromNames(self, names: Sequence[str], + module: Optional[ModuleType] = ...) -> TestSuite: ... + def getTestCaseNames(self, + testCaseClass: Type[TestCase]) -> Sequence[str]: ... + def discover(self, start_dir: str, pattern: str = ..., + top_level_dir: Optional[str] = ...) -> TestSuite: ... + +_SysExcInfoType = Tuple[Optional[Type[BaseException]], + Optional[BaseException], + Optional[TracebackType]] + +class TestResult: + errors = ... # type: List[Tuple[TestCase, str]] + failures = ... # type: List[Tuple[TestCase, str]] + skipped = ... # type: List[Tuple[TestCase, str]] + expectedFailures = ... # type: List[Tuple[TestCase, str]] + unexpectedSuccesses = ... # type: List[TestCase] + shouldStop = ... # type: bool + testsRun = ... # type: int + buffer = ... # type: bool + failfast = ... # type: bool + tb_locals = ... # type: bool + def wasSuccessful(self) -> bool: ... + def stop(self) -> None: ... + def startTest(self, test: TestCase) -> None: ... + def stopTest(self, test: TestCase) -> None: ... + def startTestRun(self) -> None: ... + def stopTestRun(self) -> None: ... + def addError(self, test: TestCase, err: _SysExcInfoType) -> None: ... + def addFailure(self, test: TestCase, err: _SysExcInfoType) -> None: ... + def addSuccess(self, test: TestCase) -> None: ... + def addSkip(self, test: TestCase, reason: str) -> None: ... + def addExpectedFailure(self, test: TestCase, + err: _SysExcInfoType) -> None: ... + def addUnexpectedSuccess(self, test: TestCase) -> None: ... + def addSubTest(self, test: TestCase, subtest: TestCase, + outcome: Optional[_SysExcInfoType]) -> None: ... + +class TextTestResult(TestResult): + separator1: str + separator2: str + def __init__(self, stream: TextIO, descriptions: bool, + verbosity: int) -> None: ... + def getDescription(self, test: TestCase) -> str: ... + def printErrors(self) -> None: ... + def printErrorList(self, flavour: str, errors: Tuple[TestCase, str]) -> None: ... +_TextTestResult = TextTestResult + +defaultTestLoader = ... # type: TestLoader + +_ResultClassType = Callable[[TextIO, bool, int], TestResult] + +class TestRunner: + def run(self, test: Union[TestSuite, TestCase]) -> TestResult: ... + +class TextTestRunner(TestRunner): + if sys.version_info >= (3, 5): + def __init__(self, stream: Optional[TextIO] = ..., + descriptions: bool = ..., verbosity: int = ..., + failfast: bool = ..., buffer: bool = ..., + resultclass: Optional[_ResultClassType] = ..., + warnings: Optional[Type[Warning]] = ..., + *, tb_locals: bool = ...) -> None: ... + else: + def __init__(self, + stream: Optional[TextIO] = ..., + descriptions: bool = ..., verbosity: int = ..., + failfast: bool = ..., buffer: bool = ..., + resultclass: Optional[_ResultClassType] = ..., + warnings: Optional[Type[Warning]] = ...) -> None: ... + def _makeResult(self) -> TestResult: ... + +# not really documented +class TestProgram: + result = ... # type: TestResult + def runTests(self) -> None: ... # undocumented + +def main(module: Union[None, str, ModuleType] = ..., + defaultTest: Union[str, Iterable[str], None] = ..., + argv: Optional[List[str]] = ..., + testRunner: Union[Type[TestRunner], TestRunner, None] = ..., + testLoader: TestLoader = ..., exit: bool = ..., verbosity: int = ..., + failfast: Optional[bool] = ..., catchbreak: Optional[bool] = ..., + buffer: Optional[bool] = ..., + warnings: Optional[str] = ...) -> TestProgram: ... + +def load_tests(loader: TestLoader, tests: TestSuite, + pattern: Optional[str]) -> TestSuite: ... + +def installHandler() -> None: ... +def registerResult(result: TestResult) -> None: ... +def removeResult(result: TestResult) -> bool: ... +@overload +def removeHandler() -> None: ... +@overload +def removeHandler(function: _FT) -> _FT: ... diff --git a/client/typeshed-fallback/stdlib/3/unittest/mock.pyi b/client/typeshed-fallback/stdlib/3/unittest/mock.pyi new file mode 100644 index 000000000..551e57c14 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/unittest/mock.pyi @@ -0,0 +1,146 @@ +# Stubs for mock + +import sys +from typing import Any, Optional, Text, Type + +FILTER_DIR = ... # type: Any + +class _slotted: ... + +class _SentinelObject: + name = ... # type: Any + def __init__(self, name: Any) -> None: ... + +class _Sentinel: + def __init__(self) -> None: ... + def __getattr__(self, name: str) -> Any: ... + +sentinel = ... # type: Any +DEFAULT = ... # type: Any + +class _CallList(list): + def __contains__(self, value: Any) -> bool: ... + +class _MockIter: + obj = ... # type: Any + def __init__(self, obj: Any) -> None: ... + def __iter__(self) -> Any: ... + def __next__(self) -> Any: ... + +class Base: + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + +# TODO: Defining this and other mock classes as classes in this stub causes +# many false positives with mypy and production code. See if we can +# improve mypy somehow and use a class with an "Any" base class. +NonCallableMock: Any + +class CallableMixin(Base): + side_effect = ... # type: Any + def __init__(self, spec: Optional[Any] = ..., side_effect: Optional[Any] = ..., return_value: Any = ..., wraps: Optional[Any] = ..., name: Optional[Any] = ..., spec_set: Optional[Any] = ..., parent: Optional[Any] = ..., _spec_state: Optional[Any] = ..., _new_name: Any = ..., _new_parent: Optional[Any] = ..., **kwargs: Any) -> None: ... + def __call__(_mock_self, *args: Any, **kwargs: Any) -> Any: ... + +Mock: Any + +class _patch: + attribute_name = ... # type: Any + getter = ... # type: Any + attribute = ... # type: Any + new = ... # type: Any + new_callable = ... # type: Any + spec = ... # type: Any + create = ... # type: bool + has_local = ... # type: Any + spec_set = ... # type: Any + autospec = ... # type: Any + kwargs = ... # type: Any + additional_patchers = ... # type: Any + def __init__(self, getter: Any, attribute: Any, new: Any, spec: Any, create: Any, spec_set: Any, autospec: Any, new_callable: Any, kwargs: Any) -> None: ... + def copy(self) -> Any: ... + def __call__(self, func: Any) -> Any: ... + def decorate_class(self, klass: Any) -> Any: ... + def decorate_callable(self, func: Any) -> Any: ... + def get_original(self) -> Any: ... + target = ... # type: Any + temp_original = ... # type: Any + is_local = ... # type: Any + def __enter__(self) -> Any: ... + def __exit__(self, *exc_info: Any) -> Any: ... + def start(self) -> Any: ... + def stop(self) -> Any: ... + +class _patch_dict: + in_dict = ... # type: Any + values = ... # type: Any + clear = ... # type: Any + def __init__(self, in_dict: Any, values: Any = ..., clear: Any = ..., **kwargs: Any) -> None: ... + def __call__(self, f: Any) -> Any: ... + def decorate_class(self, klass: Any) -> Any: ... + def __enter__(self) -> Any: ... + def __exit__(self, *args: Any) -> Any: ... + start = ... # type: Any + stop = ... # type: Any + +class _patcher: + TEST_PREFIX: str + dict: Type[_patch_dict] + def __call__(self, target: Any, new: Optional[Any] = ..., spec: Optional[Any] = ..., create: bool = ..., spec_set: Optional[Any] = ..., autospec: Optional[Any] = ..., new_callable: Optional[Any] = ..., **kwargs: Any) -> _patch: ... + def object(self, target: Any, attribute: Text, new: Optional[Any] = ..., spec: Optional[Any] = ..., create: bool = ..., spec_set: Optional[Any] = ..., autospec: Optional[Any] = ..., new_callable: Optional[Any] = ..., **kwargs: Any) -> _patch: ... + def multiple(self, target: Any, spec: Optional[Any] = ..., create: bool = ..., spec_set: Optional[Any] = ..., autospec: Optional[Any] = ..., new_callable: Optional[Any] = ..., **kwargs: Any) -> _patch: ... + def stopall(self) -> None: ... + +patch: _patcher + +class MagicMixin: + def __init__(self, *args: Any, **kw: Any) -> None: ... + +NonCallableMagicMock: Any +MagicMock: Any + +class MagicProxy: + name = ... # type: Any + parent = ... # type: Any + def __init__(self, name: Any, parent: Any) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def create_mock(self) -> Any: ... + def __get__(self, obj: Any, _type: Optional[Any] = ...) -> Any: ... + +class _ANY: + def __eq__(self, other: Any) -> bool: ... + def __ne__(self, other: Any) -> bool: ... + +ANY = ... # type: Any + +class _Call(tuple): + def __new__(cls, value: Any = ..., name: Optional[Any] = ..., parent: Optional[Any] = ..., two: bool = ..., from_kall: bool = ...) -> Any: ... + name = ... # type: Any + parent = ... # type: Any + from_kall = ... # type: Any + def __init__(self, value: Any = ..., name: Optional[Any] = ..., parent: Optional[Any] = ..., two: bool = ..., from_kall: bool = ...) -> None: ... + def __eq__(self, other: Any) -> bool: ... + __ne__ = ... # type: Any + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __getattr__(self, attr: Any) -> Any: ... + def count(self, *args: Any, **kwargs: Any) -> Any: ... + def index(self, *args: Any, **kwargs: Any) -> Any: ... + def call_list(self) -> Any: ... + +call = ... # type: Any + +def create_autospec(spec: Any, spec_set: Any = ..., instance: Any = ..., _parent: Optional[Any] = ..., _name: Optional[Any] = ..., **kwargs: Any) -> Any: ... + +class _SpecState: + spec = ... # type: Any + ids = ... # type: Any + spec_set = ... # type: Any + parent = ... # type: Any + instance = ... # type: Any + name = ... # type: Any + def __init__(self, spec: Any, spec_set: Any = ..., parent: Optional[Any] = ..., name: Optional[Any] = ..., ids: Optional[Any] = ..., instance: Any = ...) -> None: ... + +def mock_open(mock: Optional[Any] = ..., read_data: Any = ...) -> Any: ... + +PropertyMock: Any + +if sys.version_info >= (3, 7): + def seal(mock: Any) -> None: ... diff --git a/client/typeshed-fallback/stdlib/3/urllib/__init__.pyi b/client/typeshed-fallback/stdlib/3/urllib/__init__.pyi new file mode 100644 index 000000000..e69de29bb diff --git a/client/typeshed-fallback/stdlib/3/urllib/error.pyi b/client/typeshed-fallback/stdlib/3/urllib/error.pyi new file mode 100644 index 000000000..6e3d6a58f --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/urllib/error.pyi @@ -0,0 +1,12 @@ +from typing import Dict, Union +from urllib.response import addinfourl + +# Stubs for urllib.error + +class URLError(IOError): + reason = ... # type: Union[str, BaseException] +class HTTPError(URLError, addinfourl): + code = ... # type: int + headers = ... # type: Dict[str, str] + def __init__(self, url, code, msg, hdrs, fp) -> None: ... +class ContentTooShortError(URLError): ... diff --git a/client/typeshed-fallback/stdlib/3/urllib/parse.pyi b/client/typeshed-fallback/stdlib/3/urllib/parse.pyi new file mode 100644 index 000000000..5cacff6c4 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/urllib/parse.pyi @@ -0,0 +1,146 @@ +# Stubs for urllib.parse +from typing import Any, List, Dict, Tuple, AnyStr, Generic, overload, Sequence, Mapping, Union, NamedTuple, Callable, Optional +import sys + +_Str = Union[bytes, str] + + +uses_relative = ... # type: List[str] +uses_netloc = ... # type: List[str] +uses_params = ... # type: List[str] +non_hierarchical = ... # type: List[str] +uses_query = ... # type: List[str] +uses_fragment = ... # type: List[str] +scheme_chars = ... # type: str +MAX_CACHE_SIZE = 0 + +class _ResultMixinBase(Generic[AnyStr]): + def geturl(self) -> AnyStr: ... + +class _ResultMixinStr(_ResultMixinBase[str]): + def encode(self, encoding: str = ..., errors: str = ...) -> _ResultMixinBytes: ... + + +class _ResultMixinBytes(_ResultMixinBase[str]): + def decode(self, encoding: str = ..., errors: str = ...) -> _ResultMixinStr: ... + + +class _NetlocResultMixinBase(Generic[AnyStr]): + username = ... # type: AnyStr + password = ... # type: AnyStr + hostname = ... # type: AnyStr + port = ... # type: int + +class _NetlocResultMixinStr(_NetlocResultMixinBase[str], _ResultMixinStr): ... + +class _NetlocResultMixinBytes(_NetlocResultMixinBase[bytes], _ResultMixinBytes): ... + +class _DefragResultBase(tuple, Generic[AnyStr]): + url = ... # type: AnyStr + fragment = ... # type: AnyStr + + +_SplitResultBase = NamedTuple( + '_SplitResultBase', + [ + ('scheme', str), ('netloc', str), ('path', str), ('query', str), ('fragment', str) + ] +) +_SplitResultBytesBase = NamedTuple( + '_SplitResultBytesBase', + [ + ('scheme', bytes), ('netloc', bytes), ('path', bytes), ('query', bytes), ('fragment', bytes) + ] +) + +_ParseResultBase = NamedTuple( + '_ParseResultBase', + [ + ('scheme', str), ('netloc', str), ('path', str), ('params', str), ('query', str), ('fragment', str) + ] +) +_ParseResultBytesBase = NamedTuple( + '_ParseResultBytesBase', + [ + ('scheme', bytes), ('netloc', bytes), ('path', bytes), ('params', bytes), ('query', bytes), ('fragment', bytes) + ] +) + +# Structured result objects for string data +class DefragResult(_DefragResultBase[str], _ResultMixinStr): ... + +class SplitResult(_SplitResultBase, _NetlocResultMixinStr): ... + +class ParseResult(_ParseResultBase, _NetlocResultMixinStr): ... + +# Structured result objects for bytes data +class DefragResultBytes(_DefragResultBase[bytes], _ResultMixinBytes): ... + +class SplitResultBytes(_SplitResultBytesBase, _NetlocResultMixinBytes): ... + +class ParseResultBytes(_ParseResultBytesBase, _NetlocResultMixinBytes): ... + + +def parse_qs(qs: AnyStr, keep_blank_values: bool = ..., strict_parsing: bool = ..., encoding: str = ..., errors: str = ...) -> Dict[AnyStr, List[AnyStr]]: ... + +def parse_qsl(qs: AnyStr, keep_blank_values: bool = ..., strict_parsing: bool = ..., encoding: str = ..., errors: str = ...) -> List[Tuple[AnyStr, AnyStr]]: ... + + +@overload +def quote(string: str, safe: _Str = ..., encoding: str = ..., errors: str = ...) -> str: ... +@overload +def quote(string: bytes, safe: _Str = ...) -> str: ... + +def quote_from_bytes(bs: bytes, safe: _Str = ...) -> str: ... + +@overload +def quote_plus(string: str, safe: _Str = ..., encoding: str = ..., errors: str = ...) -> str: ... +@overload +def quote_plus(string: bytes, safe: _Str = ...) -> str: ... + +def unquote(string: str, encoding: str = ..., errors: str = ...) -> str: ... + +def unquote_to_bytes(string: _Str) -> bytes: ... + +def unquote_plus(string: str, encoding: str = ..., errors: str = ...) -> str: ... + +@overload +def urldefrag(url: str) -> DefragResult: ... +@overload +def urldefrag(url: bytes) -> DefragResultBytes: ... + +if sys.version_info >= (3, 5): + def urlencode(query: Union[Mapping[Any, Any], + Mapping[Any, Sequence[Any]], + Sequence[Tuple[Any, Any]], + Sequence[Tuple[Any, Sequence[Any]]]], + doseq: bool = ..., safe: AnyStr = ..., encoding: str = ..., errors: str = ..., + quote_via: Callable[[str, AnyStr, str, str], str] = ...) -> str: ... +else: + def urlencode(query: Union[Mapping[Any, Any], + Mapping[Any, Sequence[Any]], + Sequence[Tuple[Any, Any]], + Sequence[Tuple[Any, Sequence[Any]]]], + doseq: bool = ..., safe: AnyStr = ..., encoding: str = ..., errors: str = ...) -> str: ... + +def urljoin(base: AnyStr, url: Optional[AnyStr], allow_fragments: bool = ...) -> AnyStr: ... + +@overload +def urlparse(url: str, scheme: str = ..., allow_fragments: bool = ...) -> ParseResult: ... +@overload +def urlparse(url: bytes, scheme: bytes = ..., allow_fragments: bool = ...) -> ParseResultBytes: ... + +@overload +def urlsplit(url: str, scheme: str = ..., allow_fragments: bool = ...) -> SplitResult: ... +@overload +def urlsplit(url: bytes, scheme: bytes = ..., allow_fragments: bool = ...) -> SplitResultBytes: ... + +@overload +def urlunparse(components: Tuple[AnyStr, AnyStr, AnyStr, AnyStr, AnyStr, AnyStr]) -> AnyStr: ... +@overload +def urlunparse(components: Sequence[AnyStr]) -> AnyStr: ... + +@overload +def urlunsplit(components: Tuple[AnyStr, AnyStr, AnyStr, AnyStr, AnyStr]) -> AnyStr: ... +@overload +def urlunsplit(components: Sequence[AnyStr]) -> AnyStr: ... diff --git a/client/typeshed-fallback/stdlib/3/urllib/request.pyi b/client/typeshed-fallback/stdlib/3/urllib/request.pyi new file mode 100644 index 000000000..fb6fc6d44 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/urllib/request.pyi @@ -0,0 +1,222 @@ +# Stubs for urllib.request (Python 3.4) + +from typing import ( + Any, Callable, ClassVar, Dict, List, IO, Mapping, Optional, Sequence, Tuple, + TypeVar, Union, overload, NoReturn, +) +from http.client import HTTPResponse, HTTPMessage, HTTPConnectionProtocol +from http.cookiejar import CookieJar +from email.message import Message +from urllib.response import addinfourl +import ssl +import sys +import os + +_T = TypeVar('_T') +_UrlopenRet = Union[_HTTPResponse, addinfourl] + +class _HTTPResponse(HTTPResponse): + url: str + msg: str # type: ignore + +def urlopen( + url: Union[str, Request], data: Optional[bytes] = ..., + timeout: float = ..., *, cafile: Optional[str] = ..., + capath: Optional[str] = ..., cadefault: bool = ..., + context: Optional[ssl.SSLContext] = ... +) -> _UrlopenRet: ... +def install_opener(opener: OpenerDirector) -> None: ... +def build_opener( + *handlers: Union[BaseHandler, Callable[[], BaseHandler]] +) -> OpenerDirector: ... +def url2pathname(path: str) -> str: ... +def pathname2url(path: str) -> str: ... +def getproxies() -> Dict[str, str]: ... +def parse_http_list(s: str) -> List[str]: ... +def parse_keqv_list(l: List[str]) -> Dict[str, str]: ... + +class Request: + @property + def full_url(self) -> str: ... + @full_url.setter + def full_url(self, value: str) -> None: ... + @full_url.deleter + def full_url(self) -> None: ... + type: str + host: str + origin_req_host: str + selector: str + data: Optional[bytes] + headers: Dict[str, str] + unverifiable: bool + method: Optional[str] + def __init__(self, url: str, data: Optional[bytes] = ..., + headers: Dict[str, str] = ..., origin_req_host: Optional[str] = ..., + unverifiable: bool = ..., method: Optional[str] = ...) -> None: ... + def get_method(self) -> str: ... + def add_header(self, key: str, val: str) -> None: ... + def add_unredirected_header(self, key: str, val: str) -> None: ... + def has_header(self, header_name: str) -> bool: ... + def remove_header(self, header_name: str) -> None: ... + def get_full_url(self) -> str: ... + def set_proxy(self, host: str, type: str) -> None: ... + @overload + def get_header(self, header_name: str) -> Optional[str]: ... + @overload + def get_header(self, header_name: str, default: _T) -> Union[str, _T]: ... + def header_items(self) -> List[Tuple[str, str]]: ... + +class OpenerDirector: + addheaders: List[Tuple[str, str]] + def add_handler(self, handler: BaseHandler) -> None: ... + def open(self, url: Union[str, Request], data: Optional[bytes] = ..., + timeout: float = ...) -> _UrlopenRet: ... + def error(self, proto: str, *args: Any) -> _UrlopenRet: ... + + +class BaseHandler: + handler_order: ClassVar[int] + parent: OpenerDirector + def add_parent(self, parent: OpenerDirector) -> None: ... + def close(self) -> None: ... + def http_error_nnn(self, req: Request, fp: IO[str], code: int, msg: int, + hdrs: Mapping[str, str]) -> _UrlopenRet: ... + +class HTTPDefaultErrorHandler(BaseHandler): ... + +class HTTPRedirectHandler(BaseHandler): + def redirect_request(self, req: Request, fp: IO[str], code: int, msg: int, + hdrs: Mapping[str, str], + newurl: str) -> Optional[Request]: ... + def http_error_301(self, req: Request, fp: IO[str], code: int, msg: int, + hdrs: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + def http_error_302(self, req: Request, fp: IO[str], code: int, msg: int, + hdrs: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + def http_error_303(self, req: Request, fp: IO[str], code: int, msg: int, + hdrs: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + def http_error_307(self, req: Request, fp: IO[str], code: int, msg: int, + hdrs: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + +class HTTPCookieProcessor(BaseHandler): + cookiejar: CookieJar + def __init__(self, cookiejar: Optional[CookieJar] = ...) -> None: ... + +class ProxyHandler(BaseHandler): + def __init__(self, proxies: Optional[Dict[str, str]] = ...) -> None: ... + # TODO add a method for every (common) proxy protocol + +class HTTPPasswordMgr: + def add_password(self, realm: str, uri: Union[str, Sequence[str]], + user: str, passwd: str) -> None: ... + def find_user_password(self, realm: str, authuri: str) -> Tuple[Optional[str], Optional[str]]: ... + +class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr): + def add_password(self, realm: str, uri: Union[str, Sequence[str]], + user: str, passwd: str) -> None: ... + def find_user_password(self, realm: str, authuri: str) -> Tuple[Optional[str], Optional[str]]: ... + +if sys.version_info >= (3, 5): + class HTTPPasswordMgrWithPriorAuth(HTTPPasswordMgrWithDefaultRealm): + def add_password(self, realm: str, uri: Union[str, Sequence[str]], + user: str, passwd: str, + is_authenticated: bool = ...) -> None: ... + def update_authenticated(self, uri: Union[str, Sequence[str]], + is_authenticated: bool = ...) -> None: ... + def is_authenticated(self, authuri: str) -> bool: ... + +class AbstractBasicAuthHandler: + def __init__(self, + password_mgr: Optional[HTTPPasswordMgr] = ...) -> None: ... + def http_error_auth_reqed(self, authreq: str, host: str, req: Request, + headers: Mapping[str, str]) -> None: ... + +class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): + def http_error_401(self, req: Request, fp: IO[str], code: int, msg: int, + hdrs: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + +class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): + def http_error_407(self, req: Request, fp: IO[str], code: int, msg: int, + hdrs: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + +class AbstractDigestAuthHandler: + def __init__(self, passwd: Optional[HTTPPasswordMgr] = ...) -> None: ... + def reset_retry_count(self) -> None: ... + def http_error_auth_reqed(self, auth_header: str, host: str, req: Request, + headers: Mapping[str, str]) -> None: ... + def retry_http_digest_auth(self, req: Request, auth: str) -> Optional[_UrlopenRet]: ... + def get_cnonce(self, nonce: str) -> str: ... + def get_authorization(self, req: Request, chal: Mapping[str, str]) -> str: ... + def get_algorithm_impls(self, algorithm: str) -> Tuple[Callable[[str], str], Callable[[str, str], str]]: ... + def get_entity_digest(self, data: Optional[bytes], chal: Mapping[str, str]) -> Optional[str]: ... + +class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): + def http_error_401(self, req: Request, fp: IO[str], code: int, msg: int, + hdrs: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + +class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): + def http_error_407(self, req: Request, fp: IO[str], code: int, msg: int, + hdrs: Mapping[str, str]) -> Optional[_UrlopenRet]: ... + +class AbstractHTTPHandler(BaseHandler): # undocumented + def __init__(self, debuglevel: int = ...) -> None: ... + def set_http_debuglevel(self, level: int) -> None: ... + def do_request_(self, request: Request) -> Request: ... + def do_open(self, + http_class: HTTPConnectionProtocol, + req: Request, + **http_conn_args: Any) -> HTTPResponse: ... + +class HTTPHandler(AbstractHTTPHandler): + def http_open(self, req: Request) -> HTTPResponse: ... + def http_request(self, request: Request) -> Request: ... # undocumented + +class HTTPSHandler(AbstractHTTPHandler): + def __init__(self, debuglevel: int = ..., + context: Optional[ssl.SSLContext] = ..., + check_hostname: Optional[bool] = ...) -> None: ... + def https_open(self, req: Request) -> HTTPResponse: ... + def https_request(self, request: Request) -> Request: ... # undocumented + +class FileHandler(BaseHandler): + def file_open(self, req: Request) -> addinfourl: ... + +class DataHandler(BaseHandler): + def data_open(self, req: Request) -> addinfourl: ... + +class FTPHandler(BaseHandler): + def ftp_open(self, req: Request) -> addinfourl: ... + +class CacheFTPHandler(FTPHandler): + def setTimeout(self, t: float) -> None: ... + def setMaxConns(self, m: int) -> None: ... + +class UnknownHandler(BaseHandler): + def unknown_open(self, req: Request) -> NoReturn: ... + +class HTTPErrorProcessor(BaseHandler): + def http_response(self, request, response) -> _UrlopenRet: ... + def https_response(self, request, response) -> _UrlopenRet: ... + +if sys.version_info >= (3, 6): + def urlretrieve(url: str, filename: Optional[Union[str, os.PathLike]] = ..., + reporthook: Optional[Callable[[int, int, int], None]] = ..., + data: Optional[bytes] = ...) -> Tuple[str, HTTPMessage]: ... +else: + def urlretrieve(url: str, filename: Optional[str] = ..., + reporthook: Optional[Callable[[int, int, int], None]] = ..., + data: Optional[bytes] = ...) -> Tuple[str, HTTPMessage]: ... +def urlcleanup() -> None: ... + +class URLopener: + version: ClassVar[str] + def __init__(self, proxies: Optional[Dict[str, str]] = ..., + **x509: str) -> None: ... + def open(self, fullurl: str, data: Optional[bytes] = ...) -> _UrlopenRet: ... + def open_unknown(self, fullurl: str, + data: Optional[bytes] = ...) -> _UrlopenRet: ... + def retrieve(self, url: str, filename: Optional[str] = ..., + reporthook: Optional[Callable[[int, int, int], None]] = ..., + data: Optional[bytes] = ...) -> Tuple[str, Optional[Message]]: ... + +class FancyURLopener(URLopener): + def prompt_user_passwd(self, host: str, realm: str) -> Tuple[str, str]: ... diff --git a/client/typeshed-fallback/stdlib/3/urllib/response.pyi b/client/typeshed-fallback/stdlib/3/urllib/response.pyi new file mode 100644 index 000000000..ef3507d7d --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/urllib/response.pyi @@ -0,0 +1,41 @@ +# private module, we only expose what's needed + +from typing import BinaryIO, Iterable, List, Mapping, Optional, Type, TypeVar +from types import TracebackType + +_AIUT = TypeVar("_AIUT", bound=addbase) + +class addbase(BinaryIO): + def __enter__(self: _AIUT) -> _AIUT: ... + def __exit__(self, type: Optional[Type[BaseException]], value: Optional[BaseException], traceback: Optional[TracebackType]) -> bool: ... + def __iter__(self: _AIUT) -> _AIUT: ... + def __next__(self) -> bytes: ... + def close(self) -> None: ... + # These methods don't actually exist, but the class inherits at runtime from + # tempfile._TemporaryFileWrapper, which uses __getattr__ to delegate to the + # underlying file object. To satisfy the BinaryIO interface, we pretend that this + # class has these additional methods. + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def read(self, n: int = ...) -> bytes: ... + def readable(self) -> bool: ... + def readline(self, limit: int = ...) -> bytes: ... + def readlines(self, hint: int = ...) -> List[bytes]: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def writable(self) -> bool: ... + def write(self, s: bytes) -> int: ... + def writelines(self, lines: Iterable[bytes]) -> None: ... + +class addinfo(addbase): + headers: Mapping[str, str] + def info(self) -> Mapping[str, str]: ... + +class addinfourl(addinfo): + url: str + code: int + def geturl(self) -> str: ... + def getcode(self) -> int: ... diff --git a/client/typeshed-fallback/stdlib/3/urllib/robotparser.pyi b/client/typeshed-fallback/stdlib/3/urllib/robotparser.pyi new file mode 100644 index 000000000..36150ab01 --- /dev/null +++ b/client/typeshed-fallback/stdlib/3/urllib/robotparser.pyi @@ -0,0 +1,18 @@ +# Stubs for urllib.robotparser (Python 3.4) + +from typing import Iterable, NamedTuple, Optional +import sys + +_RequestRate = NamedTuple('_RequestRate', [('requests', int), ('seconds', int)]) + +class RobotFileParser: + def __init__(self, url: str = ...) -> None: ... + def set_url(self, url: str) -> None: ... + def read(self) -> None: ... + def parse(self, lines: Iterable[str]) -> None: ... + def can_fetch(self, user_agent: str, url: str) -> bool: ... + def mtime(self) -> int: ... + def modified(self) -> None: ... + if sys.version_info >= (3, 6): + def crawl_delay(self, useragent: str) -> Optional[str]: ... + def request_rate(self, useragent: str) -> Optional[_RequestRate]: ... diff --git a/jest.config.js b/jest.config.js new file mode 100644 index 000000000..107b61a49 --- /dev/null +++ b/jest.config.js @@ -0,0 +1,25 @@ +/* +* jest.config.js +* +* Configuration for jest tests. +*/ + +module.exports = { + 'roots': [ + '/src', + '/tests' + ], + 'transform': { + '^.+\\.tsx?$': 'ts-jest' + }, + 'testRegex': '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$', + 'moduleFileExtensions': [ + 'ts', + 'tsx', + 'js', + 'jsx', + 'json', + 'node' + ] +} + diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 000000000..59e68ff69 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,26 @@ +{ + "name": "pyright", + "version": "0.1.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@types/mocha": { + "version": "5.2.6", + "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-5.2.6.tgz", + "integrity": "sha512-1axi39YdtBI7z957vdqXI4Ac25e7YihYQtJa+Clnxg1zTJEaIRbndt71O3sP4GAMgiAm0pY26/b9BrY4MR/PMw==", + "dev": true + }, + "@types/node": { + "version": "11.10.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-11.10.5.tgz", + "integrity": "sha512-DuIRlQbX4K+d5I+GMnv+UfnGh+ist0RdlvOp+JZ7ePJ6KQONCFQv/gKYSU1ZzbVdFSUCKZOltjmpFAGGv5MdYA==", + "dev": true + }, + "typescript": { + "version": "3.3.3333", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.3.3333.tgz", + "integrity": "sha512-JjSKsAfuHBE/fB2oZ8NxtRTk5iGcg6hkYXMnZ3Wc+b2RSqejEqTaem11mHASMnFilHrax3sLK0GDzcJrekZYLw==", + "dev": true + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 000000000..0d6c187e7 --- /dev/null +++ b/package.json @@ -0,0 +1,18 @@ +{ + "name": "pyright", + "displayName": "Pyright", + "description": "VS Code language support for Python", + "version": "0.1.0", + "scripts": { + "postinstall": "cd server && npm install && cd ../client && npm install && cd ..", + "build": "npm run build:client && npm run build:server", + "build:client": "cd client && npm run build && cd ..", + "build:server": "cd server && npm run build && cd ..", + "build:analyzer": "cd server && npm run build:analyzer && cd .." + }, + "devDependencies": { + "@types/mocha": "^5.2.5", + "@types/node": "^11.10.5", + "typescript": "^3.2.2" + } +} diff --git a/server/customInstallServerIntoExtension.js b/server/customInstallServerIntoExtension.js new file mode 100644 index 000000000..7dce03e68 --- /dev/null +++ b/server/customInstallServerIntoExtension.js @@ -0,0 +1,74 @@ +#!/usr/bin/env node + +// This file is based on the "installServerIntoExtension" that ships with the +// vscode-languagserver node package. We needed to modify it because the original +// version does not copy the package-lock.json file, and it uses npm update +// rather than npm install. + +var path = require('path'); +var fs = require('fs'); +var cp = require('child_process'); + +var extensionDirectory = process.argv[2]; +if (!extensionDirectory) { + console.error('No extension directory provided.'); + process.exit(1) +} +extensionDirectory = path.resolve(extensionDirectory) +if (!fs.existsSync(extensionDirectory)) { + console.error('Extension directory ' + extensionDirectory + ' doesn\'t exist on disk.'); + process.exit(1); +} + +var packageFile = process.argv[3]; +if (!packageFile) { + console.error('No package.json file provided.'); + process.exit(1); +} +packageFile = path.resolve(packageFile); +if (!fs.existsSync(packageFile)) { + console.error('Package file ' + packageFile + ' doesn\'t exist on disk.'); + process.exit(1); +} +var tsconfigFile = process.argv[4]; +if (!tsconfigFile) { + console.error('No tsconfig.json file provided'); + process.exit(1); +} +tsconfigFile = path.resolve(tsconfigFile); +if (!fs.existsSync(tsconfigFile)) { + console.error('tsconfig file ' + tsconfigFile + ' doesn\'t exist on disk.') + process.exit(1); +} + +var extensionServerDirectory = path.join(extensionDirectory, 'server') + +var json = require(tsconfigFile); +var compilerOptions = json.compilerOptions; +if (compilerOptions) { + var outDir = compilerOptions.outDir; + if (!outDir || path.join(path.dirname(tsconfigFile), outDir) !== extensionServerDirectory) { + console.error('outDir in ' + process.argv[4] + ' must point to ' + extensionServerDirectory + ' but it points to ' + path.join(path.dirname(tsconfigFile), outDir)); + console.error('Please change outDir in ' + process.argv[4] + ' to ' + path.relative(path.dirname(tsconfigFile), extensionServerDirectory).replace(/\\/g, '/')); + process.exit(1); + } +} + +if (!fs.existsSync(extensionServerDirectory)) { + fs.mkdirSync(extensionServerDirectory); +} + +var dest = path.join(extensionServerDirectory, 'package.json'); +console.log('Copying package.json to extension\'s server location...'); +fs.writeFileSync(dest, fs.readFileSync(packageFile)); + +var packageLockFile = process.argv[5]; +if (fs.existsSync(packageLockFile)) { + const packageLockFileDest = path.join(extensionServerDirectory, 'package-lock.json'); + packageLockFile = path.resolve(packageLockFile); + console.log('Copying package-lock.json to extension\'s server location...'); + fs.writeFileSync(packageLockFileDest, fs.readFileSync(packageLockFile)); +} + +console.log('Installing server npm modules into extension\'s server location...'); +cp.execSync('npm install --production --prefix ' + extensionServerDirectory); diff --git a/server/package-lock.json b/server/package-lock.json new file mode 100644 index 000000000..8010e351b --- /dev/null +++ b/server/package-lock.json @@ -0,0 +1,6800 @@ +{ + "name": "pyright", + "version": "1.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@babel/code-frame": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0.tgz", + "integrity": "sha512-OfC2uemaknXr87bdLUkWog7nYuliM9Ij5HUcajsVcMCpQrcLmtxRbVFTIqmcSkSeYRBFBRxs2FiUqFJDLdiebA==", + "dev": true, + "requires": { + "@babel/highlight": "^7.0.0" + } + }, + "@babel/core": { + "version": "7.3.4", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.3.4.tgz", + "integrity": "sha512-jRsuseXBo9pN197KnDwhhaaBzyZr2oIcLHHTt2oDdQrej5Qp57dCCJafWx5ivU8/alEYDpssYqv1MUqcxwQlrA==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "@babel/generator": "^7.3.4", + "@babel/helpers": "^7.2.0", + "@babel/parser": "^7.3.4", + "@babel/template": "^7.2.2", + "@babel/traverse": "^7.3.4", + "@babel/types": "^7.3.4", + "convert-source-map": "^1.1.0", + "debug": "^4.1.0", + "json5": "^2.1.0", + "lodash": "^4.17.11", + "resolve": "^1.3.2", + "semver": "^5.4.1", + "source-map": "^0.5.0" + } + }, + "@babel/generator": { + "version": "7.3.4", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.3.4.tgz", + "integrity": "sha512-8EXhHRFqlVVWXPezBW5keTiQi/rJMQTg/Y9uVCEZ0CAF3PKtCCaVRnp64Ii1ujhkoDhhF1fVsImoN4yJ2uz4Wg==", + "dev": true, + "requires": { + "@babel/types": "^7.3.4", + "jsesc": "^2.5.1", + "lodash": "^4.17.11", + "source-map": "^0.5.0", + "trim-right": "^1.0.1" + } + }, + "@babel/helper-function-name": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.1.0.tgz", + "integrity": "sha512-A95XEoCpb3TO+KZzJ4S/5uW5fNe26DjBGqf1o9ucyLyCmi1dXq/B3c8iaWTfBk3VvetUxl16e8tIrd5teOCfGw==", + "dev": true, + "requires": { + "@babel/helper-get-function-arity": "^7.0.0", + "@babel/template": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "@babel/helper-get-function-arity": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.0.0.tgz", + "integrity": "sha512-r2DbJeg4svYvt3HOS74U4eWKsUAMRH01Z1ds1zx8KNTPtpTL5JAsdFv8BNyOpVqdFhHkkRDIg5B4AsxmkjAlmQ==", + "dev": true, + "requires": { + "@babel/types": "^7.0.0" + } + }, + "@babel/helper-plugin-utils": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.0.0.tgz", + "integrity": "sha512-CYAOUCARwExnEixLdB6sDm2dIJ/YgEAKDM1MOeMeZu9Ld/bDgVo8aiWrXwcY7OBh+1Ea2uUcVRcxKk0GJvW7QA==", + "dev": true + }, + "@babel/helper-split-export-declaration": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.0.0.tgz", + "integrity": "sha512-MXkOJqva62dfC0w85mEf/LucPPS/1+04nmmRMPEBUB++hiiThQ2zPtX/mEWQ3mtzCEjIJvPY8nuwxXtQeQwUag==", + "dev": true, + "requires": { + "@babel/types": "^7.0.0" + } + }, + "@babel/helpers": { + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.3.1.tgz", + "integrity": "sha512-Q82R3jKsVpUV99mgX50gOPCWwco9Ec5Iln/8Vyu4osNIOQgSrd9RFrQeUvmvddFNoLwMyOUWU+5ckioEKpDoGA==", + "dev": true, + "requires": { + "@babel/template": "^7.1.2", + "@babel/traverse": "^7.1.5", + "@babel/types": "^7.3.0" + } + }, + "@babel/highlight": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.0.0.tgz", + "integrity": "sha512-UFMC4ZeFC48Tpvj7C8UgLvtkaUuovQX+5xNWrsIoMG8o2z+XFKjKaN9iVmS84dPwVN00W4wPmqvYoZF3EGAsfw==", + "dev": true, + "requires": { + "chalk": "^2.0.0", + "esutils": "^2.0.2", + "js-tokens": "^4.0.0" + }, + "dependencies": { + "js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + } + } + }, + "@babel/parser": { + "version": "7.3.4", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.3.4.tgz", + "integrity": "sha512-tXZCqWtlOOP4wgCp6RjRvLmfuhnqTLy9VHwRochJBCP2nDm27JnnuFEnXFASVyQNHk36jD1tAammsCEEqgscIQ==", + "dev": true + }, + "@babel/plugin-syntax-object-rest-spread": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.2.0.tgz", + "integrity": "sha512-t0JKGgqk2We+9may3t0xDdmneaXmyxq0xieYcKHxIsrJO64n1OiMWNUtc5gQK1PA0NpdCRrtZp4z+IUaKugrSA==", + "dev": true, + "requires": { + "@babel/helper-plugin-utils": "^7.0.0" + } + }, + "@babel/template": { + "version": "7.2.2", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.2.2.tgz", + "integrity": "sha512-zRL0IMM02AUDwghf5LMSSDEz7sBCO2YnNmpg3uWTZj/v1rcG2BmQUvaGU8GhU8BvfMh1k2KIAYZ7Ji9KXPUg7g==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "@babel/parser": "^7.2.2", + "@babel/types": "^7.2.2" + } + }, + "@babel/traverse": { + "version": "7.3.4", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.3.4.tgz", + "integrity": "sha512-TvTHKp6471OYEcE/91uWmhR6PrrYywQntCHSaZ8CM8Vmp+pjAusal4nGB2WCCQd0rvI7nOMKn9GnbcvTUz3/ZQ==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "@babel/generator": "^7.3.4", + "@babel/helper-function-name": "^7.1.0", + "@babel/helper-split-export-declaration": "^7.0.0", + "@babel/parser": "^7.3.4", + "@babel/types": "^7.3.4", + "debug": "^4.1.0", + "globals": "^11.1.0", + "lodash": "^4.17.11" + } + }, + "@babel/types": { + "version": "7.3.4", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.3.4.tgz", + "integrity": "sha512-WEkp8MsLftM7O/ty580wAmZzN1nDmCACc5+jFzUt+GUFNNIi3LdRlueYz0YIlmJhlZx1QYDMZL5vdWCL0fNjFQ==", + "dev": true, + "requires": { + "esutils": "^2.0.2", + "lodash": "^4.17.11", + "to-fast-properties": "^2.0.0" + } + }, + "@types/command-line-args": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/command-line-args/-/command-line-args-5.0.0.tgz", + "integrity": "sha512-4eOPXyn5DmP64MCMF8ePDvdlvlzt2a+F8ZaVjqmh2yFCpGjc1kI3kGnCFYX9SCsGTjQcWIyVZ86IHCEyjy/MNg==", + "dev": true + }, + "@types/jest": { + "version": "24.0.9", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-24.0.9.tgz", + "integrity": "sha512-k3OOeevcBYLR5pdsOv5g3OP94h3mrJmLPHFEPWgbbVy2tGv0TZ/TlygiC848ogXhK8NL0I5up7YYtwpCp8xCJA==", + "dev": true, + "requires": { + "@types/jest-diff": "*" + } + }, + "@types/jest-diff": { + "version": "20.0.1", + "resolved": "https://registry.npmjs.org/@types/jest-diff/-/jest-diff-20.0.1.tgz", + "integrity": "sha512-yALhelO3i0hqZwhjtcr6dYyaLoCHbAMshwtj6cGxTvHZAKXHsYGdff6E8EPw3xLKY0ELUTQ69Q1rQiJENnccMA==", + "dev": true + }, + "@types/node": { + "version": "11.10.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-11.10.5.tgz", + "integrity": "sha512-DuIRlQbX4K+d5I+GMnv+UfnGh+ist0RdlvOp+JZ7ePJ6KQONCFQv/gKYSU1ZzbVdFSUCKZOltjmpFAGGv5MdYA==", + "dev": true + }, + "@webassemblyjs/ast": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.8.5.tgz", + "integrity": "sha512-aJMfngIZ65+t71C3y2nBBg5FFG0Okt9m0XEgWZ7Ywgn1oMAT8cNwx00Uv1cQyHtidq0Xn94R4TAywO+LCQ+ZAQ==", + "dev": true, + "requires": { + "@webassemblyjs/helper-module-context": "1.8.5", + "@webassemblyjs/helper-wasm-bytecode": "1.8.5", + "@webassemblyjs/wast-parser": "1.8.5" + } + }, + "@webassemblyjs/floating-point-hex-parser": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.8.5.tgz", + "integrity": "sha512-9p+79WHru1oqBh9ewP9zW95E3XAo+90oth7S5Re3eQnECGq59ly1Ri5tsIipKGpiStHsUYmY3zMLqtk3gTcOtQ==", + "dev": true + }, + "@webassemblyjs/helper-api-error": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.8.5.tgz", + "integrity": "sha512-Za/tnzsvnqdaSPOUXHyKJ2XI7PDX64kWtURyGiJJZKVEdFOsdKUCPTNEVFZq3zJ2R0G5wc2PZ5gvdTRFgm81zA==", + "dev": true + }, + "@webassemblyjs/helper-buffer": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.8.5.tgz", + "integrity": "sha512-Ri2R8nOS0U6G49Q86goFIPNgjyl6+oE1abW1pS84BuhP1Qcr5JqMwRFT3Ah3ADDDYGEgGs1iyb1DGX+kAi/c/Q==", + "dev": true + }, + "@webassemblyjs/helper-code-frame": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-code-frame/-/helper-code-frame-1.8.5.tgz", + "integrity": "sha512-VQAadSubZIhNpH46IR3yWO4kZZjMxN1opDrzePLdVKAZ+DFjkGD/rf4v1jap744uPVU6yjL/smZbRIIJTOUnKQ==", + "dev": true, + "requires": { + "@webassemblyjs/wast-printer": "1.8.5" + } + }, + "@webassemblyjs/helper-fsm": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-fsm/-/helper-fsm-1.8.5.tgz", + "integrity": "sha512-kRuX/saORcg8se/ft6Q2UbRpZwP4y7YrWsLXPbbmtepKr22i8Z4O3V5QE9DbZK908dh5Xya4Un57SDIKwB9eow==", + "dev": true + }, + "@webassemblyjs/helper-module-context": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-module-context/-/helper-module-context-1.8.5.tgz", + "integrity": "sha512-/O1B236mN7UNEU4t9X7Pj38i4VoU8CcMHyy3l2cV/kIF4U5KoHXDVqcDuOs1ltkac90IM4vZdHc52t1x8Yfs3g==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "mamacro": "^0.0.3" + } + }, + "@webassemblyjs/helper-wasm-bytecode": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.8.5.tgz", + "integrity": "sha512-Cu4YMYG3Ddl72CbmpjU/wbP6SACcOPVbHN1dI4VJNJVgFwaKf1ppeFJrwydOG3NDHxVGuCfPlLZNyEdIYlQ6QQ==", + "dev": true + }, + "@webassemblyjs/helper-wasm-section": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.8.5.tgz", + "integrity": "sha512-VV083zwR+VTrIWWtgIUpqfvVdK4ff38loRmrdDBgBT8ADXYsEZ5mPQ4Nde90N3UYatHdYoDIFb7oHzMncI02tA==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-buffer": "1.8.5", + "@webassemblyjs/helper-wasm-bytecode": "1.8.5", + "@webassemblyjs/wasm-gen": "1.8.5" + } + }, + "@webassemblyjs/ieee754": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.8.5.tgz", + "integrity": "sha512-aaCvQYrvKbY/n6wKHb/ylAJr27GglahUO89CcGXMItrOBqRarUMxWLJgxm9PJNuKULwN5n1csT9bYoMeZOGF3g==", + "dev": true, + "requires": { + "@xtuc/ieee754": "^1.2.0" + } + }, + "@webassemblyjs/leb128": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.8.5.tgz", + "integrity": "sha512-plYUuUwleLIziknvlP8VpTgO4kqNaH57Y3JnNa6DLpu/sGcP6hbVdfdX5aHAV716pQBKrfuU26BJK29qY37J7A==", + "dev": true, + "requires": { + "@xtuc/long": "4.2.2" + } + }, + "@webassemblyjs/utf8": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.8.5.tgz", + "integrity": "sha512-U7zgftmQriw37tfD934UNInokz6yTmn29inT2cAetAsaU9YeVCveWEwhKL1Mg4yS7q//NGdzy79nlXh3bT8Kjw==", + "dev": true + }, + "@webassemblyjs/wasm-edit": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.8.5.tgz", + "integrity": "sha512-A41EMy8MWw5yvqj7MQzkDjU29K7UJq1VrX2vWLzfpRHt3ISftOXqrtojn7nlPsZ9Ijhp5NwuODuycSvfAO/26Q==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-buffer": "1.8.5", + "@webassemblyjs/helper-wasm-bytecode": "1.8.5", + "@webassemblyjs/helper-wasm-section": "1.8.5", + "@webassemblyjs/wasm-gen": "1.8.5", + "@webassemblyjs/wasm-opt": "1.8.5", + "@webassemblyjs/wasm-parser": "1.8.5", + "@webassemblyjs/wast-printer": "1.8.5" + } + }, + "@webassemblyjs/wasm-gen": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.8.5.tgz", + "integrity": "sha512-BCZBT0LURC0CXDzj5FXSc2FPTsxwp3nWcqXQdOZE4U7h7i8FqtFK5Egia6f9raQLpEKT1VL7zr4r3+QX6zArWg==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-wasm-bytecode": "1.8.5", + "@webassemblyjs/ieee754": "1.8.5", + "@webassemblyjs/leb128": "1.8.5", + "@webassemblyjs/utf8": "1.8.5" + } + }, + "@webassemblyjs/wasm-opt": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.8.5.tgz", + "integrity": "sha512-HKo2mO/Uh9A6ojzu7cjslGaHaUU14LdLbGEKqTR7PBKwT6LdPtLLh9fPY33rmr5wcOMrsWDbbdCHq4hQUdd37Q==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-buffer": "1.8.5", + "@webassemblyjs/wasm-gen": "1.8.5", + "@webassemblyjs/wasm-parser": "1.8.5" + } + }, + "@webassemblyjs/wasm-parser": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.8.5.tgz", + "integrity": "sha512-pi0SYE9T6tfcMkthwcgCpL0cM9nRYr6/6fjgDtL6q/ZqKHdMWvxitRi5JcZ7RI4SNJJYnYNaWy5UUrHQy998lw==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-api-error": "1.8.5", + "@webassemblyjs/helper-wasm-bytecode": "1.8.5", + "@webassemblyjs/ieee754": "1.8.5", + "@webassemblyjs/leb128": "1.8.5", + "@webassemblyjs/utf8": "1.8.5" + } + }, + "@webassemblyjs/wast-parser": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-parser/-/wast-parser-1.8.5.tgz", + "integrity": "sha512-daXC1FyKWHF1i11obK086QRlsMsY4+tIOKgBqI1lxAnkp9xe9YMcgOxm9kLe+ttjs5aWV2KKE1TWJCN57/Btsg==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/floating-point-hex-parser": "1.8.5", + "@webassemblyjs/helper-api-error": "1.8.5", + "@webassemblyjs/helper-code-frame": "1.8.5", + "@webassemblyjs/helper-fsm": "1.8.5", + "@xtuc/long": "4.2.2" + } + }, + "@webassemblyjs/wast-printer": { + "version": "1.8.5", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.8.5.tgz", + "integrity": "sha512-w0U0pD4EhlnvRyeJzBqaVSJAo9w/ce7/WPogeXLzGkO6hzhr4GnQIZ4W4uUt5b9ooAaXPtnXlj0gzsXEOUNYMg==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/wast-parser": "1.8.5", + "@xtuc/long": "4.2.2" + } + }, + "@xtuc/ieee754": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", + "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", + "dev": true + }, + "@xtuc/long": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", + "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", + "dev": true + }, + "abab": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/abab/-/abab-2.0.0.tgz", + "integrity": "sha512-sY5AXXVZv4Y1VACTtR11UJCPHHudgY5i26Qj5TypE6DKlIApbwb5uqhXcJ5UUGbvZNRh7EeIoW+LrJumBsKp7w==", + "dev": true + }, + "acorn": { + "version": "5.7.3", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-5.7.3.tgz", + "integrity": "sha512-T/zvzYRfbVojPWahDsE5evJdHb3oJoQfFbsrKM7w5Zcs++Tr257tia3BmMP8XYVjp1S9RZXQMh7gao96BlqZOw==", + "dev": true + }, + "acorn-dynamic-import": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/acorn-dynamic-import/-/acorn-dynamic-import-4.0.0.tgz", + "integrity": "sha512-d3OEjQV4ROpoflsnUA8HozoIR504TFxNivYEUi6uwz0IYhBkTDXGuWlNdMtybRt3nqVx/L6XqMt0FxkXuWKZhw==", + "dev": true + }, + "acorn-globals": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-4.3.0.tgz", + "integrity": "sha512-hMtHj3s5RnuhvHPowpBYvJVj3rAar82JiDQHvGs1zO0l10ocX/xEdBShNHTJaboucJUsScghp74pH3s7EnHHQw==", + "dev": true, + "requires": { + "acorn": "^6.0.1", + "acorn-walk": "^6.0.1" + }, + "dependencies": { + "acorn": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.1.1.tgz", + "integrity": "sha512-jPTiwtOxaHNaAPg/dmrJ/beuzLRnXtB0kQPQ8JpotKJgTB6rX6c8mlf315941pyjBSaPg8NHXS9fhP4u17DpGA==", + "dev": true + } + } + }, + "acorn-walk": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-6.1.1.tgz", + "integrity": "sha512-OtUw6JUTgxA2QoqqmrmQ7F2NYqiBPi/L2jqHyFtllhOUvXYQXf0Z1CYUinIfyT4bTCGmrA7gX9FvHA81uzCoVw==", + "dev": true + }, + "ajv": { + "version": "6.10.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.10.0.tgz", + "integrity": "sha512-nffhOpkymDECQyR0mnsUtoCE8RlX38G0rYP+wgLWFyZuUyuuojSSvi/+euOiQBIn63whYwYVIIH1TvE3tu4OEg==", + "dev": true, + "requires": { + "fast-deep-equal": "^2.0.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + } + }, + "ajv-errors": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ajv-errors/-/ajv-errors-1.0.1.tgz", + "integrity": "sha512-DCRfO/4nQ+89p/RK43i8Ezd41EqdGIU4ld7nGF8OQ14oc/we5rEntLCUa7+jrn3nn83BosfwZA0wb4pon2o8iQ==", + "dev": true + }, + "ajv-keywords": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-3.4.0.tgz", + "integrity": "sha512-aUjdRFISbuFOl0EIZc+9e4FfZp0bDZgAdOOf30bJmw8VM9v84SHyVyxDfbWxpGYbdZD/9XoKxfHVNmxPkhwyGw==", + "dev": true + }, + "ansi-escapes": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-3.2.0.tgz", + "integrity": "sha512-cBhpre4ma+U0T1oM5fXg7Dy1Jw7zzwv7lt/GoCpr+hDQJoYnKVPLL4dCvSEFMmQurOQvSrwT7SL/DAlhBI97RQ==", + "dev": true + }, + "ansi-regex": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", + "integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", + "dev": true + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "dev": true, + "requires": { + "color-convert": "^1.9.0" + } + }, + "anymatch": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-2.0.0.tgz", + "integrity": "sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw==", + "dev": true, + "requires": { + "micromatch": "^3.1.4", + "normalize-path": "^2.1.1" + } + }, + "append-transform": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-transform/-/append-transform-1.0.0.tgz", + "integrity": "sha512-P009oYkeHyU742iSZJzZZywj4QRJdnTWffaKuJQLablCZ1uz6/cW4yaRgcDaoQ+uwOxxnt0gRUcwfsNP2ri0gw==", + "dev": true, + "requires": { + "default-require-extensions": "^2.0.0" + } + }, + "aproba": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-1.2.0.tgz", + "integrity": "sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw==", + "dev": true + }, + "argparse": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", + "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", + "dev": true, + "requires": { + "sprintf-js": "~1.0.2" + } + }, + "argv-tools": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/argv-tools/-/argv-tools-0.1.1.tgz", + "integrity": "sha512-Cc0dBvx4dvrjjKpyDA6w8RlNAw8Su30NvZbWl/Tv9ZALEVlLVkWQiHMi84Q0xNfpVuSaiQbYkdmWK8g1PLGhKw==", + "requires": { + "array-back": "^2.0.0", + "find-replace": "^2.0.1" + } + }, + "arr-diff": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/arr-diff/-/arr-diff-4.0.0.tgz", + "integrity": "sha1-1kYQdP6/7HHn4VI1dhoyml3HxSA=", + "dev": true + }, + "arr-flatten": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/arr-flatten/-/arr-flatten-1.1.0.tgz", + "integrity": "sha512-L3hKV5R/p5o81R7O02IGnwpDmkp6E982XhtbuwSe3O4qOtMMMtodicASA1Cny2U+aCXcNpml+m4dPsvsJ3jatg==", + "dev": true + }, + "arr-union": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/arr-union/-/arr-union-3.1.0.tgz", + "integrity": "sha1-45sJrqne+Gao8gbiiK9jkZuuOcQ=", + "dev": true + }, + "array-back": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/array-back/-/array-back-2.0.0.tgz", + "integrity": "sha512-eJv4pLLufP3g5kcZry0j6WXpIbzYw9GUB4mVJZno9wfwiBxbizTnHCw3VJb07cBihbFX48Y7oSrW9y+gt4glyw==", + "requires": { + "typical": "^2.6.1" + } + }, + "array-equal": { + "version": "1.0.0", + "resolved": "http://registry.npmjs.org/array-equal/-/array-equal-1.0.0.tgz", + "integrity": "sha1-jCpe8kcv2ep0KwTHenUJO6J1fJM=", + "dev": true + }, + "array-unique": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/array-unique/-/array-unique-0.3.2.tgz", + "integrity": "sha1-qJS3XUvE9s1nnvMkSp/Y9Gri1Cg=", + "dev": true + }, + "arrify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-1.0.1.tgz", + "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", + "dev": true + }, + "asn1": { + "version": "0.2.4", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz", + "integrity": "sha512-jxwzQpLQjSmWXgwaCZE9Nz+glAG01yF1QnWgbhGwHI5A6FRIEY6IVqtHhIepHqI7/kyEyQEagBC5mBEFlIYvdg==", + "dev": true, + "requires": { + "safer-buffer": "~2.1.0" + } + }, + "asn1.js": { + "version": "4.10.1", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-4.10.1.tgz", + "integrity": "sha512-p32cOF5q0Zqs9uBiONKYLm6BClCoBCM5O9JfeUSlnQLBTxYdTK+pW+nXflm8UkKd2UYlEbYz5qEi0JuZR9ckSw==", + "dev": true, + "requires": { + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + } + }, + "assert": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/assert/-/assert-1.4.1.tgz", + "integrity": "sha1-mZEtWRg2tab1s0XA8H7vwI/GXZE=", + "requires": { + "util": "0.10.3" + } + }, + "assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU=", + "dev": true + }, + "assign-symbols": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assign-symbols/-/assign-symbols-1.0.0.tgz", + "integrity": "sha1-WWZ/QfrdTyDMvCu5a41Pf3jsA2c=", + "dev": true + }, + "astral-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-1.0.0.tgz", + "integrity": "sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg==", + "dev": true + }, + "async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/async/-/async-2.6.2.tgz", + "integrity": "sha512-H1qVYh1MYhEEFLsP97cVKqCGo7KfCyTt6uEWqsTBr9SO84oK9Uwbyd/yCW+6rKJLHksBNUVWZDAjfS+Ccx0Bbg==", + "dev": true, + "requires": { + "lodash": "^4.17.11" + } + }, + "async-each": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/async-each/-/async-each-1.0.1.tgz", + "integrity": "sha1-GdOGodntxufByF04iu28xW0zYC0=", + "dev": true + }, + "async-limiter": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz", + "integrity": "sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==", + "dev": true + }, + "asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha1-x57Zf380y48robyXkLzDZkdLS3k=", + "dev": true + }, + "atob": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/atob/-/atob-2.1.2.tgz", + "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==", + "dev": true + }, + "aws-sign2": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", + "integrity": "sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg=", + "dev": true + }, + "aws4": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.8.0.tgz", + "integrity": "sha512-ReZxvNHIOv88FlT7rxcXIIC0fPt4KZqZbOlivyWtXLt8ESx84zd3kMC6iK5jVeS2qt+g7ftS7ye4fi06X5rtRQ==", + "dev": true + }, + "babel-code-frame": { + "version": "6.26.0", + "resolved": "https://registry.npmjs.org/babel-code-frame/-/babel-code-frame-6.26.0.tgz", + "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", + "dev": true, + "requires": { + "chalk": "^1.1.3", + "esutils": "^2.0.2", + "js-tokens": "^3.0.2" + }, + "dependencies": { + "ansi-styles": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", + "integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", + "dev": true + }, + "chalk": { + "version": "1.1.3", + "resolved": "http://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "supports-color": { + "version": "2.0.0", + "resolved": "http://registry.npmjs.org/supports-color/-/supports-color-2.0.0.tgz", + "integrity": "sha1-U10EXOa2Nj+kARcIRimZXp3zJMc=", + "dev": true + } + } + }, + "babel-jest": { + "version": "24.1.0", + "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-24.1.0.tgz", + "integrity": "sha512-MLcagnVrO9ybQGLEfZUqnOzv36iQzU7Bj4elm39vCukumLVSfoX+tRy3/jW7lUKc7XdpRmB/jech6L/UCsSZjw==", + "dev": true, + "requires": { + "babel-plugin-istanbul": "^5.1.0", + "babel-preset-jest": "^24.1.0", + "chalk": "^2.4.2", + "slash": "^2.0.0" + }, + "dependencies": { + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + } + } + }, + "babel-plugin-istanbul": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-5.1.1.tgz", + "integrity": "sha512-RNNVv2lsHAXJQsEJ5jonQwrJVWK8AcZpG1oxhnjCUaAjL7xahYLANhPUZbzEQHjKy1NMYUwn+0NPKQc8iSY4xQ==", + "dev": true, + "requires": { + "find-up": "^3.0.0", + "istanbul-lib-instrument": "^3.0.0", + "test-exclude": "^5.0.0" + } + }, + "babel-plugin-jest-hoist": { + "version": "24.1.0", + "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-24.1.0.tgz", + "integrity": "sha512-gljYrZz8w1b6fJzKcsfKsipSru2DU2DmQ39aB6nV3xQ0DDv3zpIzKGortA5gknrhNnPN8DweaEgrnZdmbGmhnw==", + "dev": true + }, + "babel-preset-jest": { + "version": "24.1.0", + "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-24.1.0.tgz", + "integrity": "sha512-FfNLDxFWsNX9lUmtwY7NheGlANnagvxq8LZdl5PKnVG3umP+S/g0XbVBfwtA4Ai3Ri/IMkWabBz3Tyk9wdspcw==", + "dev": true, + "requires": { + "@babel/plugin-syntax-object-rest-spread": "^7.0.0", + "babel-plugin-jest-hoist": "^24.1.0" + } + }, + "balanced-match": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "dev": true + }, + "base": { + "version": "0.11.2", + "resolved": "https://registry.npmjs.org/base/-/base-0.11.2.tgz", + "integrity": "sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==", + "dev": true, + "requires": { + "cache-base": "^1.0.1", + "class-utils": "^0.3.5", + "component-emitter": "^1.2.1", + "define-property": "^1.0.0", + "isobject": "^3.0.1", + "mixin-deep": "^1.2.0", + "pascalcase": "^0.1.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "base64-js": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.3.0.tgz", + "integrity": "sha512-ccav/yGvoa80BQDljCxsmmQ3Xvx60/UpBIij5QN21W3wBi/hhIC9OoO+KLpu9IJTS9j4DRVJ3aDDF9cMSoa2lw==", + "dev": true + }, + "bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4=", + "dev": true, + "requires": { + "tweetnacl": "^0.14.3" + } + }, + "big.js": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/big.js/-/big.js-5.2.2.tgz", + "integrity": "sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==", + "dev": true + }, + "binary-extensions": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-1.13.0.tgz", + "integrity": "sha512-EgmjVLMn22z7eGGv3kcnHwSnJXmFHjISTY9E/S5lIcTD3Oxw05QTcBLNkJFzcb3cNueUdF/IN4U+d78V0zO8Hw==", + "dev": true + }, + "bluebird": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.3.tgz", + "integrity": "sha512-/qKPUQlaW1OyR51WeCPBvRnAlnZFUJkCSG5HzGnuIqhgyJtF+T94lFnn33eiazjRm2LAHVy2guNnaq48X9SJuw==", + "dev": true + }, + "bn.js": { + "version": "4.11.8", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.11.8.tgz", + "integrity": "sha512-ItfYfPLkWHUjckQCk8xC+LwxgK8NYcXywGigJgSwOP8Y2iyWT4f2vsZnoOXTTbo+o5yXmIUJ4gn5538SO5S3gA==", + "dev": true + }, + "brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dev": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "braces": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-2.3.2.tgz", + "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==", + "dev": true, + "requires": { + "arr-flatten": "^1.1.0", + "array-unique": "^0.3.2", + "extend-shallow": "^2.0.1", + "fill-range": "^4.0.0", + "isobject": "^3.0.1", + "repeat-element": "^1.1.2", + "snapdragon": "^0.8.1", + "snapdragon-node": "^2.0.1", + "split-string": "^3.0.2", + "to-regex": "^3.0.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "brorand": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/brorand/-/brorand-1.1.0.tgz", + "integrity": "sha1-EsJe/kCkXjwyPrhnWgoM5XsiNx8=", + "dev": true + }, + "browser-process-hrtime": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/browser-process-hrtime/-/browser-process-hrtime-0.1.3.tgz", + "integrity": "sha512-bRFnI4NnjO6cnyLmOV/7PVoDEMJChlcfN0z4s1YMBY989/SvlfMI1lgCnkFUs53e9gQF+w7qu7XdllSTiSl8Aw==", + "dev": true + }, + "browser-resolve": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/browser-resolve/-/browser-resolve-1.11.3.tgz", + "integrity": "sha512-exDi1BYWB/6raKHmDTCicQfTkqwN5fioMFV4j8BsfMU4R2DK/QfZfK7kOVkmWCNANf0snkBzqGqAJBao9gZMdQ==", + "dev": true, + "requires": { + "resolve": "1.1.7" + }, + "dependencies": { + "resolve": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.1.7.tgz", + "integrity": "sha1-IDEU2CrSxe2ejgQRs5ModeiJ6Xs=", + "dev": true + } + } + }, + "browserify-aes": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", + "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", + "dev": true, + "requires": { + "buffer-xor": "^1.0.3", + "cipher-base": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.3", + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "browserify-cipher": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/browserify-cipher/-/browserify-cipher-1.0.1.tgz", + "integrity": "sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w==", + "dev": true, + "requires": { + "browserify-aes": "^1.0.4", + "browserify-des": "^1.0.0", + "evp_bytestokey": "^1.0.0" + } + }, + "browserify-des": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/browserify-des/-/browserify-des-1.0.2.tgz", + "integrity": "sha512-BioO1xf3hFwz4kc6iBhI3ieDFompMhrMlnDFC4/0/vd5MokpuAc3R+LYbwTA9A5Yc9pq9UYPqffKpW2ObuwX5A==", + "dev": true, + "requires": { + "cipher-base": "^1.0.1", + "des.js": "^1.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "browserify-rsa": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz", + "integrity": "sha1-IeCr+vbyApzy+vsTNWenAdQTVSQ=", + "dev": true, + "requires": { + "bn.js": "^4.1.0", + "randombytes": "^2.0.1" + } + }, + "browserify-sign": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/browserify-sign/-/browserify-sign-4.0.4.tgz", + "integrity": "sha1-qk62jl17ZYuqa/alfmMMvXqT0pg=", + "dev": true, + "requires": { + "bn.js": "^4.1.1", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.2", + "elliptic": "^6.0.0", + "inherits": "^2.0.1", + "parse-asn1": "^5.0.0" + } + }, + "browserify-zlib": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/browserify-zlib/-/browserify-zlib-0.2.0.tgz", + "integrity": "sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==", + "dev": true, + "requires": { + "pako": "~1.0.5" + } + }, + "bs-logger": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz", + "integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==", + "dev": true, + "requires": { + "fast-json-stable-stringify": "2.x" + } + }, + "bser": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/bser/-/bser-2.0.0.tgz", + "integrity": "sha1-mseNPtXZFYBP2HrLFYvHlxR6Fxk=", + "dev": true, + "requires": { + "node-int64": "^0.4.0" + } + }, + "buffer": { + "version": "4.9.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.1.tgz", + "integrity": "sha1-bRu2AbB6TvztlwlBMgkwJ8lbwpg=", + "dev": true, + "requires": { + "base64-js": "^1.0.2", + "ieee754": "^1.1.4", + "isarray": "^1.0.0" + } + }, + "buffer-from": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz", + "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", + "dev": true + }, + "buffer-xor": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", + "integrity": "sha1-JuYe0UIvtw3ULm42cp7VHYVf6Nk=", + "dev": true + }, + "builtin-modules": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz", + "integrity": "sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8=", + "dev": true + }, + "builtin-status-codes": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/builtin-status-codes/-/builtin-status-codes-3.0.0.tgz", + "integrity": "sha1-hZgoeOIbmOHGZCXgPQF0eI9Wnug=", + "dev": true + }, + "cacache": { + "version": "11.3.2", + "resolved": "https://registry.npmjs.org/cacache/-/cacache-11.3.2.tgz", + "integrity": "sha512-E0zP4EPGDOaT2chM08Als91eYnf8Z+eH1awwwVsngUmgppfM5jjJ8l3z5vO5p5w/I3LsiXawb1sW0VY65pQABg==", + "dev": true, + "requires": { + "bluebird": "^3.5.3", + "chownr": "^1.1.1", + "figgy-pudding": "^3.5.1", + "glob": "^7.1.3", + "graceful-fs": "^4.1.15", + "lru-cache": "^5.1.1", + "mississippi": "^3.0.0", + "mkdirp": "^0.5.1", + "move-concurrently": "^1.0.1", + "promise-inflight": "^1.0.1", + "rimraf": "^2.6.2", + "ssri": "^6.0.1", + "unique-filename": "^1.1.1", + "y18n": "^4.0.0" + } + }, + "cache-base": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/cache-base/-/cache-base-1.0.1.tgz", + "integrity": "sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==", + "dev": true, + "requires": { + "collection-visit": "^1.0.0", + "component-emitter": "^1.2.1", + "get-value": "^2.0.6", + "has-value": "^1.0.0", + "isobject": "^3.0.1", + "set-value": "^2.0.0", + "to-object-path": "^0.3.0", + "union-value": "^1.0.0", + "unset-value": "^1.0.0" + } + }, + "callsites": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.0.0.tgz", + "integrity": "sha512-tWnkwu9YEq2uzlBDI4RcLn8jrFvF9AOi8PxDNU3hZZjJcjkcRAq3vCI+vZcg1SuxISDYe86k9VZFwAxDiJGoAw==", + "dev": true + }, + "camelcase": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.2.0.tgz", + "integrity": "sha512-IXFsBS2pC+X0j0N/GE7Dm7j3bsEBp+oTpb7F50dwEVX7rf3IgwO9XatnegTsDtniKCUtEJH4fSU6Asw7uoVLfQ==", + "dev": true + }, + "capture-exit": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/capture-exit/-/capture-exit-1.2.0.tgz", + "integrity": "sha1-HF/MSJ/QqwDU8ax64QcuMXP7q28=", + "dev": true, + "requires": { + "rsvp": "^3.3.3" + } + }, + "caseless": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw=", + "dev": true + }, + "chalk": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.1.tgz", + "integrity": "sha512-ObN6h1v2fTJSmUXoS3nMQ92LbDK9be4TV+6G+omQlGJFdcUX5heKi1LZ1YnRMIgwTLEj3E24bT6tYni50rlCfQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "chokidar": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-2.1.2.tgz", + "integrity": "sha512-IwXUx0FXc5ibYmPC2XeEj5mpXoV66sR+t3jqu2NS2GYwCktt3KF1/Qqjws/NkegajBA4RbZ5+DDwlOiJsxDHEg==", + "dev": true, + "requires": { + "anymatch": "^2.0.0", + "async-each": "^1.0.1", + "braces": "^2.3.2", + "fsevents": "^1.2.7", + "glob-parent": "^3.1.0", + "inherits": "^2.0.3", + "is-binary-path": "^1.0.0", + "is-glob": "^4.0.0", + "normalize-path": "^3.0.0", + "path-is-absolute": "^1.0.0", + "readdirp": "^2.2.1", + "upath": "^1.1.0" + }, + "dependencies": { + "normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true + } + } + }, + "chownr": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.1.tgz", + "integrity": "sha512-j38EvO5+LHX84jlo6h4UzmOwi0UgW61WRyPtJz4qaadK5eY3BTS5TY/S1Stc3Uk2lIM6TPevAlULiEJwie860g==", + "dev": true + }, + "chrome-trace-event": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.0.tgz", + "integrity": "sha512-xDbVgyfDTT2piup/h8dK/y4QZfJRSa73bw1WZ8b4XM1o7fsFubUVGYcE+1ANtOzJJELGpYoG2961z0Z6OAld9A==", + "dev": true, + "requires": { + "tslib": "^1.9.0" + } + }, + "ci-info": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-2.0.0.tgz", + "integrity": "sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==", + "dev": true + }, + "cipher-base": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/cipher-base/-/cipher-base-1.0.4.tgz", + "integrity": "sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q==", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "class-utils": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", + "integrity": "sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==", + "dev": true, + "requires": { + "arr-union": "^3.1.0", + "define-property": "^0.2.5", + "isobject": "^3.0.0", + "static-extend": "^0.1.1" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + } + } + }, + "cliui": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-4.1.0.tgz", + "integrity": "sha512-4FG+RSG9DL7uEwRUZXZn3SS34DiDPfzP0VOiEwtUWlE+AR2EIg+hSyvrIgUUfhdgR/UkAeW2QHgeP+hWrXs7jQ==", + "dev": true, + "requires": { + "string-width": "^2.1.1", + "strip-ansi": "^4.0.0", + "wrap-ansi": "^2.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "dev": true + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "dev": true, + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, + "co": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", + "integrity": "sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=", + "dev": true + }, + "code-point-at": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/code-point-at/-/code-point-at-1.1.0.tgz", + "integrity": "sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c=", + "dev": true + }, + "collection-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/collection-visit/-/collection-visit-1.0.0.tgz", + "integrity": "sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=", + "dev": true, + "requires": { + "map-visit": "^1.0.0", + "object-visit": "^1.0.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "dev": true, + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", + "dev": true + }, + "combined-stream": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.7.tgz", + "integrity": "sha512-brWl9y6vOB1xYPZcpZde3N9zDByXTosAeMDo4p1wzo6UMOX4vumB+TP1RZ76sfE6Md68Q0NJSrE/gbezd4Ul+w==", + "dev": true, + "requires": { + "delayed-stream": "~1.0.0" + } + }, + "command-line-args": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.0.2.tgz", + "integrity": "sha512-/qPcbL8zpqg53x4rAaqMFlRV4opN3pbla7I7k9x8kyOBMQoGT6WltjN6sXZuxOXw6DgdK7Ad+ijYS5gjcr7vlA==", + "requires": { + "argv-tools": "^0.1.1", + "array-back": "^2.0.0", + "find-replace": "^2.0.1", + "lodash.camelcase": "^4.3.0", + "typical": "^2.6.1" + } + }, + "commander": { + "version": "2.17.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.17.1.tgz", + "integrity": "sha512-wPMUt6FnH2yzG95SA6mzjQOEKUU3aLaDEmzs1ti+1E9h+CsrZghRlqEM/EJ4KscsQVG8uNN4uVreUeT8+drlgg==", + "dev": true + }, + "commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha1-3dgA2gxmEnOTzKWVDqloo6rxJTs=", + "dev": true + }, + "compare-versions": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-3.4.0.tgz", + "integrity": "sha512-tK69D7oNXXqUW3ZNo/z7NXTEz22TCF0pTE+YF9cxvaAM9XnkLo1fV621xCLrRR6aevJlKxExkss0vWqUCUpqdg==", + "dev": true + }, + "component-emitter": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.2.1.tgz", + "integrity": "sha1-E3kY1teCg/ffemt8WmPhQOaUJeY=", + "dev": true + }, + "concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "dev": true + }, + "concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "console-browserify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-browserify/-/console-browserify-1.1.0.tgz", + "integrity": "sha1-8CQcRXMKn8YyOyBtvzjtx0HQuxA=", + "dev": true, + "requires": { + "date-now": "^0.1.4" + } + }, + "constants-browserify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/constants-browserify/-/constants-browserify-1.0.0.tgz", + "integrity": "sha1-wguW2MYXdIqvHBYCF2DNJ/y4y3U=", + "dev": true + }, + "convert-source-map": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.6.0.tgz", + "integrity": "sha512-eFu7XigvxdZ1ETfbgPBohgyQ/Z++C0eEhTor0qRwBw9unw+L0/6V8wkSuGgzdThkiS5lSpdptOQPD8Ak40a+7A==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.1" + } + }, + "copy-concurrently": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/copy-concurrently/-/copy-concurrently-1.0.5.tgz", + "integrity": "sha512-f2domd9fsVDFtaFcbaRZuYXwtdmnzqbADSwhSWYxYB/Q8zsdUUFMXVRwXGDMWmbEzAn1kdRrtI1T/KTFOL4X2A==", + "dev": true, + "requires": { + "aproba": "^1.1.1", + "fs-write-stream-atomic": "^1.0.8", + "iferr": "^0.1.5", + "mkdirp": "^0.5.1", + "rimraf": "^2.5.4", + "run-queue": "^1.0.0" + } + }, + "copy-descriptor": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/copy-descriptor/-/copy-descriptor-0.1.1.tgz", + "integrity": "sha1-Z29us8OZl8LuGsOpJP1hJHSPV40=", + "dev": true + }, + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", + "dev": true + }, + "create-ecdh": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/create-ecdh/-/create-ecdh-4.0.3.tgz", + "integrity": "sha512-GbEHQPMOswGpKXM9kCWVrremUcBmjteUaQ01T9rkKCPDXfUHX0IoP9LpHYo2NPFampa4e+/pFDc3jQdxrxQLaw==", + "dev": true, + "requires": { + "bn.js": "^4.1.0", + "elliptic": "^6.0.0" + } + }, + "create-hash": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", + "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", + "dev": true, + "requires": { + "cipher-base": "^1.0.1", + "inherits": "^2.0.1", + "md5.js": "^1.3.4", + "ripemd160": "^2.0.1", + "sha.js": "^2.4.0" + } + }, + "create-hmac": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", + "integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==", + "dev": true, + "requires": { + "cipher-base": "^1.0.3", + "create-hash": "^1.1.0", + "inherits": "^2.0.1", + "ripemd160": "^2.0.0", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" + } + }, + "cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "dev": true, + "requires": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "crypto-browserify": { + "version": "3.12.0", + "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-3.12.0.tgz", + "integrity": "sha512-fz4spIh+znjO2VjL+IdhEpRJ3YN6sMzITSBijk6FK2UvTqruSQW+/cCZTSNsMiZNvUeq0CqurF+dAbyiGOY6Wg==", + "dev": true, + "requires": { + "browserify-cipher": "^1.0.0", + "browserify-sign": "^4.0.0", + "create-ecdh": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.0", + "diffie-hellman": "^5.0.0", + "inherits": "^2.0.1", + "pbkdf2": "^3.0.3", + "public-encrypt": "^4.0.0", + "randombytes": "^2.0.0", + "randomfill": "^1.0.3" + } + }, + "cssom": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/cssom/-/cssom-0.3.6.tgz", + "integrity": "sha512-DtUeseGk9/GBW0hl0vVPpU22iHL6YB5BUX7ml1hB+GMpo0NX5G4voX3kdWiMSEguFtcW3Vh3djqNF4aIe6ne0A==", + "dev": true + }, + "cssstyle": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-1.2.1.tgz", + "integrity": "sha512-7DYm8qe+gPx/h77QlCyFmX80+fGaE/6A/Ekl0zaszYOubvySO2saYFdQ78P29D0UsULxFKCetDGNaNRUdSF+2A==", + "dev": true, + "requires": { + "cssom": "0.3.x" + } + }, + "cyclist": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/cyclist/-/cyclist-0.2.2.tgz", + "integrity": "sha1-GzN5LhHpFKL9bW7WRHRkRE5fpkA=", + "dev": true + }, + "dashdash": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", + "dev": true, + "requires": { + "assert-plus": "^1.0.0" + } + }, + "data-urls": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-1.1.0.tgz", + "integrity": "sha512-YTWYI9se1P55u58gL5GkQHW4P6VJBJ5iBT+B5a7i2Tjadhv52paJG0qHX4A0OR6/t52odI64KP2YvFpkDOi3eQ==", + "dev": true, + "requires": { + "abab": "^2.0.0", + "whatwg-mimetype": "^2.2.0", + "whatwg-url": "^7.0.0" + }, + "dependencies": { + "whatwg-url": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-7.0.0.tgz", + "integrity": "sha512-37GeVSIJ3kn1JgKyjiYNmSLP1yzbpb29jdmwBSgkD9h40/hyrR/OifpVUndji3tmwGgD8qpw7iQu3RSbCrBpsQ==", + "dev": true, + "requires": { + "lodash.sortby": "^4.7.0", + "tr46": "^1.0.1", + "webidl-conversions": "^4.0.2" + } + } + } + }, + "date-now": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/date-now/-/date-now-0.1.4.tgz", + "integrity": "sha1-6vQ5/U1ISK105cx9vvIAZyueNFs=", + "dev": true + }, + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "dev": true, + "requires": { + "ms": "^2.1.1" + } + }, + "decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=", + "dev": true + }, + "decode-uri-component": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.0.tgz", + "integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=", + "dev": true + }, + "deep-is": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz", + "integrity": "sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=", + "dev": true + }, + "default-require-extensions": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/default-require-extensions/-/default-require-extensions-2.0.0.tgz", + "integrity": "sha1-9fj7sYp9bVCyH2QfZJ67Uiz+JPc=", + "dev": true, + "requires": { + "strip-bom": "^3.0.0" + } + }, + "define-properties": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.1.3.tgz", + "integrity": "sha512-3MqfYKj2lLzdMSf8ZIZE/V+Zuy+BgD6f164e8K2w7dgnpKArBDerGYpM46IYYcjnkdPNMjPk9A6VFB8+3SKlXQ==", + "dev": true, + "requires": { + "object-keys": "^1.0.12" + } + }, + "define-property": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-2.0.2.tgz", + "integrity": "sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ==", + "dev": true, + "requires": { + "is-descriptor": "^1.0.2", + "isobject": "^3.0.1" + }, + "dependencies": { + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=", + "dev": true + }, + "des.js": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/des.js/-/des.js-1.0.0.tgz", + "integrity": "sha1-wHTS4qpqipoH29YfmhXCzYPsjsw=", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" + } + }, + "detect-file": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/detect-file/-/detect-file-1.0.0.tgz", + "integrity": "sha1-8NZtA2cqglyxtzvbP+YjEMjlUrc=", + "dev": true + }, + "detect-newline": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-2.1.0.tgz", + "integrity": "sha1-9B8cEL5LAOh7XxPaaAdZ8sW/0+I=", + "dev": true + }, + "diff": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-3.5.0.tgz", + "integrity": "sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA==", + "dev": true + }, + "diff-sequences": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-24.0.0.tgz", + "integrity": "sha512-46OkIuVGBBnrC0soO/4LHu5LHGHx0uhP65OVz8XOrAJpqiCB2aVIuESvjI1F9oqebuvY8lekS1pt6TN7vt7qsw==", + "dev": true + }, + "diffie-hellman": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", + "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==", + "dev": true, + "requires": { + "bn.js": "^4.1.0", + "miller-rabin": "^4.0.0", + "randombytes": "^2.0.0" + } + }, + "domain-browser": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/domain-browser/-/domain-browser-1.2.0.tgz", + "integrity": "sha512-jnjyiM6eRyZl2H+W8Q/zLMA481hzi0eszAaBUzIVnmYVDBbnLxVNnfu1HgEBvCbL+71FrxMl3E6lpKH7Ge3OXA==", + "dev": true + }, + "domexception": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/domexception/-/domexception-1.0.1.tgz", + "integrity": "sha512-raigMkn7CJNNo6Ihro1fzG7wr3fHuYVytzquZKX5n0yizGsTcYgzdIUwj1X9pK0VvjeihV+XiclP+DjwbsSKug==", + "dev": true, + "requires": { + "webidl-conversions": "^4.0.2" + } + }, + "duplexify": { + "version": "3.7.1", + "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-3.7.1.tgz", + "integrity": "sha512-07z8uv2wMyS51kKhD1KsdXJg5WQ6t93RneqRxUHnskXVtlYYkLqM0gqStQZ3pj073g687jPCHrqNfCzawLYh5g==", + "dev": true, + "requires": { + "end-of-stream": "^1.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.0.0", + "stream-shift": "^1.0.0" + } + }, + "ecc-jsbn": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", + "integrity": "sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=", + "dev": true, + "requires": { + "jsbn": "~0.1.0", + "safer-buffer": "^2.1.0" + } + }, + "elliptic": { + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.4.1.tgz", + "integrity": "sha512-BsXLz5sqX8OHcsh7CqBMztyXARmGQ3LWPtGjJi6DiJHq5C/qvi9P3OqgswKSDftbu8+IoI/QDTAm2fFnQ9SZSQ==", + "dev": true, + "requires": { + "bn.js": "^4.4.0", + "brorand": "^1.0.1", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.0" + } + }, + "emojis-list": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-2.1.0.tgz", + "integrity": "sha1-TapNnbAPmBmIDHn6RXrlsJof04k=", + "dev": true + }, + "end-of-stream": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.1.tgz", + "integrity": "sha512-1MkrZNvWTKCaigbn+W15elq2BB/L22nqrSY5DKlo3X6+vclJm8Bb5djXJBmEX6fS3+zCh/F4VBK5Z2KxJt4s2Q==", + "dev": true, + "requires": { + "once": "^1.4.0" + } + }, + "enhanced-resolve": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-4.1.0.tgz", + "integrity": "sha512-F/7vkyTtyc/llOIn8oWclcB25KdRaiPBpZYDgJHgh/UHtpgT2p2eldQgtQnLtUvfMKPKxbRaQM/hHkvLHt1Vng==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "memory-fs": "^0.4.0", + "tapable": "^1.0.0" + } + }, + "errno": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/errno/-/errno-0.1.7.tgz", + "integrity": "sha512-MfrRBDWzIWifgq6tJj60gkAwtLNb6sQPlcFrSOflcP1aFmmruKQ2wRnze/8V6kgyz7H3FF8Npzv78mZ7XLLflg==", + "dev": true, + "requires": { + "prr": "~1.0.1" + } + }, + "error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "dev": true, + "requires": { + "is-arrayish": "^0.2.1" + } + }, + "es-abstract": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.13.0.tgz", + "integrity": "sha512-vDZfg/ykNxQVwup/8E1BZhVzFfBxs9NqMzGcvIJrqg5k2/5Za2bWo40dK2J1pgLngZ7c+Shh8lwYtLGyrwPutg==", + "dev": true, + "requires": { + "es-to-primitive": "^1.2.0", + "function-bind": "^1.1.1", + "has": "^1.0.3", + "is-callable": "^1.1.4", + "is-regex": "^1.0.4", + "object-keys": "^1.0.12" + } + }, + "es-to-primitive": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.2.0.tgz", + "integrity": "sha512-qZryBOJjV//LaxLTV6UC//WewneB3LcXOL9NP++ozKVXsIIIpm/2c13UDiD9Jp2eThsecw9m3jPqDwTyobcdbg==", + "dev": true, + "requires": { + "is-callable": "^1.1.4", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.2" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", + "dev": true + }, + "escodegen": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-1.11.1.tgz", + "integrity": "sha512-JwiqFD9KdGVVpeuRa68yU3zZnBEOcPs0nKW7wZzXky8Z7tffdYUHbe11bPCV5jYlK6DVdKLWLm0f5I/QlL0Kmw==", + "dev": true, + "requires": { + "esprima": "^3.1.3", + "estraverse": "^4.2.0", + "esutils": "^2.0.2", + "optionator": "^0.8.1", + "source-map": "~0.6.1" + }, + "dependencies": { + "esprima": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-3.1.3.tgz", + "integrity": "sha1-/cpRzuYTOJXjyI1TXOSdv/YqRjM=", + "dev": true + }, + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "optional": true + } + } + }, + "eslint-scope": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-4.0.2.tgz", + "integrity": "sha512-5q1+B/ogmHl8+paxtOKx38Z8LtWkVGuNt3+GQNErqwLl6ViNp/gdJGMCjZNxZ8j/VYjDNZ2Fo+eQc1TAVPIzbg==", + "dev": true, + "requires": { + "esrecurse": "^4.1.0", + "estraverse": "^4.1.1" + } + }, + "esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "dev": true + }, + "esrecurse": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.2.1.tgz", + "integrity": "sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ==", + "dev": true, + "requires": { + "estraverse": "^4.1.0" + } + }, + "estraverse": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.2.0.tgz", + "integrity": "sha1-De4/7TH81GlhjOc0IJn8GvoL2xM=", + "dev": true + }, + "esutils": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.2.tgz", + "integrity": "sha1-Cr9PHKpbyx96nYrMbepPqqBLrJs=", + "dev": true + }, + "events": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.0.0.tgz", + "integrity": "sha512-Dc381HFWJzEOhQ+d8pkNon++bk9h6cdAoAj4iE6Q4y6xgTzySWXlKn05/TVNpjnfRqi/X0EpJEJohPjNI3zpVA==", + "dev": true + }, + "evp_bytestokey": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/evp_bytestokey/-/evp_bytestokey-1.0.3.tgz", + "integrity": "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==", + "dev": true, + "requires": { + "md5.js": "^1.3.4", + "safe-buffer": "^5.1.1" + } + }, + "exec-sh": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/exec-sh/-/exec-sh-0.2.2.tgz", + "integrity": "sha512-FIUCJz1RbuS0FKTdaAafAByGS0CPvU3R0MeHxgtl+djzCc//F8HakL8GzmVNZanasTbTAY/3DRFA0KpVqj/eAw==", + "dev": true, + "requires": { + "merge": "^1.2.0" + } + }, + "execa": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", + "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", + "dev": true, + "requires": { + "cross-spawn": "^6.0.0", + "get-stream": "^4.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + } + }, + "exit": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", + "integrity": "sha1-BjJjj42HfMghB9MKD/8aF8uhzQw=", + "dev": true + }, + "expand-brackets": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/expand-brackets/-/expand-brackets-2.1.4.tgz", + "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", + "dev": true, + "requires": { + "debug": "^2.3.3", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "posix-character-classes": "^0.1.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + } + } + }, + "expand-tilde": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/expand-tilde/-/expand-tilde-2.0.2.tgz", + "integrity": "sha1-l+gBqgUt8CRU3kawK/YhZCzchQI=", + "dev": true, + "requires": { + "homedir-polyfill": "^1.0.1" + } + }, + "expect": { + "version": "24.1.0", + "resolved": "https://registry.npmjs.org/expect/-/expect-24.1.0.tgz", + "integrity": "sha512-lVcAPhaYkQcIyMS+F8RVwzbm1jro20IG8OkvxQ6f1JfqhVZyyudCwYogQ7wnktlf14iF3ii7ArIUO/mqvrW9Gw==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.0", + "jest-get-type": "^24.0.0", + "jest-matcher-utils": "^24.0.0", + "jest-message-util": "^24.0.0", + "jest-regex-util": "^24.0.0" + } + }, + "extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "dev": true + }, + "extend-shallow": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-3.0.2.tgz", + "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", + "dev": true, + "requires": { + "assign-symbols": "^1.0.0", + "is-extendable": "^1.0.1" + }, + "dependencies": { + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "dev": true, + "requires": { + "is-plain-object": "^2.0.4" + } + } + } + }, + "extglob": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/extglob/-/extglob-2.0.4.tgz", + "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", + "dev": true, + "requires": { + "array-unique": "^0.3.2", + "define-property": "^1.0.0", + "expand-brackets": "^2.1.4", + "extend-shallow": "^2.0.1", + "fragment-cache": "^0.2.1", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha1-lpGEQOMEGnpBT4xS48V06zw+HgU=", + "dev": true + }, + "fast-deep-equal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-2.0.1.tgz", + "integrity": "sha1-ewUhjd+WZ79/Nwv3/bLLFf3Qqkk=", + "dev": true + }, + "fast-json-stable-stringify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.0.0.tgz", + "integrity": "sha1-1RQsDK7msRifh9OnYREGT4bIu/I=", + "dev": true + }, + "fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=", + "dev": true + }, + "fb-watchman": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.0.tgz", + "integrity": "sha1-VOmr99+i8mzZsWNsWIwa/AXeXVg=", + "dev": true, + "requires": { + "bser": "^2.0.0" + } + }, + "figgy-pudding": { + "version": "3.5.1", + "resolved": "https://registry.npmjs.org/figgy-pudding/-/figgy-pudding-3.5.1.tgz", + "integrity": "sha512-vNKxJHTEKNThjfrdJwHc7brvM6eVevuO5nTj6ez8ZQ1qbXTvGthucRF7S4vf2cr71QVnT70V34v0S1DyQsti0w==", + "dev": true + }, + "fileset": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/fileset/-/fileset-2.0.3.tgz", + "integrity": "sha1-jnVIqW08wjJ+5eZ0FocjozO7oqA=", + "dev": true, + "requires": { + "glob": "^7.0.3", + "minimatch": "^3.0.3" + } + }, + "fill-range": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-4.0.0.tgz", + "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-number": "^3.0.0", + "repeat-string": "^1.6.1", + "to-regex-range": "^2.1.0" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "find-cache-dir": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-2.0.0.tgz", + "integrity": "sha512-LDUY6V1Xs5eFskUVYtIwatojt6+9xC9Chnlk/jYOOvn3FAFfSaWddxahDGyNHh0b2dMXa6YW2m0tk8TdVaXHlA==", + "dev": true, + "requires": { + "commondir": "^1.0.1", + "make-dir": "^1.0.0", + "pkg-dir": "^3.0.0" + } + }, + "find-replace": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-2.0.1.tgz", + "integrity": "sha512-LzDo3Fpa30FLIBsh6DCDnMN1KW2g4QKkqKmejlImgWY67dDFPX/x9Kh/op/GK522DchQXEvDi/wD48HKW49XOQ==", + "requires": { + "array-back": "^2.0.0", + "test-value": "^3.0.0" + } + }, + "find-up": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", + "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "dev": true, + "requires": { + "locate-path": "^3.0.0" + } + }, + "findup-sync": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-2.0.0.tgz", + "integrity": "sha1-kyaxSIwi0aYIhlCoaQGy2akKLLw=", + "dev": true, + "requires": { + "detect-file": "^1.0.0", + "is-glob": "^3.1.0", + "micromatch": "^3.0.4", + "resolve-dir": "^1.0.1" + }, + "dependencies": { + "is-glob": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", + "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", + "dev": true, + "requires": { + "is-extglob": "^2.1.0" + } + } + } + }, + "flush-write-stream": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/flush-write-stream/-/flush-write-stream-1.1.1.tgz", + "integrity": "sha512-3Z4XhFZ3992uIq0XOqb9AreonueSYphE6oYbpt5+3u06JWklbsPkNv3ZKkP9Bz/r+1MWCaMoSQ28P85+1Yc77w==", + "dev": true, + "requires": { + "inherits": "^2.0.3", + "readable-stream": "^2.3.6" + } + }, + "for-in": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", + "integrity": "sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=", + "dev": true + }, + "forever-agent": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", + "integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE=", + "dev": true + }, + "form-data": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", + "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", + "dev": true, + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.6", + "mime-types": "^2.1.12" + } + }, + "fragment-cache": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/fragment-cache/-/fragment-cache-0.2.1.tgz", + "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=", + "dev": true, + "requires": { + "map-cache": "^0.2.2" + } + }, + "from2": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/from2/-/from2-2.3.0.tgz", + "integrity": "sha1-i/tVAr3kpNNs/e6gB/zKIdfjgq8=", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "readable-stream": "^2.0.0" + } + }, + "fs-write-stream-atomic": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/fs-write-stream-atomic/-/fs-write-stream-atomic-1.0.10.tgz", + "integrity": "sha1-tH31NJPvkR33VzHnCp3tAYnbQMk=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "iferr": "^0.1.5", + "imurmurhash": "^0.1.4", + "readable-stream": "1 || 2" + } + }, + "fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "dev": true + }, + "fsevents": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-1.2.7.tgz", + "integrity": "sha512-Pxm6sI2MeBD7RdD12RYsqaP0nMiwx8eZBXCa6z2L+mRHm2DYrOYwihmhjpkdjUHwQhslWQjRpEgNq4XvBmaAuw==", + "dev": true, + "optional": true, + "requires": { + "nan": "^2.9.2", + "node-pre-gyp": "^0.10.0" + }, + "dependencies": { + "abbrev": { + "version": "1.1.1", + "bundled": true, + "dev": true, + "optional": true + }, + "ansi-regex": { + "version": "2.1.1", + "bundled": true, + "dev": true, + "optional": true + }, + "aproba": { + "version": "1.2.0", + "bundled": true, + "dev": true, + "optional": true + }, + "are-we-there-yet": { + "version": "1.1.5", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "delegates": "^1.0.0", + "readable-stream": "^2.0.6" + } + }, + "balanced-match": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "brace-expansion": { + "version": "1.1.11", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "chownr": { + "version": "1.1.1", + "bundled": true, + "dev": true, + "optional": true + }, + "code-point-at": { + "version": "1.1.0", + "bundled": true, + "dev": true, + "optional": true + }, + "concat-map": { + "version": "0.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "console-control-strings": { + "version": "1.1.0", + "bundled": true, + "dev": true, + "optional": true + }, + "core-util-is": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "debug": { + "version": "2.6.9", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "ms": "2.0.0" + } + }, + "deep-extend": { + "version": "0.6.0", + "bundled": true, + "dev": true, + "optional": true + }, + "delegates": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "detect-libc": { + "version": "1.0.3", + "bundled": true, + "dev": true, + "optional": true + }, + "fs-minipass": { + "version": "1.2.5", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "minipass": "^2.2.1" + } + }, + "fs.realpath": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "gauge": { + "version": "2.7.4", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "aproba": "^1.0.3", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.0", + "object-assign": "^4.1.0", + "signal-exit": "^3.0.0", + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wide-align": "^1.1.0" + } + }, + "glob": { + "version": "7.1.3", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "has-unicode": { + "version": "2.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "iconv-lite": { + "version": "0.4.24", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "ignore-walk": { + "version": "3.0.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "minimatch": "^3.0.4" + } + }, + "inflight": { + "version": "1.0.6", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.3", + "bundled": true, + "dev": true, + "optional": true + }, + "ini": { + "version": "1.3.5", + "bundled": true, + "dev": true, + "optional": true + }, + "is-fullwidth-code-point": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "isarray": { + "version": "1.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "minimatch": { + "version": "3.0.4", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "bundled": true, + "dev": true, + "optional": true + }, + "minipass": { + "version": "2.3.5", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "safe-buffer": "^5.1.2", + "yallist": "^3.0.0" + } + }, + "minizlib": { + "version": "1.2.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "minipass": "^2.2.1" + } + }, + "mkdirp": { + "version": "0.5.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "minimist": "0.0.8" + } + }, + "ms": { + "version": "2.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "needle": { + "version": "2.2.4", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "debug": "^2.1.2", + "iconv-lite": "^0.4.4", + "sax": "^1.2.4" + } + }, + "node-pre-gyp": { + "version": "0.10.3", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "detect-libc": "^1.0.2", + "mkdirp": "^0.5.1", + "needle": "^2.2.1", + "nopt": "^4.0.1", + "npm-packlist": "^1.1.6", + "npmlog": "^4.0.2", + "rc": "^1.2.7", + "rimraf": "^2.6.1", + "semver": "^5.3.0", + "tar": "^4" + } + }, + "nopt": { + "version": "4.0.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "abbrev": "1", + "osenv": "^0.1.4" + } + }, + "npm-bundled": { + "version": "1.0.5", + "bundled": true, + "dev": true, + "optional": true + }, + "npm-packlist": { + "version": "1.2.0", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "ignore-walk": "^3.0.1", + "npm-bundled": "^1.0.1" + } + }, + "npmlog": { + "version": "4.1.2", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "are-we-there-yet": "~1.1.2", + "console-control-strings": "~1.1.0", + "gauge": "~2.7.3", + "set-blocking": "~2.0.0" + } + }, + "number-is-nan": { + "version": "1.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "object-assign": { + "version": "4.1.1", + "bundled": true, + "dev": true, + "optional": true + }, + "once": { + "version": "1.4.0", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "wrappy": "1" + } + }, + "os-homedir": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "os-tmpdir": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "osenv": { + "version": "0.1.5", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.0" + } + }, + "path-is-absolute": { + "version": "1.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "process-nextick-args": { + "version": "2.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "rc": { + "version": "1.2.8", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "deep-extend": "^0.6.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "bundled": true, + "dev": true, + "optional": true + } + } + }, + "readable-stream": { + "version": "2.3.6", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "rimraf": { + "version": "2.6.3", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "glob": "^7.1.3" + } + }, + "safe-buffer": { + "version": "5.1.2", + "bundled": true, + "dev": true, + "optional": true + }, + "safer-buffer": { + "version": "2.1.2", + "bundled": true, + "dev": true, + "optional": true + }, + "sax": { + "version": "1.2.4", + "bundled": true, + "dev": true, + "optional": true + }, + "semver": { + "version": "5.6.0", + "bundled": true, + "dev": true, + "optional": true + }, + "set-blocking": { + "version": "2.0.0", + "bundled": true, + "dev": true, + "optional": true + }, + "signal-exit": { + "version": "3.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "string-width": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "string_decoder": { + "version": "1.1.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "strip-json-comments": { + "version": "2.0.1", + "bundled": true, + "dev": true, + "optional": true + }, + "tar": { + "version": "4.4.8", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "chownr": "^1.1.1", + "fs-minipass": "^1.2.5", + "minipass": "^2.3.4", + "minizlib": "^1.1.1", + "mkdirp": "^0.5.0", + "safe-buffer": "^5.1.2", + "yallist": "^3.0.2" + } + }, + "util-deprecate": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "wide-align": { + "version": "1.1.3", + "bundled": true, + "dev": true, + "optional": true, + "requires": { + "string-width": "^1.0.2 || 2" + } + }, + "wrappy": { + "version": "1.0.2", + "bundled": true, + "dev": true, + "optional": true + }, + "yallist": { + "version": "3.0.3", + "bundled": true, + "dev": true, + "optional": true + } + } + }, + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "dev": true + }, + "get-caller-file": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-1.0.3.tgz", + "integrity": "sha512-3t6rVToeoZfYSGd8YoLFR2DJkiQrIiUrGcjvFX2mDw3bn6k2OtwHN0TNCLbBO+w8qTvimhDkv+LSscbJY1vE6w==", + "dev": true + }, + "get-stream": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz", + "integrity": "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==", + "dev": true, + "requires": { + "pump": "^3.0.0" + } + }, + "get-value": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/get-value/-/get-value-2.0.6.tgz", + "integrity": "sha1-3BXKHGcjh8p2vTesCjlbogQqLCg=", + "dev": true + }, + "getpass": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", + "dev": true, + "requires": { + "assert-plus": "^1.0.0" + } + }, + "glob": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz", + "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", + "dev": true, + "requires": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + } + }, + "glob-parent": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-3.1.0.tgz", + "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", + "dev": true, + "requires": { + "is-glob": "^3.1.0", + "path-dirname": "^1.0.0" + }, + "dependencies": { + "is-glob": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-3.1.0.tgz", + "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", + "dev": true, + "requires": { + "is-extglob": "^2.1.0" + } + } + } + }, + "global-modules": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/global-modules/-/global-modules-1.0.0.tgz", + "integrity": "sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg==", + "dev": true, + "requires": { + "global-prefix": "^1.0.1", + "is-windows": "^1.0.1", + "resolve-dir": "^1.0.0" + } + }, + "global-prefix": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/global-prefix/-/global-prefix-1.0.2.tgz", + "integrity": "sha1-2/dDxsFJklk8ZVVoy2btMsASLr4=", + "dev": true, + "requires": { + "expand-tilde": "^2.0.2", + "homedir-polyfill": "^1.0.1", + "ini": "^1.3.4", + "is-windows": "^1.0.1", + "which": "^1.2.14" + } + }, + "globals": { + "version": "11.11.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-11.11.0.tgz", + "integrity": "sha512-WHq43gS+6ufNOEqlrDBxVEbb8ntfXrfAUU2ZOpCxrBdGKW3gyv8mCxAfIBD0DroPKGrJ2eSsXsLtY9MPntsyTw==", + "dev": true + }, + "graceful-fs": { + "version": "4.1.15", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", + "integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==", + "dev": true + }, + "growly": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/growly/-/growly-1.3.0.tgz", + "integrity": "sha1-8QdIy+dq+WS3yWyTxrzCivEgwIE=", + "dev": true + }, + "handlebars": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.1.0.tgz", + "integrity": "sha512-l2jRuU1NAWK6AW5qqcTATWQJvNPEwkM7NEKSiv/gqOsoSQbVoWyqVEY5GS+XPQ88zLNmqASRpzfdm8d79hJS+w==", + "dev": true, + "requires": { + "async": "^2.5.0", + "optimist": "^0.6.1", + "source-map": "^0.6.1", + "uglify-js": "^3.1.4" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "har-schema": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", + "integrity": "sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI=", + "dev": true + }, + "har-validator": { + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.3.tgz", + "integrity": "sha512-sNvOCzEQNr/qrvJgc3UG/kD4QtlHycrzwS+6mfTrrSq97BvaYcPZZI1ZSqGSPR73Cxn4LKTD4PttRwfU7jWq5g==", + "dev": true, + "requires": { + "ajv": "^6.5.5", + "har-schema": "^2.0.0" + } + }, + "has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dev": true, + "requires": { + "function-bind": "^1.1.1" + } + }, + "has-ansi": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz", + "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", + "dev": true + }, + "has-symbols": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.0.tgz", + "integrity": "sha1-uhqPGvKg/DllD1yFA2dwQSIGO0Q=", + "dev": true + }, + "has-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-1.0.0.tgz", + "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=", + "dev": true, + "requires": { + "get-value": "^2.0.6", + "has-values": "^1.0.0", + "isobject": "^3.0.0" + } + }, + "has-values": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-1.0.0.tgz", + "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=", + "dev": true, + "requires": { + "is-number": "^3.0.0", + "kind-of": "^4.0.0" + }, + "dependencies": { + "kind-of": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-4.0.0.tgz", + "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "hash-base": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/hash-base/-/hash-base-3.0.4.tgz", + "integrity": "sha1-X8hoaEfs1zSZQDMZprCj8/auSRg=", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "hash.js": { + "version": "1.1.7", + "resolved": "https://registry.npmjs.org/hash.js/-/hash.js-1.1.7.tgz", + "integrity": "sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==", + "dev": true, + "requires": { + "inherits": "^2.0.3", + "minimalistic-assert": "^1.0.1" + } + }, + "hmac-drbg": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz", + "integrity": "sha1-0nRXAQJabHdabFRXk+1QL8DGSaE=", + "dev": true, + "requires": { + "hash.js": "^1.0.3", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.1" + } + }, + "homedir-polyfill": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz", + "integrity": "sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==", + "dev": true, + "requires": { + "parse-passwd": "^1.0.0" + } + }, + "hosted-git-info": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.7.1.tgz", + "integrity": "sha512-7T/BxH19zbcCTa8XkMlbK5lTo1WtgkFi3GvdWEyNuc4Vex7/9Dqbnpsf4JMydcfj9HCg4zUWFTL3Za6lapg5/w==", + "dev": true + }, + "html-encoding-sniffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-1.0.2.tgz", + "integrity": "sha512-71lZziiDnsuabfdYiUeWdCVyKuqwWi23L8YeIgV9jSSZHCtb6wB1BKWooH7L3tn4/FuZJMVWyNaIDr4RGmaSYw==", + "dev": true, + "requires": { + "whatwg-encoding": "^1.0.1" + } + }, + "http-signature": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", + "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", + "dev": true, + "requires": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + } + }, + "https-browserify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/https-browserify/-/https-browserify-1.0.0.tgz", + "integrity": "sha1-7AbBDgo0wPL68Zn3/X/Hj//QPHM=", + "dev": true + }, + "iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dev": true, + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "ieee754": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.12.tgz", + "integrity": "sha512-GguP+DRY+pJ3soyIiGPTvdiVXjZ+DbXOxGpXn3eMvNW4x4irjqXm4wHKscC+TfxSJ0yw/S1F24tqdMNsMZTiLA==", + "dev": true + }, + "iferr": { + "version": "0.1.5", + "resolved": "https://registry.npmjs.org/iferr/-/iferr-0.1.5.tgz", + "integrity": "sha1-xg7taebY/bazEEofy8ocGS3FtQE=", + "dev": true + }, + "import-local": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-2.0.0.tgz", + "integrity": "sha512-b6s04m3O+s3CGSbqDIyP4R6aAwAeYlVq9+WUWep6iHa8ETRf9yei1U48C5MmfJmV9AiLYYBKPMq/W+/WRpQmCQ==", + "dev": true, + "requires": { + "pkg-dir": "^3.0.0", + "resolve-cwd": "^2.0.0" + } + }, + "imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha1-khi5srkoojixPcT7a21XbyMUU+o=", + "dev": true + }, + "indexof": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/indexof/-/indexof-0.0.1.tgz", + "integrity": "sha1-gtwzbSMrkGIXnQWrMpOmYFn9Q10=", + "dev": true + }, + "inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "dev": true, + "requires": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "inherits": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "dev": true + }, + "ini": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz", + "integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw==", + "dev": true + }, + "interpret": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.2.0.tgz", + "integrity": "sha512-mT34yGKMNceBQUoVn7iCDKDntA7SC6gycMAWzGx1z/CMCTV7b2AAtXlo3nRyHZ1FelRkQbQjprHSYGwzLtkVbw==", + "dev": true + }, + "invariant": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.4.tgz", + "integrity": "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==", + "dev": true, + "requires": { + "loose-envify": "^1.0.0" + } + }, + "invert-kv": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/invert-kv/-/invert-kv-2.0.0.tgz", + "integrity": "sha512-wPVv/y/QQ/Uiirj/vh3oP+1Ww+AWehmi1g5fFWGPF6IpCBCDVrhgHRMvrLfdYcwDh3QJbGXDW4JAuzxElLSqKA==", + "dev": true + }, + "is-accessor-descriptor": { + "version": "0.1.6", + "resolved": "http://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=", + "dev": true + }, + "is-binary-path": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-1.0.1.tgz", + "integrity": "sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg=", + "dev": true, + "requires": { + "binary-extensions": "^1.0.0" + } + }, + "is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", + "dev": true + }, + "is-callable": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.1.4.tgz", + "integrity": "sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA==", + "dev": true + }, + "is-ci": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz", + "integrity": "sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==", + "dev": true, + "requires": { + "ci-info": "^2.0.0" + } + }, + "is-data-descriptor": { + "version": "0.1.4", + "resolved": "http://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-date-object": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.1.tgz", + "integrity": "sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY=", + "dev": true + }, + "is-descriptor": { + "version": "0.1.6", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-0.1.6.tgz", + "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^0.1.6", + "is-data-descriptor": "^0.1.4", + "kind-of": "^5.0.0" + }, + "dependencies": { + "kind-of": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-5.1.0.tgz", + "integrity": "sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw==", + "dev": true + } + } + }, + "is-extendable": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-0.1.1.tgz", + "integrity": "sha1-YrEQ4omkcUGOPsNqYX1HLjAd/Ik=", + "dev": true + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=", + "dev": true + }, + "is-fullwidth-code-point": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", + "integrity": "sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=", + "dev": true + }, + "is-generator-fn": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.0.0.tgz", + "integrity": "sha512-elzyIdM7iKoFHzcrndIqjYomImhxrFRnGP3galODoII4TB9gI7mZ+FnlLQmmjf27SxHS2gKEeyhX5/+YRS6H9g==", + "dev": true + }, + "is-glob": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.0.tgz", + "integrity": "sha1-lSHHaEXMJhCoUgPd8ICpWML/q8A=", + "dev": true, + "requires": { + "is-extglob": "^2.1.1" + } + }, + "is-number": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-3.0.0.tgz", + "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "is-plain-object": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz", + "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", + "dev": true, + "requires": { + "isobject": "^3.0.1" + } + }, + "is-regex": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.4.tgz", + "integrity": "sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=", + "dev": true, + "requires": { + "has": "^1.0.1" + } + }, + "is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=", + "dev": true + }, + "is-symbol": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.2.tgz", + "integrity": "sha512-HS8bZ9ox60yCJLH9snBpIwv9pYUAkcuLhSA1oero1UB5y9aiQpRA8y2ex945AOtCZL1lJDeIk3G5LthswI46Lw==", + "dev": true, + "requires": { + "has-symbols": "^1.0.0" + } + }, + "is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", + "dev": true + }, + "is-windows": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-windows/-/is-windows-1.0.2.tgz", + "integrity": "sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==", + "dev": true + }, + "is-wsl": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-1.1.0.tgz", + "integrity": "sha1-HxbkqiKwTRM2tmGIpmrzxgDDpm0=", + "dev": true + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "dev": true + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=", + "dev": true + }, + "isobject": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz", + "integrity": "sha1-TkMekrEalzFjaqH5yNHMvP2reN8=", + "dev": true + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo=", + "dev": true + }, + "istanbul-api": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/istanbul-api/-/istanbul-api-2.1.1.tgz", + "integrity": "sha512-kVmYrehiwyeBAk/wE71tW6emzLiHGjYIiDrc8sfyty4F8M02/lrgXSm+R1kXysmF20zArvmZXjlE/mg24TVPJw==", + "dev": true, + "requires": { + "async": "^2.6.1", + "compare-versions": "^3.2.1", + "fileset": "^2.0.3", + "istanbul-lib-coverage": "^2.0.3", + "istanbul-lib-hook": "^2.0.3", + "istanbul-lib-instrument": "^3.1.0", + "istanbul-lib-report": "^2.0.4", + "istanbul-lib-source-maps": "^3.0.2", + "istanbul-reports": "^2.1.1", + "js-yaml": "^3.12.0", + "make-dir": "^1.3.0", + "minimatch": "^3.0.4", + "once": "^1.4.0" + } + }, + "istanbul-lib-coverage": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.3.tgz", + "integrity": "sha512-dKWuzRGCs4G+67VfW9pBFFz2Jpi4vSp/k7zBcJ888ofV5Mi1g5CUML5GvMvV6u9Cjybftu+E8Cgp+k0dI1E5lw==", + "dev": true + }, + "istanbul-lib-hook": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/istanbul-lib-hook/-/istanbul-lib-hook-2.0.3.tgz", + "integrity": "sha512-CLmEqwEhuCYtGcpNVJjLV1DQyVnIqavMLFHV/DP+np/g3qvdxu3gsPqYoJMXm15sN84xOlckFB3VNvRbf5yEgA==", + "dev": true, + "requires": { + "append-transform": "^1.0.0" + } + }, + "istanbul-lib-instrument": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-3.1.0.tgz", + "integrity": "sha512-ooVllVGT38HIk8MxDj/OIHXSYvH+1tq/Vb38s8ixt9GoJadXska4WkGY+0wkmtYCZNYtaARniH/DixUGGLZ0uA==", + "dev": true, + "requires": { + "@babel/generator": "^7.0.0", + "@babel/parser": "^7.0.0", + "@babel/template": "^7.0.0", + "@babel/traverse": "^7.0.0", + "@babel/types": "^7.0.0", + "istanbul-lib-coverage": "^2.0.3", + "semver": "^5.5.0" + } + }, + "istanbul-lib-report": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-2.0.4.tgz", + "integrity": "sha512-sOiLZLAWpA0+3b5w5/dq0cjm2rrNdAfHWaGhmn7XEFW6X++IV9Ohn+pnELAl9K3rfpaeBfbmH9JU5sejacdLeA==", + "dev": true, + "requires": { + "istanbul-lib-coverage": "^2.0.3", + "make-dir": "^1.3.0", + "supports-color": "^6.0.0" + }, + "dependencies": { + "supports-color": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", + "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "istanbul-lib-source-maps": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-3.0.2.tgz", + "integrity": "sha512-JX4v0CiKTGp9fZPmoxpu9YEkPbEqCqBbO3403VabKjH+NRXo72HafD5UgnjTEqHL2SAjaZK1XDuDOkn6I5QVfQ==", + "dev": true, + "requires": { + "debug": "^4.1.1", + "istanbul-lib-coverage": "^2.0.3", + "make-dir": "^1.3.0", + "rimraf": "^2.6.2", + "source-map": "^0.6.1" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "istanbul-reports": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-2.1.1.tgz", + "integrity": "sha512-FzNahnidyEPBCI0HcufJoSEoKykesRlFcSzQqjH9x0+LC8tnnE/p/90PBLu8iZTxr8yYZNyTtiAujUqyN+CIxw==", + "dev": true, + "requires": { + "handlebars": "^4.1.0" + } + }, + "jest": { + "version": "24.1.0", + "resolved": "https://registry.npmjs.org/jest/-/jest-24.1.0.tgz", + "integrity": "sha512-+q91L65kypqklvlRFfXfdzUKyngQLOcwGhXQaLmVHv+d09LkNXuBuGxlofTFW42XMzu3giIcChchTsCNUjQ78A==", + "dev": true, + "requires": { + "import-local": "^2.0.0", + "jest-cli": "^24.1.0" + }, + "dependencies": { + "jest-cli": { + "version": "24.1.0", + "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-24.1.0.tgz", + "integrity": "sha512-U/iyWPwOI0T1CIxVLtk/2uviOTJ/OiSWJSe8qt6X1VkbbgP+nrtLJlmT9lPBe4lK78VNFJtrJ7pttcNv/s7yCw==", + "dev": true, + "requires": { + "ansi-escapes": "^3.0.0", + "chalk": "^2.0.1", + "exit": "^0.1.2", + "glob": "^7.1.2", + "graceful-fs": "^4.1.15", + "import-local": "^2.0.0", + "is-ci": "^2.0.0", + "istanbul-api": "^2.0.8", + "istanbul-lib-coverage": "^2.0.2", + "istanbul-lib-instrument": "^3.0.1", + "istanbul-lib-source-maps": "^3.0.1", + "jest-changed-files": "^24.0.0", + "jest-config": "^24.1.0", + "jest-environment-jsdom": "^24.0.0", + "jest-get-type": "^24.0.0", + "jest-haste-map": "^24.0.0", + "jest-message-util": "^24.0.0", + "jest-regex-util": "^24.0.0", + "jest-resolve-dependencies": "^24.1.0", + "jest-runner": "^24.1.0", + "jest-runtime": "^24.1.0", + "jest-snapshot": "^24.1.0", + "jest-util": "^24.0.0", + "jest-validate": "^24.0.0", + "jest-watcher": "^24.0.0", + "jest-worker": "^24.0.0", + "micromatch": "^3.1.10", + "node-notifier": "^5.2.1", + "p-each-series": "^1.0.0", + "pirates": "^4.0.0", + "prompts": "^2.0.1", + "realpath-native": "^1.0.0", + "rimraf": "^2.5.4", + "slash": "^2.0.0", + "string-length": "^2.0.0", + "strip-ansi": "^5.0.0", + "which": "^1.2.12", + "yargs": "^12.0.2" + } + } + } + }, + "jest-changed-files": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-24.0.0.tgz", + "integrity": "sha512-nnuU510R9U+UX0WNb5XFEcsrMqriSiRLeO9KWDFgPrpToaQm60prfQYpxsXigdClpvNot5bekDY440x9dNGnsQ==", + "dev": true, + "requires": { + "execa": "^1.0.0", + "throat": "^4.0.0" + } + }, + "jest-config": { + "version": "24.1.0", + "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-24.1.0.tgz", + "integrity": "sha512-FbbRzRqtFC6eGjG5VwsbW4E5dW3zqJKLWYiZWhB0/4E5fgsMw8GODLbGSrY5t17kKOtCWb/Z7nsIThRoDpuVyg==", + "dev": true, + "requires": { + "@babel/core": "^7.1.0", + "babel-jest": "^24.1.0", + "chalk": "^2.0.1", + "glob": "^7.1.1", + "jest-environment-jsdom": "^24.0.0", + "jest-environment-node": "^24.0.0", + "jest-get-type": "^24.0.0", + "jest-jasmine2": "^24.1.0", + "jest-regex-util": "^24.0.0", + "jest-resolve": "^24.1.0", + "jest-util": "^24.0.0", + "jest-validate": "^24.0.0", + "micromatch": "^3.1.10", + "pretty-format": "^24.0.0", + "realpath-native": "^1.0.2" + } + }, + "jest-diff": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-24.0.0.tgz", + "integrity": "sha512-XY5wMpRaTsuMoU+1/B2zQSKQ9RdE9gsLkGydx3nvApeyPijLA8GtEvIcPwISRCer+VDf9W1mStTYYq6fPt8ryA==", + "dev": true, + "requires": { + "chalk": "^2.0.1", + "diff-sequences": "^24.0.0", + "jest-get-type": "^24.0.0", + "pretty-format": "^24.0.0" + } + }, + "jest-docblock": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-24.0.0.tgz", + "integrity": "sha512-KfAKZ4SN7CFOZpWg4i7g7MSlY0M+mq7K0aMqENaG2vHuhC9fc3vkpU/iNN9sOus7v3h3Y48uEjqz3+Gdn2iptA==", + "dev": true, + "requires": { + "detect-newline": "^2.1.0" + } + }, + "jest-each": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-24.0.0.tgz", + "integrity": "sha512-gFcbY4Cu55yxExXMkjrnLXov3bWO3dbPAW7HXb31h/DNWdNc/6X8MtxGff8nh3/MjkF9DpVqnj0KsPKuPK0cpA==", + "dev": true, + "requires": { + "chalk": "^2.0.1", + "jest-get-type": "^24.0.0", + "jest-util": "^24.0.0", + "pretty-format": "^24.0.0" + } + }, + "jest-environment-jsdom": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-24.0.0.tgz", + "integrity": "sha512-1YNp7xtxajTRaxbylDc2pWvFnfDTH5BJJGyVzyGAKNt/lEULohwEV9zFqTgG4bXRcq7xzdd+sGFws+LxThXXOw==", + "dev": true, + "requires": { + "jest-mock": "^24.0.0", + "jest-util": "^24.0.0", + "jsdom": "^11.5.1" + } + }, + "jest-environment-node": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-24.0.0.tgz", + "integrity": "sha512-62fOFcaEdU0VLaq8JL90TqwI7hLn0cOKOl8vY2n477vRkCJRojiRRtJVRzzCcgFvs6gqU97DNqX5R0BrBP6Rxg==", + "dev": true, + "requires": { + "jest-mock": "^24.0.0", + "jest-util": "^24.0.0" + } + }, + "jest-get-type": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-24.0.0.tgz", + "integrity": "sha512-z6/Eyf6s9ZDGz7eOvl+fzpuJmN9i0KyTt1no37/dHu8galssxz5ZEgnc1KaV8R31q1khxyhB4ui/X5ZjjPk77w==", + "dev": true + }, + "jest-haste-map": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-24.0.0.tgz", + "integrity": "sha512-CcViJyUo41IQqttLxXVdI41YErkzBKbE6cS6dRAploCeutePYfUimWd3C9rQEWhX0YBOQzvNsC0O9nYxK2nnxQ==", + "dev": true, + "requires": { + "fb-watchman": "^2.0.0", + "graceful-fs": "^4.1.15", + "invariant": "^2.2.4", + "jest-serializer": "^24.0.0", + "jest-util": "^24.0.0", + "jest-worker": "^24.0.0", + "micromatch": "^3.1.10", + "sane": "^3.0.0" + } + }, + "jest-jasmine2": { + "version": "24.1.0", + "resolved": "https://registry.npmjs.org/jest-jasmine2/-/jest-jasmine2-24.1.0.tgz", + "integrity": "sha512-H+o76SdSNyCh9fM5K8upK45YTo/DiFx5w2YAzblQebSQmukDcoVBVeXynyr7DDnxh+0NTHYRCLwJVf3tC518wg==", + "dev": true, + "requires": { + "@babel/traverse": "^7.1.0", + "chalk": "^2.0.1", + "co": "^4.6.0", + "expect": "^24.1.0", + "is-generator-fn": "^2.0.0", + "jest-each": "^24.0.0", + "jest-matcher-utils": "^24.0.0", + "jest-message-util": "^24.0.0", + "jest-snapshot": "^24.1.0", + "jest-util": "^24.0.0", + "pretty-format": "^24.0.0", + "throat": "^4.0.0" + } + }, + "jest-leak-detector": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-24.0.0.tgz", + "integrity": "sha512-ZYHJYFeibxfsDSKowjDP332pStuiFT2xfc5R67Rjm/l+HFJWJgNIOCOlQGeXLCtyUn3A23+VVDdiCcnB6dTTrg==", + "dev": true, + "requires": { + "pretty-format": "^24.0.0" + } + }, + "jest-matcher-utils": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-24.0.0.tgz", + "integrity": "sha512-LQTDmO+aWRz1Tf9HJg+HlPHhDh1E1c65kVwRFo5mwCVp5aQDzlkz4+vCvXhOKFjitV2f0kMdHxnODrXVoi+rlA==", + "dev": true, + "requires": { + "chalk": "^2.0.1", + "jest-diff": "^24.0.0", + "jest-get-type": "^24.0.0", + "pretty-format": "^24.0.0" + } + }, + "jest-message-util": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-24.0.0.tgz", + "integrity": "sha512-J9ROJIwz/IeC+eV1XSwnRK4oAwPuhmxEyYx1+K5UI+pIYwFZDSrfZaiWTdq0d2xYFw4Xiu+0KQWsdsQpgJMf3Q==", + "dev": true, + "requires": { + "@babel/code-frame": "^7.0.0", + "chalk": "^2.0.1", + "micromatch": "^3.1.10", + "slash": "^2.0.0", + "stack-utils": "^1.0.1" + } + }, + "jest-mock": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-24.0.0.tgz", + "integrity": "sha512-sQp0Hu5fcf5NZEh1U9eIW2qD0BwJZjb63Yqd98PQJFvf/zzUTBoUAwv/Dc/HFeNHIw1f3hl/48vNn+j3STaI7A==", + "dev": true + }, + "jest-regex-util": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-24.0.0.tgz", + "integrity": "sha512-Jv/uOTCuC+PY7WpJl2mpoI+WbY2ut73qwwO9ByJJNwOCwr1qWhEW2Lyi2S9ZewUdJqeVpEBisdEVZSI+Zxo58Q==", + "dev": true + }, + "jest-resolve": { + "version": "24.1.0", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-24.1.0.tgz", + "integrity": "sha512-TPiAIVp3TG6zAxH28u/6eogbwrvZjBMWroSLBDkwkHKrqxB/RIdwkWDye4uqPlZIXWIaHtifY3L0/eO5Z0f2wg==", + "dev": true, + "requires": { + "browser-resolve": "^1.11.3", + "chalk": "^2.0.1", + "realpath-native": "^1.0.0" + } + }, + "jest-resolve-dependencies": { + "version": "24.1.0", + "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-24.1.0.tgz", + "integrity": "sha512-2VwPsjd3kRPu7qe2cpytAgowCObk5AKeizfXuuiwgm1a9sijJDZe8Kh1sFj6FKvSaNEfCPlBVkZEJa2482m/Uw==", + "dev": true, + "requires": { + "jest-regex-util": "^24.0.0", + "jest-snapshot": "^24.1.0" + } + }, + "jest-runner": { + "version": "24.1.0", + "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-24.1.0.tgz", + "integrity": "sha512-CDGOkT3AIFl16BLL/OdbtYgYvbAprwJ+ExKuLZmGSCSldwsuU2dEGauqkpvd9nphVdAnJUcP12e/EIlnTX0QXg==", + "dev": true, + "requires": { + "chalk": "^2.4.2", + "exit": "^0.1.2", + "graceful-fs": "^4.1.15", + "jest-config": "^24.1.0", + "jest-docblock": "^24.0.0", + "jest-haste-map": "^24.0.0", + "jest-jasmine2": "^24.1.0", + "jest-leak-detector": "^24.0.0", + "jest-message-util": "^24.0.0", + "jest-runtime": "^24.1.0", + "jest-util": "^24.0.0", + "jest-worker": "^24.0.0", + "source-map-support": "^0.5.6", + "throat": "^4.0.0" + }, + "dependencies": { + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "dev": true, + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + } + } + }, + "jest-runtime": { + "version": "24.1.0", + "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-24.1.0.tgz", + "integrity": "sha512-59/BY6OCuTXxGeDhEMU7+N33dpMQyXq7MLK07cNSIY/QYt2QZgJ7Tjx+rykBI0skAoigFl0A5tmT8UdwX92YuQ==", + "dev": true, + "requires": { + "@babel/core": "^7.1.0", + "babel-plugin-istanbul": "^5.1.0", + "chalk": "^2.0.1", + "convert-source-map": "^1.4.0", + "exit": "^0.1.2", + "fast-json-stable-stringify": "^2.0.0", + "glob": "^7.1.3", + "graceful-fs": "^4.1.15", + "jest-config": "^24.1.0", + "jest-haste-map": "^24.0.0", + "jest-message-util": "^24.0.0", + "jest-regex-util": "^24.0.0", + "jest-resolve": "^24.1.0", + "jest-snapshot": "^24.1.0", + "jest-util": "^24.0.0", + "jest-validate": "^24.0.0", + "micromatch": "^3.1.10", + "realpath-native": "^1.0.0", + "slash": "^2.0.0", + "strip-bom": "^3.0.0", + "write-file-atomic": "2.4.1", + "yargs": "^12.0.2" + } + }, + "jest-serializer": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-serializer/-/jest-serializer-24.0.0.tgz", + "integrity": "sha512-9FKxQyrFgHtx3ozU+1a8v938ILBE7S8Ko3uiAVjT8Yfi2o91j/fj81jacCQZ/Ihjiff/VsUCXVgQ+iF1XdImOw==", + "dev": true + }, + "jest-snapshot": { + "version": "24.1.0", + "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-24.1.0.tgz", + "integrity": "sha512-th6TDfFqEmXvuViacU1ikD7xFb7lQsPn2rJl7OEmnfIVpnrx3QNY2t3PE88meeg0u/mQ0nkyvmC05PBqO4USFA==", + "dev": true, + "requires": { + "@babel/types": "^7.0.0", + "chalk": "^2.0.1", + "jest-diff": "^24.0.0", + "jest-matcher-utils": "^24.0.0", + "jest-message-util": "^24.0.0", + "jest-resolve": "^24.1.0", + "mkdirp": "^0.5.1", + "natural-compare": "^1.4.0", + "pretty-format": "^24.0.0", + "semver": "^5.5.0" + } + }, + "jest-util": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-24.0.0.tgz", + "integrity": "sha512-QxsALc4wguYS7cfjdQSOr5HTkmjzkHgmZvIDkcmPfl1ib8PNV8QUWLwbKefCudWS0PRKioV+VbQ0oCUPC691fQ==", + "dev": true, + "requires": { + "callsites": "^3.0.0", + "chalk": "^2.0.1", + "graceful-fs": "^4.1.15", + "is-ci": "^2.0.0", + "jest-message-util": "^24.0.0", + "mkdirp": "^0.5.1", + "slash": "^2.0.0", + "source-map": "^0.6.0" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "jest-validate": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-24.0.0.tgz", + "integrity": "sha512-vMrKrTOP4BBFIeOWsjpsDgVXATxCspC9S1gqvbJ3Tnn/b9ACsJmteYeVx9830UMV28Cob1RX55x96Qq3Tfad4g==", + "dev": true, + "requires": { + "camelcase": "^5.0.0", + "chalk": "^2.0.1", + "jest-get-type": "^24.0.0", + "leven": "^2.1.0", + "pretty-format": "^24.0.0" + } + }, + "jest-watcher": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-24.0.0.tgz", + "integrity": "sha512-GxkW2QrZ4YxmW1GUWER05McjVDunBlKMFfExu+VsGmXJmpej1saTEKvONdx5RJBlVdpPI5x6E3+EDQSIGgl53g==", + "dev": true, + "requires": { + "ansi-escapes": "^3.0.0", + "chalk": "^2.0.1", + "jest-util": "^24.0.0", + "string-length": "^2.0.0" + } + }, + "jest-worker": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-24.0.0.tgz", + "integrity": "sha512-s64/OThpfQvoCeHG963MiEZOAAxu8kHsaL/rCMF7lpdzo7vgF0CtPml9hfguOMgykgH/eOm4jFP4ibfHLruytg==", + "dev": true, + "requires": { + "merge-stream": "^1.0.1", + "supports-color": "^6.1.0" + }, + "dependencies": { + "supports-color": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-6.1.0.tgz", + "integrity": "sha512-qe1jfm1Mg7Nq/NSh6XE24gPXROEVsWHxC1LIx//XNlD9iw7YZQGjZNjYN7xGaEG6iKdA8EtNFW6R0gjnVXp+wQ==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + } + } + }, + "js-tokens": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz", + "integrity": "sha1-mGbfOVECEw449/mWvOtlRDIJwls=", + "dev": true + }, + "js-yaml": { + "version": "3.12.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.12.0.tgz", + "integrity": "sha512-PIt2cnwmPfL4hKNwqeiuz4bKfnzHTBv6HyVgjahA6mPLwPDzjDWrplJBMjHUFxku/N3FlmrbyPclad+I+4mJ3A==", + "dev": true, + "requires": { + "argparse": "^1.0.7", + "esprima": "^4.0.0" + } + }, + "jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha1-peZUwuWi3rXyAdls77yoDA7y9RM=", + "dev": true + }, + "jsdom": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-11.12.0.tgz", + "integrity": "sha512-y8Px43oyiBM13Zc1z780FrfNLJCXTL40EWlty/LXUtcjykRBNgLlCjWXpfSPBl2iv+N7koQN+dvqszHZgT/Fjw==", + "dev": true, + "requires": { + "abab": "^2.0.0", + "acorn": "^5.5.3", + "acorn-globals": "^4.1.0", + "array-equal": "^1.0.0", + "cssom": ">= 0.3.2 < 0.4.0", + "cssstyle": "^1.0.0", + "data-urls": "^1.0.0", + "domexception": "^1.0.1", + "escodegen": "^1.9.1", + "html-encoding-sniffer": "^1.0.2", + "left-pad": "^1.3.0", + "nwsapi": "^2.0.7", + "parse5": "4.0.0", + "pn": "^1.1.0", + "request": "^2.87.0", + "request-promise-native": "^1.0.5", + "sax": "^1.2.4", + "symbol-tree": "^3.2.2", + "tough-cookie": "^2.3.4", + "w3c-hr-time": "^1.0.1", + "webidl-conversions": "^4.0.2", + "whatwg-encoding": "^1.0.3", + "whatwg-mimetype": "^2.1.0", + "whatwg-url": "^6.4.1", + "ws": "^5.2.0", + "xml-name-validator": "^3.0.0" + } + }, + "jsesc": { + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", + "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "dev": true + }, + "json-parse-better-errors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", + "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==", + "dev": true + }, + "json-schema": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.2.3.tgz", + "integrity": "sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM=", + "dev": true + }, + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, + "json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=", + "dev": true + }, + "json5": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.1.0.tgz", + "integrity": "sha512-8Mh9h6xViijj36g7Dxi+Y4S6hNGV96vcJZr/SrlHh1LR/pEn/8j/+qIBbs44YKl69Lrfctp4QD+AdWLTMqEZAQ==", + "dev": true, + "requires": { + "minimist": "^1.2.0" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + } + } + }, + "jsprim": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.1.tgz", + "integrity": "sha1-MT5mvB5cwG5Di8G3SZwuXFastqI=", + "dev": true, + "requires": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.2.3", + "verror": "1.10.0" + } + }, + "kind-of": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz", + "integrity": "sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==", + "dev": true + }, + "kleur": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.2.tgz", + "integrity": "sha512-3h7B2WRT5LNXOtQiAaWonilegHcPSf9nLVXlSTci8lu1dZUuui61+EsPEZqSVxY7rXYmB2DVKMQILxaO5WL61Q==", + "dev": true + }, + "lcid": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/lcid/-/lcid-2.0.0.tgz", + "integrity": "sha512-avPEb8P8EGnwXKClwsNUgryVjllcRqtMYa49NTsbQagYuT1DcXnl1915oxWjoyGrXR6zH/Y0Zc96xWsPcoDKeA==", + "dev": true, + "requires": { + "invert-kv": "^2.0.0" + } + }, + "left-pad": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/left-pad/-/left-pad-1.3.0.tgz", + "integrity": "sha512-XI5MPzVNApjAyhQzphX8BkmKsKUxD4LdyK24iZeQGinBN9yTQT3bFlCBy/aVx2HrNcqQGsdot8ghrjyrvMCoEA==", + "dev": true + }, + "leven": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/leven/-/leven-2.1.0.tgz", + "integrity": "sha1-wuep93IJTe6dNCAq6KzORoeHVYA=", + "dev": true + }, + "levn": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.3.0.tgz", + "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" + } + }, + "load-json-file": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", + "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=", + "dev": true, + "requires": { + "graceful-fs": "^4.1.2", + "parse-json": "^4.0.0", + "pify": "^3.0.0", + "strip-bom": "^3.0.0" + } + }, + "loader-runner": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-2.4.0.tgz", + "integrity": "sha512-Jsmr89RcXGIwivFY21FcRrisYZfvLMTWx5kOLc+JTxtpBOG6xML0vzbc6SEQG2FO9/4Fc3wW4LVcB5DmGflaRw==", + "dev": true + }, + "loader-utils": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-1.2.3.tgz", + "integrity": "sha512-fkpz8ejdnEMG3s37wGL07iSBDg99O9D5yflE9RGNH3hRdx9SOwYfnGYdZOUIZitN8E+E2vkq3MUMYMvPYl5ZZA==", + "dev": true, + "requires": { + "big.js": "^5.2.2", + "emojis-list": "^2.0.0", + "json5": "^1.0.1" + }, + "dependencies": { + "json5": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz", + "integrity": "sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==", + "dev": true, + "requires": { + "minimist": "^1.2.0" + } + }, + "minimist": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + } + } + }, + "locate-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-3.0.0.tgz", + "integrity": "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==", + "dev": true, + "requires": { + "p-locate": "^3.0.0", + "path-exists": "^3.0.0" + } + }, + "lodash": { + "version": "4.17.11", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.11.tgz", + "integrity": "sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==", + "dev": true + }, + "lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha1-soqmKIorn8ZRA1x3EfZathkDMaY=" + }, + "lodash.sortby": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/lodash.sortby/-/lodash.sortby-4.7.0.tgz", + "integrity": "sha1-7dFMgk4sycHgsKG0K7UhBRakJDg=", + "dev": true + }, + "loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "dev": true, + "requires": { + "js-tokens": "^3.0.0 || ^4.0.0" + } + }, + "lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "requires": { + "yallist": "^3.0.2" + } + }, + "make-dir": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-1.3.0.tgz", + "integrity": "sha512-2w31R7SJtieJJnQtGc7RVL2StM2vGYVfqUOvUDxH6bC6aJTxPxTF0GnIgCyu7tjockiUWAYQRbxa7vKn34s5sQ==", + "dev": true, + "requires": { + "pify": "^3.0.0" + } + }, + "make-error": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.5.tgz", + "integrity": "sha512-c3sIjNUow0+8swNwVpqoH4YCShKNFkMaw6oH1mNS2haDZQqkeZFlHS3dhoeEbKKmJB4vXpJucU6oH75aDYeE9g==", + "dev": true + }, + "makeerror": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.11.tgz", + "integrity": "sha1-4BpckQnyr3lmDk6LlYd5AYT1qWw=", + "dev": true, + "requires": { + "tmpl": "1.0.x" + } + }, + "mamacro": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/mamacro/-/mamacro-0.0.3.tgz", + "integrity": "sha512-qMEwh+UujcQ+kbz3T6V+wAmO2U8veoq2w+3wY8MquqwVA3jChfwY+Tk52GZKDfACEPjuZ7r2oJLejwpt8jtwTA==", + "dev": true + }, + "map-age-cleaner": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/map-age-cleaner/-/map-age-cleaner-0.1.3.tgz", + "integrity": "sha512-bJzx6nMoP6PDLPBFmg7+xRKeFZvFboMrGlxmNj9ClvX53KrmvM5bXFXEWjbz4cz1AFn+jWJ9z/DJSz7hrs0w3w==", + "dev": true, + "requires": { + "p-defer": "^1.0.0" + } + }, + "map-cache": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", + "integrity": "sha1-wyq9C9ZSXZsFFkW7TyasXcmKDb8=", + "dev": true + }, + "map-visit": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/map-visit/-/map-visit-1.0.0.tgz", + "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", + "dev": true, + "requires": { + "object-visit": "^1.0.0" + } + }, + "md5.js": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/md5.js/-/md5.js-1.3.5.tgz", + "integrity": "sha512-xitP+WxNPcTTOgnTJcrhM0xvdPepipPSf3I8EIpGKeFLjt3PlJLIDG3u8EX53ZIubkb+5U2+3rELYpEhHhzdkg==", + "dev": true, + "requires": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "mem": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/mem/-/mem-4.1.0.tgz", + "integrity": "sha512-I5u6Q1x7wxO0kdOpYBB28xueHADYps5uty/zg936CiG8NTe5sJL8EjrCuLneuDW3PlMdZBGDIn8BirEVdovZvg==", + "dev": true, + "requires": { + "map-age-cleaner": "^0.1.1", + "mimic-fn": "^1.0.0", + "p-is-promise": "^2.0.0" + } + }, + "memory-fs": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/memory-fs/-/memory-fs-0.4.1.tgz", + "integrity": "sha1-OpoguEYlI+RHz7x+i7gO1me/xVI=", + "dev": true, + "requires": { + "errno": "^0.1.3", + "readable-stream": "^2.0.1" + } + }, + "merge": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/merge/-/merge-1.2.1.tgz", + "integrity": "sha512-VjFo4P5Whtj4vsLzsYBu5ayHhoHJ0UqNm7ibvShmbmoz7tGi0vXaoJbGdB+GmDMLUdg8DpQXEIeVDAe8MaABvQ==", + "dev": true + }, + "merge-stream": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-1.0.1.tgz", + "integrity": "sha1-QEEgLVCKNCugAXQAjfDCUbjBNeE=", + "dev": true, + "requires": { + "readable-stream": "^2.0.1" + } + }, + "micromatch": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-3.1.10.tgz", + "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==", + "dev": true, + "requires": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "braces": "^2.3.1", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "extglob": "^2.0.4", + "fragment-cache": "^0.2.1", + "kind-of": "^6.0.2", + "nanomatch": "^1.2.9", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.2" + } + }, + "miller-rabin": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/miller-rabin/-/miller-rabin-4.0.1.tgz", + "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==", + "dev": true, + "requires": { + "bn.js": "^4.0.0", + "brorand": "^1.0.1" + } + }, + "mime-db": { + "version": "1.38.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.38.0.tgz", + "integrity": "sha512-bqVioMFFzc2awcdJZIzR3HjZFX20QhilVS7hytkKrv7xFAn8bM1gzc/FOX2awLISvWe0PV8ptFKcon+wZ5qYkg==", + "dev": true + }, + "mime-types": { + "version": "2.1.22", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.22.tgz", + "integrity": "sha512-aGl6TZGnhm/li6F7yx82bJiBZwgiEa4Hf6CNr8YO+r5UHr53tSTYZb102zyU50DOWWKeOv0uQLRL0/9EiKWCog==", + "dev": true, + "requires": { + "mime-db": "~1.38.0" + } + }, + "mimic-fn": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-1.2.0.tgz", + "integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==", + "dev": true + }, + "minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "dev": true + }, + "minimalistic-crypto-utils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-crypto-utils/-/minimalistic-crypto-utils-1.0.1.tgz", + "integrity": "sha1-9sAMHAsIIkblxNmd+4x8CDsrWCo=", + "dev": true + }, + "minimatch": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "dev": true, + "requires": { + "brace-expansion": "^1.1.7" + } + }, + "minimist": { + "version": "0.0.8", + "resolved": "http://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", + "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", + "dev": true + }, + "mississippi": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mississippi/-/mississippi-3.0.0.tgz", + "integrity": "sha512-x471SsVjUtBRtcvd4BzKE9kFC+/2TeWgKCgw0bZcw1b9l2X3QX5vCWgF+KaZaYm87Ss//rHnWryupDrgLvmSkA==", + "dev": true, + "requires": { + "concat-stream": "^1.5.0", + "duplexify": "^3.4.2", + "end-of-stream": "^1.1.0", + "flush-write-stream": "^1.0.0", + "from2": "^2.1.0", + "parallel-transform": "^1.1.0", + "pump": "^3.0.0", + "pumpify": "^1.3.3", + "stream-each": "^1.1.0", + "through2": "^2.0.0" + } + }, + "mixin-deep": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.1.tgz", + "integrity": "sha512-8ZItLHeEgaqEvd5lYBXfm4EZSFCX29Jb9K+lAHhDKzReKBQKj3R+7NOF6tjqYi9t4oI8VUfaWITJQm86wnXGNQ==", + "dev": true, + "requires": { + "for-in": "^1.0.2", + "is-extendable": "^1.0.1" + }, + "dependencies": { + "is-extendable": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz", + "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", + "dev": true, + "requires": { + "is-plain-object": "^2.0.4" + } + } + } + }, + "mkdirp": { + "version": "0.5.1", + "resolved": "http://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", + "dev": true, + "requires": { + "minimist": "0.0.8" + } + }, + "move-concurrently": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/move-concurrently/-/move-concurrently-1.0.1.tgz", + "integrity": "sha1-viwAX9oy4LKa8fBdfEszIUxwH5I=", + "dev": true, + "requires": { + "aproba": "^1.1.1", + "copy-concurrently": "^1.0.0", + "fs-write-stream-atomic": "^1.0.8", + "mkdirp": "^0.5.1", + "rimraf": "^2.5.4", + "run-queue": "^1.0.3" + } + }, + "ms": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", + "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==", + "dev": true + }, + "nan": { + "version": "2.12.1", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.12.1.tgz", + "integrity": "sha512-JY7V6lRkStKcKTvHO5NVSQRv+RV+FIL5pvDoLiAtSL9pKlC5x9PKQcZDsq7m4FO4d57mkhC6Z+QhAh3Jdk5JFw==", + "dev": true, + "optional": true + }, + "nanomatch": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/nanomatch/-/nanomatch-1.2.13.tgz", + "integrity": "sha512-fpoe2T0RbHwBTBUOftAfBPaDEi06ufaUai0mE6Yn1kacc3SnTErfb/h+X94VXzI64rKFHYImXSvdwGGCmwOqCA==", + "dev": true, + "requires": { + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "fragment-cache": "^0.2.1", + "is-windows": "^1.0.2", + "kind-of": "^6.0.2", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" + } + }, + "natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=", + "dev": true + }, + "neo-async": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.0.tgz", + "integrity": "sha512-MFh0d/Wa7vkKO3Y3LlacqAEeHK0mckVqzDieUKTT+KGxi+zIpeVsFxymkIiRpbpDziHc290Xr9A1O4Om7otoRA==", + "dev": true + }, + "nice-try": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==", + "dev": true + }, + "node-int64": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", + "integrity": "sha1-h6kGXNs1XTGC2PlM4RGIuCXGijs=", + "dev": true + }, + "node-libs-browser": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/node-libs-browser/-/node-libs-browser-2.2.0.tgz", + "integrity": "sha512-5MQunG/oyOaBdttrL40dA7bUfPORLRWMUJLQtMg7nluxUvk5XwnLdL9twQHFAjRx/y7mIMkLKT9++qPbbk6BZA==", + "dev": true, + "requires": { + "assert": "^1.1.1", + "browserify-zlib": "^0.2.0", + "buffer": "^4.3.0", + "console-browserify": "^1.1.0", + "constants-browserify": "^1.0.0", + "crypto-browserify": "^3.11.0", + "domain-browser": "^1.1.1", + "events": "^3.0.0", + "https-browserify": "^1.0.0", + "os-browserify": "^0.3.0", + "path-browserify": "0.0.0", + "process": "^0.11.10", + "punycode": "^1.2.4", + "querystring-es3": "^0.2.0", + "readable-stream": "^2.3.3", + "stream-browserify": "^2.0.1", + "stream-http": "^2.7.2", + "string_decoder": "^1.0.0", + "timers-browserify": "^2.0.4", + "tty-browserify": "0.0.0", + "url": "^0.11.0", + "util": "^0.11.0", + "vm-browserify": "0.0.4" + }, + "dependencies": { + "punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=", + "dev": true + }, + "util": { + "version": "0.11.1", + "resolved": "https://registry.npmjs.org/util/-/util-0.11.1.tgz", + "integrity": "sha512-HShAsny+zS2TZfaXxD9tYj4HQGlBezXZMZuM/S5PKLLoZkShZiGk9o5CzukI1LVHZvjdvZ2Sj1aW/Ndn2NB/HQ==", + "dev": true, + "requires": { + "inherits": "2.0.3" + } + } + } + }, + "node-modules-regexp": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-modules-regexp/-/node-modules-regexp-1.0.0.tgz", + "integrity": "sha1-jZ2+KJZKSsVxLpExZCEHxx6Q7EA=", + "dev": true + }, + "node-notifier": { + "version": "5.4.0", + "resolved": "https://registry.npmjs.org/node-notifier/-/node-notifier-5.4.0.tgz", + "integrity": "sha512-SUDEb+o71XR5lXSTyivXd9J7fCloE3SyP4lSgt3lU2oSANiox+SxlNRGPjDKrwU1YN3ix2KN/VGGCg0t01rttQ==", + "dev": true, + "requires": { + "growly": "^1.3.0", + "is-wsl": "^1.1.0", + "semver": "^5.5.0", + "shellwords": "^0.1.1", + "which": "^1.3.0" + } + }, + "normalize-package-data": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", + "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", + "dev": true, + "requires": { + "hosted-git-info": "^2.1.4", + "resolve": "^1.10.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" + } + }, + "normalize-path": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-2.1.1.tgz", + "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", + "dev": true, + "requires": { + "remove-trailing-separator": "^1.0.1" + } + }, + "npm-run-path": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", + "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", + "dev": true, + "requires": { + "path-key": "^2.0.0" + } + }, + "number-is-nan": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/number-is-nan/-/number-is-nan-1.0.1.tgz", + "integrity": "sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0=", + "dev": true + }, + "nwsapi": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.1.1.tgz", + "integrity": "sha512-T5GaA1J/d34AC8mkrFD2O0DR17kwJ702ZOtJOsS8RpbsQZVOC2/xYFb1i/cw+xdM54JIlMuojjDOYct8GIWtwg==", + "dev": true + }, + "oauth-sign": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", + "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", + "dev": true + }, + "object-copy": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/object-copy/-/object-copy-0.1.0.tgz", + "integrity": "sha1-fn2Fi3gb18mRpBupde04EnVOmYw=", + "dev": true, + "requires": { + "copy-descriptor": "^0.1.0", + "define-property": "^0.2.5", + "kind-of": "^3.0.3" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "object-keys": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.0.tgz", + "integrity": "sha512-6OO5X1+2tYkNyNEx6TsCxEqFfRWaqx6EtMiSbGrw8Ob8v9Ne+Hl8rBAgLBZn5wjEz3s/s6U1WXFUFOcxxAwUpg==", + "dev": true + }, + "object-visit": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/object-visit/-/object-visit-1.0.1.tgz", + "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=", + "dev": true, + "requires": { + "isobject": "^3.0.0" + } + }, + "object.getownpropertydescriptors": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/object.getownpropertydescriptors/-/object.getownpropertydescriptors-2.0.3.tgz", + "integrity": "sha1-h1jIRvW0B62rDyNuCYbxSwUcqhY=", + "dev": true, + "requires": { + "define-properties": "^1.1.2", + "es-abstract": "^1.5.1" + } + }, + "object.pick": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/object.pick/-/object.pick-1.3.0.tgz", + "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", + "dev": true, + "requires": { + "isobject": "^3.0.1" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "dev": true, + "requires": { + "wrappy": "1" + } + }, + "optimist": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/optimist/-/optimist-0.6.1.tgz", + "integrity": "sha1-2j6nRob6IaGaERwybpDrFaAZZoY=", + "dev": true, + "requires": { + "minimist": "~0.0.1", + "wordwrap": "~0.0.2" + } + }, + "optionator": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.8.2.tgz", + "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", + "dev": true, + "requires": { + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.4", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "wordwrap": "~1.0.0" + }, + "dependencies": { + "wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus=", + "dev": true + } + } + }, + "os-browserify": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/os-browserify/-/os-browserify-0.3.0.tgz", + "integrity": "sha1-hUNzx/XCMVkU/Jv8a9gjj92h7Cc=", + "dev": true + }, + "os-locale": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/os-locale/-/os-locale-3.1.0.tgz", + "integrity": "sha512-Z8l3R4wYWM40/52Z+S265okfFj8Kt2cC2MKY+xNi3kFs+XGI7WXu/I309QQQYbRW4ijiZ+yxs9pqEhJh0DqW3Q==", + "dev": true, + "requires": { + "execa": "^1.0.0", + "lcid": "^2.0.0", + "mem": "^4.0.0" + } + }, + "p-defer": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-defer/-/p-defer-1.0.0.tgz", + "integrity": "sha1-n26xgvbJqozXQwBKfU+WsZaw+ww=", + "dev": true + }, + "p-each-series": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-each-series/-/p-each-series-1.0.0.tgz", + "integrity": "sha1-kw89Et0fUOdDRFeiLNbwSsatf3E=", + "dev": true, + "requires": { + "p-reduce": "^1.0.0" + } + }, + "p-finally": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=", + "dev": true + }, + "p-is-promise": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-is-promise/-/p-is-promise-2.0.0.tgz", + "integrity": "sha512-pzQPhYMCAgLAKPWD2jC3Se9fEfrD9npNos0y150EeqZll7akhEgGhTW/slB6lHku8AvYGiJ+YJ5hfHKePPgFWg==", + "dev": true + }, + "p-limit": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz", + "integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==", + "dev": true, + "requires": { + "p-try": "^2.0.0" + } + }, + "p-locate": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-3.0.0.tgz", + "integrity": "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ==", + "dev": true, + "requires": { + "p-limit": "^2.0.0" + } + }, + "p-reduce": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-reduce/-/p-reduce-1.0.0.tgz", + "integrity": "sha1-GMKw3ZNqRpClKfgjH1ig/bakffo=", + "dev": true + }, + "p-try": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.0.0.tgz", + "integrity": "sha512-hMp0onDKIajHfIkdRk3P4CdCmErkYAxxDtP3Wx/4nZ3aGlau2VKh3mZpcuFkH27WQkL/3WBCPOktzA9ZOAnMQQ==", + "dev": true + }, + "pako": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.10.tgz", + "integrity": "sha512-0DTvPVU3ed8+HNXOu5Bs+o//Mbdj9VNQMUOe9oKCwh8l0GNwpTDMKCWbRjgtD291AWnkAgkqA/LOnQS8AmS1tw==", + "dev": true + }, + "parallel-transform": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/parallel-transform/-/parallel-transform-1.1.0.tgz", + "integrity": "sha1-1BDwZbBdojCB/NEPKIVMKb2jOwY=", + "dev": true, + "requires": { + "cyclist": "~0.2.2", + "inherits": "^2.0.3", + "readable-stream": "^2.1.5" + } + }, + "parse-asn1": { + "version": "5.1.4", + "resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.4.tgz", + "integrity": "sha512-Qs5duJcuvNExRfFZ99HDD3z4mAi3r9Wl/FOjEOijlxwCZs7E7mW2vjTpgQ4J8LpTF8x5v+1Vn5UQFejmWT11aw==", + "dev": true, + "requires": { + "asn1.js": "^4.0.0", + "browserify-aes": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.0", + "pbkdf2": "^3.0.3", + "safe-buffer": "^5.1.1" + } + }, + "parse-json": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", + "integrity": "sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=", + "dev": true, + "requires": { + "error-ex": "^1.3.1", + "json-parse-better-errors": "^1.0.1" + } + }, + "parse-passwd": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/parse-passwd/-/parse-passwd-1.0.0.tgz", + "integrity": "sha1-bVuTSkVpk7I9N/QKOC1vFmao5cY=", + "dev": true + }, + "parse5": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-4.0.0.tgz", + "integrity": "sha512-VrZ7eOd3T1Fk4XWNXMgiGBK/z0MG48BWG2uQNU4I72fkQuKUTZpl+u9k+CxEG0twMVzSmXEEz12z5Fnw1jIQFA==", + "dev": true + }, + "pascalcase": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/pascalcase/-/pascalcase-0.1.1.tgz", + "integrity": "sha1-s2PlXoAGym/iF4TS2yK9FdeRfxQ=", + "dev": true + }, + "path-browserify": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.0.tgz", + "integrity": "sha1-oLhwcpquIUAFt9UDLsLLuw+0RRo=", + "dev": true + }, + "path-dirname": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/path-dirname/-/path-dirname-1.0.2.tgz", + "integrity": "sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA=", + "dev": true + }, + "path-exists": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-3.0.0.tgz", + "integrity": "sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=", + "dev": true + }, + "path-is-absolute": { + "version": "1.0.1", + "resolved": "http://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "dev": true + }, + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=", + "dev": true + }, + "path-parse": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.6.tgz", + "integrity": "sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==", + "dev": true + }, + "path-type": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-3.0.0.tgz", + "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", + "dev": true, + "requires": { + "pify": "^3.0.0" + } + }, + "pbkdf2": { + "version": "3.0.17", + "resolved": "https://registry.npmjs.org/pbkdf2/-/pbkdf2-3.0.17.tgz", + "integrity": "sha512-U/il5MsrZp7mGg3mSQfn742na2T+1/vHDCG5/iTI3X9MKUuYUZVLQhyRsg06mCgDBTd57TxzgZt7P+fYfjRLtA==", + "dev": true, + "requires": { + "create-hash": "^1.1.2", + "create-hmac": "^1.1.4", + "ripemd160": "^2.0.1", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" + } + }, + "performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=", + "dev": true + }, + "pify": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", + "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", + "dev": true + }, + "pirates": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.1.tgz", + "integrity": "sha512-WuNqLTbMI3tmfef2TKxlQmAiLHKtFhlsCZnPIpuv2Ow0RDVO8lfy1Opf4NUzlMXLjPl+Men7AuVdX6TA+s+uGA==", + "dev": true, + "requires": { + "node-modules-regexp": "^1.0.0" + } + }, + "pkg-dir": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-3.0.0.tgz", + "integrity": "sha512-/E57AYkoeQ25qkxMj5PBOVgF8Kiu/h7cYS30Z5+R7WaiCCBfLq58ZI/dSeaEKb9WVJV5n/03QwrN3IeWIFllvw==", + "dev": true, + "requires": { + "find-up": "^3.0.0" + } + }, + "pn": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/pn/-/pn-1.1.0.tgz", + "integrity": "sha512-2qHaIQr2VLRFoxe2nASzsV6ef4yOOH+Fi9FBOVH6cqeSgUnoyySPZkxzLuzd+RYOQTRpROA0ztTMqxROKSb/nA==", + "dev": true + }, + "posix-character-classes": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/posix-character-classes/-/posix-character-classes-0.1.1.tgz", + "integrity": "sha1-AerA/jta9xoqbAL+q7jB/vfgDqs=", + "dev": true + }, + "prelude-ls": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz", + "integrity": "sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=", + "dev": true + }, + "pretty-format": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-24.0.0.tgz", + "integrity": "sha512-LszZaKG665djUcqg5ZQq+XzezHLKrxsA86ZABTozp+oNhkdqa+tG2dX4qa6ERl5c/sRDrAa3lHmwnvKoP+OG/g==", + "dev": true, + "requires": { + "ansi-regex": "^4.0.0", + "ansi-styles": "^3.2.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", + "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==", + "dev": true + } + } + }, + "process": { + "version": "0.11.10", + "resolved": "https://registry.npmjs.org/process/-/process-0.11.10.tgz", + "integrity": "sha1-czIwDoQBYb2j5podHZGn1LwW8YI=", + "dev": true + }, + "process-nextick-args": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.0.tgz", + "integrity": "sha512-MtEC1TqN0EU5nephaJ4rAtThHtC86dNN9qCuEhtshvpVBkAW5ZO7BASN9REnF9eoXGcRub+pFuKEpOHE+HbEMw==", + "dev": true + }, + "promise-inflight": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/promise-inflight/-/promise-inflight-1.0.1.tgz", + "integrity": "sha1-mEcocL8igTL8vdhoEputEsPAKeM=", + "dev": true + }, + "prompts": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.0.3.tgz", + "integrity": "sha512-H8oWEoRZpybm6NV4to9/1limhttEo13xK62pNvn2JzY0MA03p7s0OjtmhXyon3uJmxiJJVSuUwEJFFssI3eBiQ==", + "dev": true, + "requires": { + "kleur": "^3.0.2", + "sisteransi": "^1.0.0" + } + }, + "prr": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/prr/-/prr-1.0.1.tgz", + "integrity": "sha1-0/wRS6BplaRexok/SEzrHXj19HY=", + "dev": true + }, + "psl": { + "version": "1.1.31", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.1.31.tgz", + "integrity": "sha512-/6pt4+C+T+wZUieKR620OpzN/LlnNKuWjy1iFLQ/UG35JqHlR/89MP1d96dUfkf6Dne3TuLQzOYEYshJ+Hx8mw==", + "dev": true + }, + "public-encrypt": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/public-encrypt/-/public-encrypt-4.0.3.tgz", + "integrity": "sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q==", + "dev": true, + "requires": { + "bn.js": "^4.1.0", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "parse-asn1": "^5.0.0", + "randombytes": "^2.0.1", + "safe-buffer": "^5.1.2" + } + }, + "pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "dev": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "pumpify": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/pumpify/-/pumpify-1.5.1.tgz", + "integrity": "sha512-oClZI37HvuUJJxSKKrC17bZ9Cu0ZYhEAGPsPUy9KlMUmv9dKX2o77RUmq7f3XjIxbwyGwYzbzQ1L2Ks8sIradQ==", + "dev": true, + "requires": { + "duplexify": "^3.6.0", + "inherits": "^2.0.3", + "pump": "^2.0.0" + }, + "dependencies": { + "pump": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/pump/-/pump-2.0.1.tgz", + "integrity": "sha512-ruPMNRkN3MHP1cWJc9OWr+T/xDP0jhXYCLfJcBuX54hhfIBnaQmAUMfDcG4DM5UMWByBbJY69QSphm3jtDKIkA==", + "dev": true, + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + } + } + }, + "punycode": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.1.1.tgz", + "integrity": "sha512-XRsRjdf+j5ml+y/6GKHPZbrF/8p2Yga0JPtdqTIY2Xe5ohJPD9saDJJLPvp9+NSBprVvevdXZybnj2cv8OEd0A==", + "dev": true + }, + "qs": { + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.2.tgz", + "integrity": "sha512-N5ZAX4/LxJmF+7wN74pUD6qAh9/wnvdQcjq9TZjevvXzSUo7bfmw91saqMjzGS2xq91/odN2dW/WOl7qQHNDGA==", + "dev": true + }, + "querystring": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", + "integrity": "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA=", + "dev": true + }, + "querystring-es3": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/querystring-es3/-/querystring-es3-0.2.1.tgz", + "integrity": "sha1-nsYfeQSYdXB9aUFFlv2Qek1xHnM=", + "dev": true + }, + "randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dev": true, + "requires": { + "safe-buffer": "^5.1.0" + } + }, + "randomfill": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/randomfill/-/randomfill-1.0.4.tgz", + "integrity": "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw==", + "dev": true, + "requires": { + "randombytes": "^2.0.5", + "safe-buffer": "^5.1.0" + } + }, + "read-pkg": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-3.0.0.tgz", + "integrity": "sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=", + "dev": true, + "requires": { + "load-json-file": "^4.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^3.0.0" + } + }, + "read-pkg-up": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-4.0.0.tgz", + "integrity": "sha512-6etQSH7nJGsK0RbG/2TeDzZFa8shjQ1um+SwQQ5cwKy0dhSXdOncEhb1CPpvQG4h7FyOV6EB6YlV0yJvZQNAkA==", + "dev": true, + "requires": { + "find-up": "^3.0.0", + "read-pkg": "^3.0.0" + } + }, + "readable-stream": { + "version": "2.3.6", + "resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", + "dev": true, + "requires": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "readdirp": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-2.2.1.tgz", + "integrity": "sha512-1JU/8q+VgFZyxwrJ+SVIOsh+KywWGpds3NTqikiKpDMZWScmAYyKIgqkO+ARvNWJfXeXR1zxz7aHF4u4CyH6vQ==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.11", + "micromatch": "^3.1.10", + "readable-stream": "^2.0.2" + } + }, + "realpath-native": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/realpath-native/-/realpath-native-1.1.0.tgz", + "integrity": "sha512-wlgPA6cCIIg9gKz0fgAPjnzh4yR/LnXovwuo9hvyGvx3h8nX4+/iLZplfUWasXpqD8BdnGnP5njOFjkUwPzvjA==", + "dev": true, + "requires": { + "util.promisify": "^1.0.0" + } + }, + "regex-not": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/regex-not/-/regex-not-1.0.2.tgz", + "integrity": "sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==", + "dev": true, + "requires": { + "extend-shallow": "^3.0.2", + "safe-regex": "^1.1.0" + } + }, + "remove-trailing-separator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/remove-trailing-separator/-/remove-trailing-separator-1.1.0.tgz", + "integrity": "sha1-wkvOKig62tW8P1jg1IJJuSN52O8=", + "dev": true + }, + "repeat-element": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/repeat-element/-/repeat-element-1.1.3.tgz", + "integrity": "sha512-ahGq0ZnV5m5XtZLMb+vP76kcAM5nkLqk0lpqAuojSKGgQtn4eRi4ZZGm2olo2zKFH+sMsWaqOCW1dqAnOru72g==", + "dev": true + }, + "repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=", + "dev": true + }, + "request": { + "version": "2.88.0", + "resolved": "https://registry.npmjs.org/request/-/request-2.88.0.tgz", + "integrity": "sha512-NAqBSrijGLZdM0WZNsInLJpkJokL72XYjUpnB0iwsRgxh7dB6COrHnTBNwN0E+lHDAJzu7kLAkDeY08z2/A0hg==", + "dev": true, + "requires": { + "aws-sign2": "~0.7.0", + "aws4": "^1.8.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.6", + "extend": "~3.0.2", + "forever-agent": "~0.6.1", + "form-data": "~2.3.2", + "har-validator": "~5.1.0", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.19", + "oauth-sign": "~0.9.0", + "performance-now": "^2.1.0", + "qs": "~6.5.2", + "safe-buffer": "^5.1.2", + "tough-cookie": "~2.4.3", + "tunnel-agent": "^0.6.0", + "uuid": "^3.3.2" + }, + "dependencies": { + "punycode": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", + "integrity": "sha1-wNWmOycYgArY4esPpSachN1BhF4=", + "dev": true + }, + "tough-cookie": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.4.3.tgz", + "integrity": "sha512-Q5srk/4vDM54WJsJio3XNn6K2sCG+CQ8G5Wz6bZhRZoAe/+TxjWB/GlFAnYEbkYVlON9FMk/fE3h2RLpPXo4lQ==", + "dev": true, + "requires": { + "psl": "^1.1.24", + "punycode": "^1.4.1" + } + } + } + }, + "request-promise-core": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/request-promise-core/-/request-promise-core-1.1.2.tgz", + "integrity": "sha512-UHYyq1MO8GsefGEt7EprS8UrXsm1TxEvFUX1IMTuSLU2Rh7fTIdFtl8xD7JiEYiWU2dl+NYAjCTksTehQUxPag==", + "dev": true, + "requires": { + "lodash": "^4.17.11" + } + }, + "request-promise-native": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/request-promise-native/-/request-promise-native-1.0.7.tgz", + "integrity": "sha512-rIMnbBdgNViL37nZ1b3L/VfPOpSi0TqVDQPAvO6U14lMzOLrt5nilxCQqtDKhZeDiW0/hkCXGoQjhgJd/tCh6w==", + "dev": true, + "requires": { + "request-promise-core": "1.1.2", + "stealthy-require": "^1.1.1", + "tough-cookie": "^2.3.3" + } + }, + "require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha1-jGStX9MNqxyXbiNE/+f3kqam30I=", + "dev": true + }, + "require-main-filename": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-1.0.1.tgz", + "integrity": "sha1-l/cXtp1IeE9fUmpsWqj/3aBVpNE=", + "dev": true + }, + "resolve": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.10.0.tgz", + "integrity": "sha512-3sUr9aq5OfSg2S9pNtPA9hL1FVEAjvfOC4leW0SNf/mpnaakz2a9femSd6LqAww2RaFctwyf1lCqnTHuF1rxDg==", + "dev": true, + "requires": { + "path-parse": "^1.0.6" + } + }, + "resolve-cwd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-2.0.0.tgz", + "integrity": "sha1-AKn3OHVW4nA46uIyyqNypqWbZlo=", + "dev": true, + "requires": { + "resolve-from": "^3.0.0" + } + }, + "resolve-dir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/resolve-dir/-/resolve-dir-1.0.1.tgz", + "integrity": "sha1-eaQGRMNivoLybv/nOcm7U4IEb0M=", + "dev": true, + "requires": { + "expand-tilde": "^2.0.0", + "global-modules": "^1.0.0" + } + }, + "resolve-from": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-3.0.0.tgz", + "integrity": "sha1-six699nWiBvItuZTM17rywoYh0g=", + "dev": true + }, + "resolve-url": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/resolve-url/-/resolve-url-0.2.1.tgz", + "integrity": "sha1-LGN/53yJOv0qZj/iGqkIAGjiBSo=", + "dev": true + }, + "ret": { + "version": "0.1.15", + "resolved": "https://registry.npmjs.org/ret/-/ret-0.1.15.tgz", + "integrity": "sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==", + "dev": true + }, + "rimraf": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.6.3.tgz", + "integrity": "sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==", + "dev": true, + "requires": { + "glob": "^7.1.3" + } + }, + "ripemd160": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/ripemd160/-/ripemd160-2.0.2.tgz", + "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==", + "dev": true, + "requires": { + "hash-base": "^3.0.0", + "inherits": "^2.0.1" + } + }, + "rsvp": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/rsvp/-/rsvp-3.6.2.tgz", + "integrity": "sha512-OfWGQTb9vnwRjwtA2QwpG2ICclHC3pgXZO5xt8H2EfgDquO0qVdSb5T88L4qJVAEugbS56pAuV4XZM58UX8ulw==", + "dev": true + }, + "run-queue": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/run-queue/-/run-queue-1.0.3.tgz", + "integrity": "sha1-6Eg5bwV9Ij8kOGkkYY4laUFh7Ec=", + "dev": true, + "requires": { + "aproba": "^1.1.1" + } + }, + "safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true + }, + "safe-regex": { + "version": "1.1.0", + "resolved": "http://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", + "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", + "dev": true, + "requires": { + "ret": "~0.1.10" + } + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true + }, + "sane": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/sane/-/sane-3.1.0.tgz", + "integrity": "sha512-G5GClRRxT1cELXfdAq7UKtUsv8q/ZC5k8lQGmjEm4HcAl3HzBy68iglyNCmw4+0tiXPCBZntslHlRhbnsSws+Q==", + "dev": true, + "requires": { + "anymatch": "^2.0.0", + "capture-exit": "^1.2.0", + "exec-sh": "^0.2.0", + "execa": "^1.0.0", + "fb-watchman": "^2.0.0", + "fsevents": "^1.2.3", + "micromatch": "^3.1.4", + "minimist": "^1.1.1", + "walker": "~1.0.5", + "watch": "~0.18.0" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "resolved": "http://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + } + } + }, + "sax": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", + "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==", + "dev": true + }, + "schema-utils": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-1.0.0.tgz", + "integrity": "sha512-i27Mic4KovM/lnGsy8whRCHhc7VicJajAjTrYg11K9zfZXnYIt4k5F+kZkwjnrhKzLic/HLU4j11mjsz2G/75g==", + "dev": true, + "requires": { + "ajv": "^6.1.0", + "ajv-errors": "^1.0.0", + "ajv-keywords": "^3.1.0" + } + }, + "semver": { + "version": "5.6.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.6.0.tgz", + "integrity": "sha512-RS9R6R35NYgQn++fkDWaOmqGoj4Ek9gGs+DPxNUZKuwE183xjJroKvyo1IzVFeXvUrvmALy6FWD5xrdJT25gMg==", + "dev": true + }, + "serialize-javascript": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-1.6.1.tgz", + "integrity": "sha512-A5MOagrPFga4YaKQSWHryl7AXvbQkEqpw4NNYMTNYUNV51bA8ABHgYFpqKx+YFFrw59xMV1qGH1R4AgoNIVgCw==", + "dev": true + }, + "set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha1-BF+XgtARrppoA93TgrJDkrPYkPc=", + "dev": true + }, + "set-value": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-2.0.0.tgz", + "integrity": "sha512-hw0yxk9GT/Hr5yJEYnHNKYXkIA8mVJgd9ditYZCe16ZczcaELYYcfvaXesNACk2O8O0nTiPQcQhGUQj8JLzeeg==", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-extendable": "^0.1.1", + "is-plain-object": "^2.0.3", + "split-string": "^3.0.1" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + } + } + }, + "setimmediate": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", + "integrity": "sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU=", + "dev": true + }, + "sha.js": { + "version": "2.4.11", + "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", + "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", + "dev": true, + "requires": { + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "dev": true, + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=", + "dev": true + }, + "shellwords": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/shellwords/-/shellwords-0.1.1.tgz", + "integrity": "sha512-vFwSUfQvqybiICwZY5+DAWIPLKsWO31Q91JSKl3UYv+K5c2QRPzn0qzec6QPu1Qc9eHYItiP3NdJqNVqetYAww==", + "dev": true + }, + "signal-exit": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", + "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=", + "dev": true + }, + "sisteransi": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.0.tgz", + "integrity": "sha512-N+z4pHB4AmUv0SjveWRd6q1Nj5w62m5jodv+GD8lvmbY/83T/rpbJGZOnK5T149OldDj4Db07BSv9xY4K6NTPQ==", + "dev": true + }, + "slash": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-2.0.0.tgz", + "integrity": "sha512-ZYKh3Wh2z1PpEXWr0MpSBZ0V6mZHAQfYevttO11c51CaWjGTaadiKZ+wVt1PbMlDV5qhMFslpZCemhwOK7C89A==", + "dev": true + }, + "snapdragon": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz", + "integrity": "sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg==", + "dev": true, + "requires": { + "base": "^0.11.1", + "debug": "^2.2.0", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "map-cache": "^0.2.2", + "source-map": "^0.5.6", + "source-map-resolve": "^0.5.0", + "use": "^3.1.0" + }, + "dependencies": { + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dev": true, + "requires": { + "ms": "2.0.0" + } + }, + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + }, + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "dev": true + } + } + }, + "snapdragon-node": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/snapdragon-node/-/snapdragon-node-2.1.1.tgz", + "integrity": "sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==", + "dev": true, + "requires": { + "define-property": "^1.0.0", + "isobject": "^3.0.0", + "snapdragon-util": "^3.0.1" + }, + "dependencies": { + "define-property": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-1.0.0.tgz", + "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", + "dev": true, + "requires": { + "is-descriptor": "^1.0.0" + } + }, + "is-accessor-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-1.0.0.tgz", + "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-data-descriptor": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-1.0.0.tgz", + "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", + "dev": true, + "requires": { + "kind-of": "^6.0.0" + } + }, + "is-descriptor": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-descriptor/-/is-descriptor-1.0.2.tgz", + "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", + "dev": true, + "requires": { + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" + } + } + } + }, + "snapdragon-util": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/snapdragon-util/-/snapdragon-util-3.0.1.tgz", + "integrity": "sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==", + "dev": true, + "requires": { + "kind-of": "^3.2.0" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "source-list-map": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/source-list-map/-/source-list-map-2.0.1.tgz", + "integrity": "sha512-qnQ7gVMxGNxsiL4lEuJwe/To8UnK7fAnmbGEEH8RpLouuKbeEm0lhbQVFIrNSuB+G7tVrAlVsZgETT5nljf+Iw==", + "dev": true + }, + "source-map": { + "version": "0.5.7", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", + "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=", + "dev": true + }, + "source-map-resolve": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/source-map-resolve/-/source-map-resolve-0.5.2.tgz", + "integrity": "sha512-MjqsvNwyz1s0k81Goz/9vRBe9SZdB09Bdw+/zYyO+3CuPk6fouTaxscHkgtE8jKvf01kVfl8riHzERQ/kefaSA==", + "dev": true, + "requires": { + "atob": "^2.1.1", + "decode-uri-component": "^0.2.0", + "resolve-url": "^0.2.1", + "source-map-url": "^0.4.0", + "urix": "^0.1.0" + } + }, + "source-map-support": { + "version": "0.5.10", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.10.tgz", + "integrity": "sha512-YfQ3tQFTK/yzlGJuX8pTwa4tifQj4QS2Mj7UegOu8jAz59MqIiMGPXxQhVQiIMNzayuUSF/jEuVnfFF5JqybmQ==", + "dev": true, + "requires": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "source-map-url": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/source-map-url/-/source-map-url-0.4.0.tgz", + "integrity": "sha1-PpNdfd1zYxuXZZlW1VEo6HtQhKM=", + "dev": true + }, + "spdx-correct": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.1.0.tgz", + "integrity": "sha512-lr2EZCctC2BNR7j7WzJ2FpDznxky1sjfxvvYEyzxNyb6lZXHODmEoJeFu4JupYlkfha1KZpJyoqiJ7pgA1qq8Q==", + "dev": true, + "requires": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-exceptions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.2.0.tgz", + "integrity": "sha512-2XQACfElKi9SlVb1CYadKDXvoajPgBVPn/gOQLrTvHdElaVhr7ZEbqJaRnJLVNeaI4cMEAgVCeBMKF6MWRDCRA==", + "dev": true + }, + "spdx-expression-parse": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.0.tgz", + "integrity": "sha512-Yg6D3XpRD4kkOmTpdgbUiEJFKghJH03fiC1OPll5h/0sO6neh2jqRDVHOQ4o/LMea0tgCkbMgea5ip/e+MkWyg==", + "dev": true, + "requires": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "spdx-license-ids": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.3.tgz", + "integrity": "sha512-uBIcIl3Ih6Phe3XHK1NqboJLdGfwr1UN3k6wSD1dZpmPsIkb8AGNbZYJ1fOBk834+Gxy8rpfDxrS6XLEMZMY2g==", + "dev": true + }, + "split-string": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/split-string/-/split-string-3.1.0.tgz", + "integrity": "sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==", + "dev": true, + "requires": { + "extend-shallow": "^3.0.0" + } + }, + "sprintf-js": { + "version": "1.0.3", + "resolved": "http://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", + "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", + "dev": true + }, + "sshpk": { + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.16.1.tgz", + "integrity": "sha512-HXXqVUq7+pcKeLqqZj6mHFUMvXtOJt1uoUx09pFW6011inTMxqI8BA8PM95myrIyyKwdnzjdFjLiE6KBPVtJIg==", + "dev": true, + "requires": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + } + }, + "ssri": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ssri/-/ssri-6.0.1.tgz", + "integrity": "sha512-3Wge10hNcT1Kur4PDFwEieXSCMCJs/7WvSACcrMYrNp+b8kDL1/0wJch5Ni2WrtwEa2IO8OsVfeKIciKCDx/QA==", + "dev": true, + "requires": { + "figgy-pudding": "^3.5.1" + } + }, + "stack-utils": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-1.0.2.tgz", + "integrity": "sha512-MTX+MeG5U994cazkjd/9KNAapsHnibjMLnfXodlkXw76JEea0UiNzrqidzo1emMwk7w5Qhc9jd4Bn9TBb1MFwA==", + "dev": true + }, + "static-extend": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz", + "integrity": "sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=", + "dev": true, + "requires": { + "define-property": "^0.2.5", + "object-copy": "^0.1.0" + }, + "dependencies": { + "define-property": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/define-property/-/define-property-0.2.5.tgz", + "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", + "dev": true, + "requires": { + "is-descriptor": "^0.1.0" + } + } + } + }, + "stealthy-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/stealthy-require/-/stealthy-require-1.1.1.tgz", + "integrity": "sha1-NbCYdbT/SfJqd35QmzCQoyJr8ks=", + "dev": true + }, + "stream-browserify": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/stream-browserify/-/stream-browserify-2.0.2.tgz", + "integrity": "sha512-nX6hmklHs/gr2FuxYDltq8fJA1GDlxKQCz8O/IM4atRqBH8OORmBNgfvW5gG10GT/qQ9u0CzIvr2X5Pkt6ntqg==", + "dev": true, + "requires": { + "inherits": "~2.0.1", + "readable-stream": "^2.0.2" + } + }, + "stream-each": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/stream-each/-/stream-each-1.2.3.tgz", + "integrity": "sha512-vlMC2f8I2u/bZGqkdfLQW/13Zihpej/7PmSiMQsbYddxuTsJp8vRe2x2FvVExZg7FaOds43ROAuFJwPR4MTZLw==", + "dev": true, + "requires": { + "end-of-stream": "^1.1.0", + "stream-shift": "^1.0.0" + } + }, + "stream-http": { + "version": "2.8.3", + "resolved": "https://registry.npmjs.org/stream-http/-/stream-http-2.8.3.tgz", + "integrity": "sha512-+TSkfINHDo4J+ZobQLWiMouQYB+UVYFttRA94FpEzzJ7ZdqcL4uUUQ7WkdkI4DSozGmgBUE/a47L+38PenXhUw==", + "dev": true, + "requires": { + "builtin-status-codes": "^3.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.3.6", + "to-arraybuffer": "^1.0.0", + "xtend": "^4.0.0" + } + }, + "stream-shift": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.0.tgz", + "integrity": "sha1-1cdSgl5TZ+eG944Y5EXqIjoVWVI=", + "dev": true + }, + "string-length": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/string-length/-/string-length-2.0.0.tgz", + "integrity": "sha1-1A27aGo6zpYMHP/KVivyxF+DY+0=", + "dev": true, + "requires": { + "astral-regex": "^1.0.0", + "strip-ansi": "^4.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "dev": true + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "dev": true, + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, + "string-width": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", + "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", + "dev": true, + "requires": { + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", + "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", + "dev": true + }, + "strip-ansi": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", + "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", + "dev": true, + "requires": { + "ansi-regex": "^3.0.0" + } + } + } + }, + "string_decoder": { + "version": "1.1.1", + "resolved": "http://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "requires": { + "safe-buffer": "~5.1.0" + } + }, + "strip-ansi": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.0.0.tgz", + "integrity": "sha512-Uu7gQyZI7J7gn5qLn1Np3G9vcYGTVqB+lFTytnDJv83dd8T22aGH451P3jueT2/QemInJDfxHB5Tde5OzgG1Ow==", + "dev": true, + "requires": { + "ansi-regex": "^4.0.0" + }, + "dependencies": { + "ansi-regex": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.0.0.tgz", + "integrity": "sha512-iB5Dda8t/UqpPI/IjsejXu5jOGDrzn41wJyljwPH65VCIbk6+1BzFIMJGFwTNrYXT1CrD+B4l19U7awiQ8rk7w==", + "dev": true + } + } + }, + "strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha1-IzTBjpx1n3vdVv3vfprj1YjmjtM=", + "dev": true + }, + "strip-eof": { + "version": "1.0.0", + "resolved": "http://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", + "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=", + "dev": true + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dev": true, + "requires": { + "has-flag": "^3.0.0" + } + }, + "symbol-tree": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.2.tgz", + "integrity": "sha1-rifbOPZgp64uHDt9G8KQgZuFGeY=", + "dev": true + }, + "tapable": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-1.1.1.tgz", + "integrity": "sha512-9I2ydhj8Z9veORCw5PRm4u9uebCn0mcCa6scWoNcbZ6dAtoo2618u9UUzxgmsCOreJpqDDuv61LvwofW7hLcBA==", + "dev": true + }, + "terser": { + "version": "3.16.1", + "resolved": "https://registry.npmjs.org/terser/-/terser-3.16.1.tgz", + "integrity": "sha512-JDJjgleBROeek2iBcSNzOHLKsB/MdDf+E/BOAJ0Tk9r7p9/fVobfv7LMJ/g/k3v9SXdmjZnIlFd5nfn/Rt0Xow==", + "dev": true, + "requires": { + "commander": "~2.17.1", + "source-map": "~0.6.1", + "source-map-support": "~0.5.9" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "terser-webpack-plugin": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-1.2.3.tgz", + "integrity": "sha512-GOK7q85oAb/5kE12fMuLdn2btOS9OBZn4VsecpHDywoUC/jLhSAKOiYo0ezx7ss2EXPMzyEWFoE0s1WLE+4+oA==", + "dev": true, + "requires": { + "cacache": "^11.0.2", + "find-cache-dir": "^2.0.0", + "schema-utils": "^1.0.0", + "serialize-javascript": "^1.4.0", + "source-map": "^0.6.1", + "terser": "^3.16.1", + "webpack-sources": "^1.1.0", + "worker-farm": "^1.5.2" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "test-exclude": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-5.1.0.tgz", + "integrity": "sha512-gwf0S2fFsANC55fSeSqpb8BYk6w3FDvwZxfNjeF6FRgvFa43r+7wRiA/Q0IxoRU37wB/LE8IQ4221BsNucTaCA==", + "dev": true, + "requires": { + "arrify": "^1.0.1", + "minimatch": "^3.0.4", + "read-pkg-up": "^4.0.0", + "require-main-filename": "^1.0.1" + } + }, + "test-value": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/test-value/-/test-value-3.0.0.tgz", + "integrity": "sha512-sVACdAWcZkSU9x7AOmJo5TqE+GyNJknHaHsMrR6ZnhjVlVN9Yx6FjHrsKZ3BjIpPCT68zYesPWkakrNupwfOTQ==", + "requires": { + "array-back": "^2.0.0", + "typical": "^2.6.1" + } + }, + "throat": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/throat/-/throat-4.1.0.tgz", + "integrity": "sha1-iQN8vJLFarGJJua6TLsgDhVnKmo=", + "dev": true + }, + "through2": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/through2/-/through2-2.0.5.tgz", + "integrity": "sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==", + "dev": true, + "requires": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + } + }, + "timers-browserify": { + "version": "2.0.10", + "resolved": "https://registry.npmjs.org/timers-browserify/-/timers-browserify-2.0.10.tgz", + "integrity": "sha512-YvC1SV1XdOUaL6gx5CoGroT3Gu49pK9+TZ38ErPldOWW4j49GI1HKs9DV+KGq/w6y+LZ72W1c8cKz2vzY+qpzg==", + "dev": true, + "requires": { + "setimmediate": "^1.0.4" + } + }, + "tmpl": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.4.tgz", + "integrity": "sha1-I2QN17QtAEM5ERQIIOXPRA5SHdE=", + "dev": true + }, + "to-arraybuffer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/to-arraybuffer/-/to-arraybuffer-1.0.1.tgz", + "integrity": "sha1-fSKbH8xjfkZsoIEYCDanqr/4P0M=", + "dev": true + }, + "to-fast-properties": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", + "integrity": "sha1-3F5pjL0HkmW8c+A3doGk5Og/YW4=", + "dev": true + }, + "to-object-path": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/to-object-path/-/to-object-path-0.3.0.tgz", + "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=", + "dev": true, + "requires": { + "kind-of": "^3.0.2" + }, + "dependencies": { + "kind-of": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", + "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", + "dev": true, + "requires": { + "is-buffer": "^1.1.5" + } + } + } + }, + "to-regex": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/to-regex/-/to-regex-3.0.2.tgz", + "integrity": "sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw==", + "dev": true, + "requires": { + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "regex-not": "^1.0.2", + "safe-regex": "^1.1.0" + } + }, + "to-regex-range": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-2.1.1.tgz", + "integrity": "sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=", + "dev": true, + "requires": { + "is-number": "^3.0.0", + "repeat-string": "^1.6.1" + } + }, + "tough-cookie": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", + "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", + "dev": true, + "requires": { + "psl": "^1.1.28", + "punycode": "^2.1.1" + } + }, + "tr46": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-1.0.1.tgz", + "integrity": "sha1-qLE/1r/SSJUZZ0zN5VujaTtwbQk=", + "dev": true, + "requires": { + "punycode": "^2.1.0" + } + }, + "trim-right": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/trim-right/-/trim-right-1.0.1.tgz", + "integrity": "sha1-yy4SAwZ+DI3h9hQJS5/kVwTqYAM=", + "dev": true + }, + "ts-jest": { + "version": "24.0.0", + "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-24.0.0.tgz", + "integrity": "sha512-o8BO3TkMREpAATaFTrXkovMsCpBl2z4NDBoLJuWZcJJj1ijI49UnvDMfVpj+iogn/Jl8Pbhuei5nc/Ti+frEHw==", + "dev": true, + "requires": { + "bs-logger": "0.x", + "buffer-from": "1.x", + "fast-json-stable-stringify": "2.x", + "json5": "2.x", + "make-error": "1.x", + "mkdirp": "0.x", + "resolve": "1.x", + "semver": "^5.5", + "yargs-parser": "10.x" + }, + "dependencies": { + "camelcase": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-4.1.0.tgz", + "integrity": "sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0=", + "dev": true + }, + "yargs-parser": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-10.1.0.tgz", + "integrity": "sha512-VCIyR1wJoEBZUqk5PA+oOBF6ypbwh5aNB3I50guxAL/quggdfs4TtNHQrSazFA3fYZ+tEqfs0zIGlv0c/rgjbQ==", + "dev": true, + "requires": { + "camelcase": "^4.1.0" + } + } + } + }, + "ts-loader": { + "version": "5.3.3", + "resolved": "https://registry.npmjs.org/ts-loader/-/ts-loader-5.3.3.tgz", + "integrity": "sha512-KwF1SplmOJepnoZ4eRIloH/zXL195F51skt7reEsS6jvDqzgc/YSbz9b8E07GxIUwLXdcD4ssrJu6v8CwaTafA==", + "dev": true, + "requires": { + "chalk": "^2.3.0", + "enhanced-resolve": "^4.0.0", + "loader-utils": "^1.0.2", + "micromatch": "^3.1.4", + "semver": "^5.0.1" + } + }, + "tslib": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.3.tgz", + "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==", + "dev": true + }, + "tslint": { + "version": "5.13.1", + "resolved": "https://registry.npmjs.org/tslint/-/tslint-5.13.1.tgz", + "integrity": "sha512-fplQqb2miLbcPhyHoMV4FU9PtNRbgmm/zI5d3SZwwmJQM6V0eodju+hplpyfhLWpmwrDNfNYU57uYRb8s0zZoQ==", + "dev": true, + "requires": { + "babel-code-frame": "^6.22.0", + "builtin-modules": "^1.1.1", + "chalk": "^2.3.0", + "commander": "^2.12.1", + "diff": "^3.2.0", + "glob": "^7.1.1", + "js-yaml": "^3.7.0", + "minimatch": "^3.0.4", + "mkdirp": "^0.5.1", + "resolve": "^1.3.2", + "semver": "^5.3.0", + "tslib": "^1.8.0", + "tsutils": "^2.27.2" + }, + "dependencies": { + "resolve": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.10.0.tgz", + "integrity": "sha512-3sUr9aq5OfSg2S9pNtPA9hL1FVEAjvfOC4leW0SNf/mpnaakz2a9femSd6LqAww2RaFctwyf1lCqnTHuF1rxDg==", + "dev": true, + "requires": { + "path-parse": "^1.0.6" + } + } + } + }, + "tslint-microsoft-contrib": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/tslint-microsoft-contrib/-/tslint-microsoft-contrib-6.1.0.tgz", + "integrity": "sha512-8DgmiPTgNQSYTjrKKv/h1aHnDd7EkGAjTxatrjfSDp5jUXENGI7Qj7qi7T8xBdTZN9Z3nb80u0NhdBBOMcQFHg==", + "dev": true, + "requires": { + "tsutils": "^2.27.2 <2.29.0" + }, + "dependencies": { + "tsutils": { + "version": "2.28.0", + "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-2.28.0.tgz", + "integrity": "sha512-bh5nAtW0tuhvOJnx1GLRn5ScraRLICGyJV5wJhtRWOLsxW70Kk5tZtpK3O/hW6LDnqKS9mlUMPZj9fEMJ0gxqA==", + "dev": true, + "requires": { + "tslib": "^1.8.1" + } + } + } + }, + "tsutils": { + "version": "2.29.0", + "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-2.29.0.tgz", + "integrity": "sha512-g5JVHCIJwzfISaXpXE1qvNalca5Jwob6FjI4AoPlqMusJ6ftFE7IkkFoMhVLRgK+4Kx3gkzb8UZK5t5yTTvEmA==", + "dev": true, + "requires": { + "tslib": "^1.8.1" + } + }, + "tty-browserify": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz", + "integrity": "sha1-oVe6QC2iTpv5V/mqadUk7tQpAaY=", + "dev": true + }, + "tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", + "dev": true, + "requires": { + "safe-buffer": "^5.0.1" + } + }, + "tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q=", + "dev": true + }, + "type-check": { + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz", + "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", + "dev": true, + "requires": { + "prelude-ls": "~1.1.2" + } + }, + "typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", + "dev": true + }, + "typescript": { + "version": "3.3.3333", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-3.3.3333.tgz", + "integrity": "sha512-JjSKsAfuHBE/fB2oZ8NxtRTk5iGcg6hkYXMnZ3Wc+b2RSqejEqTaem11mHASMnFilHrax3sLK0GDzcJrekZYLw==", + "dev": true + }, + "typescript-char": { + "version": "0.0.0", + "resolved": "https://registry.npmjs.org/typescript-char/-/typescript-char-0.0.0.tgz", + "integrity": "sha1-VY/tpzfHZaYQtzfu+7F3Xum8jas=" + }, + "typical": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/typical/-/typical-2.6.1.tgz", + "integrity": "sha1-XAgOXWYcu+OCWdLnCjxyU+hziB0=" + }, + "uglify-js": { + "version": "3.4.9", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.4.9.tgz", + "integrity": "sha512-8CJsbKOtEbnJsTyv6LE6m6ZKniqMiFWmm9sRbopbkGs3gMPPfd3Fh8iIA4Ykv5MgaTbqHr4BaoGLJLZNhsrW1Q==", + "dev": true, + "optional": true, + "requires": { + "commander": "~2.17.1", + "source-map": "~0.6.1" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true, + "optional": true + } + } + }, + "union-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/union-value/-/union-value-1.0.0.tgz", + "integrity": "sha1-XHHDTLW61dzr4+oM0IIHulqhrqQ=", + "dev": true, + "requires": { + "arr-union": "^3.1.0", + "get-value": "^2.0.6", + "is-extendable": "^0.1.1", + "set-value": "^0.4.3" + }, + "dependencies": { + "extend-shallow": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extend-shallow/-/extend-shallow-2.0.1.tgz", + "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", + "dev": true, + "requires": { + "is-extendable": "^0.1.0" + } + }, + "set-value": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/set-value/-/set-value-0.4.3.tgz", + "integrity": "sha1-fbCPnT0i3H945Trzw79GZuzfzPE=", + "dev": true, + "requires": { + "extend-shallow": "^2.0.1", + "is-extendable": "^0.1.1", + "is-plain-object": "^2.0.1", + "to-object-path": "^0.3.0" + } + } + } + }, + "unique-filename": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/unique-filename/-/unique-filename-1.1.1.tgz", + "integrity": "sha512-Vmp0jIp2ln35UTXuryvjzkjGdRyf9b2lTXuSYUiPmzRcl3FDtYqAwOnTJkAngD9SWhnoJzDbTKwaOrZ+STtxNQ==", + "dev": true, + "requires": { + "unique-slug": "^2.0.0" + } + }, + "unique-slug": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/unique-slug/-/unique-slug-2.0.1.tgz", + "integrity": "sha512-n9cU6+gITaVu7VGj1Z8feKMmfAjEAQGhwD9fE3zvpRRa0wEIx8ODYkVGfSc94M2OX00tUFV8wH3zYbm1I8mxFg==", + "dev": true, + "requires": { + "imurmurhash": "^0.1.4" + } + }, + "unset-value": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unset-value/-/unset-value-1.0.0.tgz", + "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=", + "dev": true, + "requires": { + "has-value": "^0.3.1", + "isobject": "^3.0.0" + }, + "dependencies": { + "has-value": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/has-value/-/has-value-0.3.1.tgz", + "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=", + "dev": true, + "requires": { + "get-value": "^2.0.3", + "has-values": "^0.1.4", + "isobject": "^2.0.0" + }, + "dependencies": { + "isobject": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-2.1.0.tgz", + "integrity": "sha1-8GVWEJaj8dou9GJy+BXIQNh+DIk=", + "dev": true, + "requires": { + "isarray": "1.0.0" + } + } + } + }, + "has-values": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/has-values/-/has-values-0.1.4.tgz", + "integrity": "sha1-bWHeldkd/Km5oCCJrThL/49it3E=", + "dev": true + } + } + }, + "upath": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/upath/-/upath-1.1.0.tgz", + "integrity": "sha512-bzpH/oBhoS/QI/YtbkqCg6VEiPYjSZtrHQM6/QnJS6OL9pKUFLqb3aFh4Scvwm45+7iAgiMkLhSbaZxUqmrprw==", + "dev": true + }, + "uri-js": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.2.2.tgz", + "integrity": "sha512-KY9Frmirql91X2Qgjry0Wd4Y+YTdrdZheS8TFwvkbLWf/G5KNJDCh6pKL5OZctEW4+0Baa5idK2ZQuELRwPznQ==", + "dev": true, + "requires": { + "punycode": "^2.1.0" + } + }, + "urix": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/urix/-/urix-0.1.0.tgz", + "integrity": "sha1-2pN/emLiH+wf0Y1Js1wpNQZ6bHI=", + "dev": true + }, + "url": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/url/-/url-0.11.0.tgz", + "integrity": "sha1-ODjpfPxgUh63PFJajlW/3Z4uKPE=", + "dev": true, + "requires": { + "punycode": "1.3.2", + "querystring": "0.2.0" + }, + "dependencies": { + "punycode": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", + "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=", + "dev": true + } + } + }, + "use": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz", + "integrity": "sha512-cwESVXlO3url9YWlFW/TA9cshCEhtu7IKJ/p5soJ/gGpj7vbvFrAY/eIioQ6Dw23KjZhYgiIo8HOs1nQ2vr/oQ==", + "dev": true + }, + "util": { + "version": "0.10.3", + "resolved": "http://registry.npmjs.org/util/-/util-0.10.3.tgz", + "integrity": "sha1-evsa/lCAUkZInj23/g7TeTNqwPk=", + "requires": { + "inherits": "2.0.1" + }, + "dependencies": { + "inherits": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "integrity": "sha1-sX0I0ya0Qj5Wjv9xn5GwscvfafE=" + } + } + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", + "dev": true + }, + "util.promisify": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/util.promisify/-/util.promisify-1.0.0.tgz", + "integrity": "sha512-i+6qA2MPhvoKLuxnJNpXAGhg7HphQOSUq2LKMZD0m15EiskXUkMvKdF4Uui0WYeCUGea+o2cw/ZuwehtfsrNkA==", + "dev": true, + "requires": { + "define-properties": "^1.1.2", + "object.getownpropertydescriptors": "^2.0.3" + } + }, + "uuid": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", + "integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==", + "dev": true + }, + "v8-compile-cache": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.0.2.tgz", + "integrity": "sha512-1wFuMUIM16MDJRCrpbpuEPTUGmM5QMUg0cr3KFwra2XgOgFcPGDQHDh3CszSCD2Zewc/dh/pamNEW8CbfDebUw==", + "dev": true + }, + "validate-npm-package-license": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", + "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", + "dev": true, + "requires": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "verror": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", + "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", + "dev": true, + "requires": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } + }, + "vm-browserify": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-0.0.4.tgz", + "integrity": "sha1-XX6kW7755Kb/ZflUOOCofDV9WnM=", + "dev": true, + "requires": { + "indexof": "0.0.1" + } + }, + "vscode-jsonrpc": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-4.0.0.tgz", + "integrity": "sha512-perEnXQdQOJMTDFNv+UF3h1Y0z4iSiaN9jIlb0OqIYgosPCZGYh/MCUlkFtV2668PL69lRDO32hmvL2yiidUYg==" + }, + "vscode-languageserver": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/vscode-languageserver/-/vscode-languageserver-5.2.1.tgz", + "integrity": "sha512-GuayqdKZqAwwaCUjDvMTAVRPJOp/SLON3mJ07eGsx/Iq9HjRymhKWztX41rISqDKhHVVyFM+IywICyZDla6U3A==", + "requires": { + "vscode-languageserver-protocol": "3.14.1", + "vscode-uri": "^1.0.6" + } + }, + "vscode-languageserver-protocol": { + "version": "3.14.1", + "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.14.1.tgz", + "integrity": "sha512-IL66BLb2g20uIKog5Y2dQ0IiigW0XKrvmWiOvc0yXw80z3tMEzEnHjaGAb3ENuU7MnQqgnYJ1Cl2l9RvNgDi4g==", + "requires": { + "vscode-jsonrpc": "^4.0.0", + "vscode-languageserver-types": "3.14.0" + } + }, + "vscode-languageserver-types": { + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.14.0.tgz", + "integrity": "sha512-lTmS6AlAlMHOvPQemVwo3CezxBp0sNB95KNPkqp3Nxd5VFEnuG1ByM0zlRWos0zjO3ZWtkvhal0COgiV1xIA4A==" + }, + "vscode-uri": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/vscode-uri/-/vscode-uri-1.0.6.tgz", + "integrity": "sha512-sLI2L0uGov3wKVb9EB+vIQBl9tVP90nqRvxSoJ35vI3NjxE8jfsE5DSOhWgSunHSZmKS4OCi2jrtfxK7uyp2ww==" + }, + "w3c-hr-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/w3c-hr-time/-/w3c-hr-time-1.0.1.tgz", + "integrity": "sha1-gqwr/2PZUOqeMYmlimViX+3xkEU=", + "dev": true, + "requires": { + "browser-process-hrtime": "^0.1.2" + } + }, + "walker": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.7.tgz", + "integrity": "sha1-L3+bj9ENZ3JisYqITijRlhjgKPs=", + "dev": true, + "requires": { + "makeerror": "1.0.x" + } + }, + "watch": { + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/watch/-/watch-0.18.0.tgz", + "integrity": "sha1-KAlUdsbffJDJYxOJkMClQj60uYY=", + "dev": true, + "requires": { + "exec-sh": "^0.2.0", + "minimist": "^1.2.0" + }, + "dependencies": { + "minimist": { + "version": "1.2.0", + "resolved": "http://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz", + "integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=", + "dev": true + } + } + }, + "watchpack": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-1.6.0.tgz", + "integrity": "sha512-i6dHe3EyLjMmDlU1/bGQpEw25XSjkJULPuAVKCbNRefQVq48yXKUpwg538F7AZTf9kyr57zj++pQFltUa5H7yA==", + "dev": true, + "requires": { + "chokidar": "^2.0.2", + "graceful-fs": "^4.1.2", + "neo-async": "^2.5.0" + } + }, + "webidl-conversions": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-4.0.2.tgz", + "integrity": "sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==", + "dev": true + }, + "webpack": { + "version": "4.29.6", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-4.29.6.tgz", + "integrity": "sha512-MwBwpiE1BQpMDkbnUUaW6K8RFZjljJHArC6tWQJoFm0oQtfoSebtg4Y7/QHnJ/SddtjYLHaKGX64CFjG5rehJw==", + "dev": true, + "requires": { + "@webassemblyjs/ast": "1.8.5", + "@webassemblyjs/helper-module-context": "1.8.5", + "@webassemblyjs/wasm-edit": "1.8.5", + "@webassemblyjs/wasm-parser": "1.8.5", + "acorn": "^6.0.5", + "acorn-dynamic-import": "^4.0.0", + "ajv": "^6.1.0", + "ajv-keywords": "^3.1.0", + "chrome-trace-event": "^1.0.0", + "enhanced-resolve": "^4.1.0", + "eslint-scope": "^4.0.0", + "json-parse-better-errors": "^1.0.2", + "loader-runner": "^2.3.0", + "loader-utils": "^1.1.0", + "memory-fs": "~0.4.1", + "micromatch": "^3.1.8", + "mkdirp": "~0.5.0", + "neo-async": "^2.5.0", + "node-libs-browser": "^2.0.0", + "schema-utils": "^1.0.0", + "tapable": "^1.1.0", + "terser-webpack-plugin": "^1.1.0", + "watchpack": "^1.5.0", + "webpack-sources": "^1.3.0" + }, + "dependencies": { + "acorn": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-6.1.1.tgz", + "integrity": "sha512-jPTiwtOxaHNaAPg/dmrJ/beuzLRnXtB0kQPQ8JpotKJgTB6rX6c8mlf315941pyjBSaPg8NHXS9fhP4u17DpGA==", + "dev": true + } + } + }, + "webpack-cli": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-3.2.3.tgz", + "integrity": "sha512-Ik3SjV6uJtWIAN5jp5ZuBMWEAaP5E4V78XJ2nI+paFPh8v4HPSwo/myN0r29Xc/6ZKnd2IdrAlpSgNOu2CDQ6Q==", + "dev": true, + "requires": { + "chalk": "^2.4.1", + "cross-spawn": "^6.0.5", + "enhanced-resolve": "^4.1.0", + "findup-sync": "^2.0.0", + "global-modules": "^1.0.0", + "import-local": "^2.0.0", + "interpret": "^1.1.0", + "loader-utils": "^1.1.0", + "supports-color": "^5.5.0", + "v8-compile-cache": "^2.0.2", + "yargs": "^12.0.4" + } + }, + "webpack-sources": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-1.3.0.tgz", + "integrity": "sha512-OiVgSrbGu7NEnEvQJJgdSFPl2qWKkWq5lHMhgiToIiN9w34EBnjYzSYs+VbL5KoYiLNtFFa7BZIKxRED3I32pA==", + "dev": true, + "requires": { + "source-list-map": "^2.0.0", + "source-map": "~0.6.1" + }, + "dependencies": { + "source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "dev": true + } + } + }, + "whatwg-encoding": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-1.0.5.tgz", + "integrity": "sha512-b5lim54JOPN9HtzvK9HFXvBma/rnfFeqsic0hSpjtDbVxR3dJKLc+KB4V6GgiGOvl7CY/KNh8rxSo9DKQrnUEw==", + "dev": true, + "requires": { + "iconv-lite": "0.4.24" + } + }, + "whatwg-mimetype": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-2.3.0.tgz", + "integrity": "sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g==", + "dev": true + }, + "whatwg-url": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-6.5.0.tgz", + "integrity": "sha512-rhRZRqx/TLJQWUpQ6bmrt2UV4f0HCQ463yQuONJqC6fO2VoEb1pTYddbe59SkYq87aoM5A3bdhMZiUiVws+fzQ==", + "dev": true, + "requires": { + "lodash.sortby": "^4.7.0", + "tr46": "^1.0.1", + "webidl-conversions": "^4.0.2" + } + }, + "which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "dev": true, + "requires": { + "isexe": "^2.0.0" + } + }, + "which-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.0.tgz", + "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", + "dev": true + }, + "wordwrap": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-0.0.3.tgz", + "integrity": "sha1-o9XabNXAvAAI03I0u68b7WMFkQc=", + "dev": true + }, + "worker-farm": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/worker-farm/-/worker-farm-1.6.0.tgz", + "integrity": "sha512-6w+3tHbM87WnSWnENBUvA2pxJPLhQUg5LKwUQHq3r+XPhIM+Gh2R5ycbwPCyuGbNg+lPgdcnQUhuC02kJCvffQ==", + "dev": true, + "requires": { + "errno": "~0.1.7" + } + }, + "wrap-ansi": { + "version": "2.1.0", + "resolved": "http://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", + "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", + "dev": true, + "requires": { + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1" + }, + "dependencies": { + "is-fullwidth-code-point": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz", + "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", + "dev": true, + "requires": { + "number-is-nan": "^1.0.0" + } + }, + "string-width": { + "version": "1.0.2", + "resolved": "http://registry.npmjs.org/string-width/-/string-width-1.0.2.tgz", + "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", + "dev": true, + "requires": { + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" + } + }, + "strip-ansi": { + "version": "3.0.1", + "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", + "dev": true, + "requires": { + "ansi-regex": "^2.0.0" + } + } + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", + "dev": true + }, + "write-file-atomic": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-2.4.1.tgz", + "integrity": "sha512-TGHFeZEZMnv+gBFRfjAcxL5bPHrsGKtnb4qsFAws7/vlh+QfwAaySIw4AXP9ZskTTh5GWu3FLuJhsWVdiJPGvg==", + "dev": true, + "requires": { + "graceful-fs": "^4.1.11", + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.2" + } + }, + "ws": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-5.2.2.tgz", + "integrity": "sha512-jaHFD6PFv6UgoIVda6qZllptQsMlDEJkTQcybzzXDYM1XO9Y8em691FGMPmM46WGyLU4z9KMgQN+qrux/nhlHA==", + "dev": true, + "requires": { + "async-limiter": "~1.0.0" + } + }, + "xml-name-validator": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-3.0.0.tgz", + "integrity": "sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw==", + "dev": true + }, + "xtend": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", + "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", + "dev": true + }, + "y18n": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", + "integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==", + "dev": true + }, + "yallist": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.0.3.tgz", + "integrity": "sha512-S+Zk8DEWE6oKpV+vI3qWkaK+jSbIK86pCwe2IF/xwIpQ8jEuxpw9NyaGjmp9+BoJv5FV2piqCDcoCtStppiq2A==", + "dev": true + }, + "yargs": { + "version": "12.0.5", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-12.0.5.tgz", + "integrity": "sha512-Lhz8TLaYnxq/2ObqHDql8dX8CJi97oHxrjUcYtzKbbykPtVW9WB+poxI+NM2UIzsMgNCZTIf0AQwsjK5yMAqZw==", + "dev": true, + "requires": { + "cliui": "^4.0.0", + "decamelize": "^1.2.0", + "find-up": "^3.0.0", + "get-caller-file": "^1.0.1", + "os-locale": "^3.0.0", + "require-directory": "^2.1.1", + "require-main-filename": "^1.0.1", + "set-blocking": "^2.0.0", + "string-width": "^2.0.0", + "which-module": "^2.0.0", + "y18n": "^3.2.1 || ^4.0.0", + "yargs-parser": "^11.1.1" + } + }, + "yargs-parser": { + "version": "11.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-11.1.1.tgz", + "integrity": "sha512-C6kB/WJDiaxONLJQnF8ccx9SEeoTTLek8RVbaOIsrAUS8VrBEXfmeSnCZxygc+XC2sNMBIwOOnfcxiynjHsVSQ==", + "dev": true, + "requires": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + } + } + } +} diff --git a/server/package.json b/server/package.json new file mode 100644 index 000000000..384d6c3cf --- /dev/null +++ b/server/package.json @@ -0,0 +1,40 @@ +{ + "name": "pyright", + "displayName": "pyright", + "description": "Linter and type checker for the Python language", + "version": "1.0.0", + "license": "MIT", + "scripts": { + "start": "npm run start:analyzer && npm run start:server", + "start:analyzer": "npm i && npm run build:analyzer", + "start:server": "npm i && npm run build:server", + "build": "npm run build:server && npm run build:analyzer", + "build:analyzer": "npm run tslint && tsc", + "build:server": "npm run installServer && webpack", + "installServer": "node ./customInstallServerIntoExtension.js ../client ./package.json ./tsconfig.json ./package-lock.json", + "watch": "tsc --watch", + "tslint": "tslint --project tsconfig.json --fix", + "test": "jest" + }, + "dependencies": { + "assert": "^1.4.1", + "command-line-args": "^5.0.2", + "typescript-char": "^0.0.0", + "vscode-languageserver": "^5.1.0" + }, + "devDependencies": { + "@types/command-line-args": "^5.0.0", + "@types/jest": "^24.0.9", + "@types/node": "^11.10.5", + "jest": "^24.1.0", + "ts-jest": "^24.0.0", + "tslint": "^5.13.1", + "tslint-microsoft-contrib": "^6.1.0", + "ts-loader": "^5.3.1", + "typescript": "^3.3.3333", + "webpack": "^4.27.1", + "webpack-cli": "^3.0.8" + }, + "types": "out/main.d.ts", + "main": "out/main.js" +} diff --git a/server/src/analyzer/analyzerFileInfo.ts b/server/src/analyzer/analyzerFileInfo.ts new file mode 100644 index 000000000..0713382f5 --- /dev/null +++ b/server/src/analyzer/analyzerFileInfo.ts @@ -0,0 +1,29 @@ +/* +* analyzerFileInfo.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Input type common to multiple analyzer passes. +*/ + +import { ConfigOptions, ExecutionEnvironment } from '../common/configOptions'; +import { TextRangeDiagnosticSink } from '../common/diagnosticSink'; +import { TextRange } from '../common/textRange'; +import { TextRangeCollection } from '../common/textRangeCollection'; +import { ParseResults } from '../parser/parser'; +import { Scope } from './scope'; + +// Maps import paths to the parse tree for the imported module. +export type ImportMap = { [importPath: string]: ParseResults }; + +export interface AnalyzerFileInfo { + importMap: ImportMap; + builtinsScope?: Scope; + diagnosticSink: TextRangeDiagnosticSink; + executionEnvironment: ExecutionEnvironment; + configOptions: ConfigOptions; + lines: TextRangeCollection; + filePath: string; + isStubFile: boolean; + isTypingStubFile: boolean; +} diff --git a/server/src/analyzer/analyzerNodeInfo.ts b/server/src/analyzer/analyzerNodeInfo.ts new file mode 100644 index 000000000..68efe5074 --- /dev/null +++ b/server/src/analyzer/analyzerNodeInfo.ts @@ -0,0 +1,142 @@ +/* +* analyzerNodeInfo.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Defines objects that the analyzer(s) hang off the parse nodes in +* the parse tree. It contains information collected during the +* analysis phases that can be used for later analysis steps or for +* language services (e.g. hover information). +*/ + +import { NameBindings } from '../parser/nameBindings'; +import { ParseNode } from '../parser/parseNodes'; +import { ImportResult } from './importResult'; +import { TypeSourceId } from './inferredType'; +import { Scope } from './scope'; +import { Declaration } from './symbol'; +import { Type } from './types'; + +// An always-incrementing ID for assigning to nodes. +let NextTypeSourceId: TypeSourceId = 1; + +export class AnalyzerNodeInfo { + //--------------------------------------------------------------- + // Set by PostParseWalker + + // Name bindings for nodes that introduce namespaces (modules, + // functions, classes and lambdas). It records the static binding + // type (local, non-local, global) for names used within that scope. + _nameBindings?: NameBindings; + + // Information about an import; used for import nodes only. + _importInfo?: ImportResult; + + //--------------------------------------------------------------- + // Set by SemanticAnalyzer + + // Scope for nodes that introduce scopes: modules, functions, + // classes, and lambdas. A scope is used to store symbol names + // and their associated types and declarations. + _scope?: Scope; + + //--------------------------------------------------------------- + // Set by TypeAnalyzer + + // Cached type information for expression nodes; allows analyzer to + // avoid recomputing types repeatedly. + _expressionType?: Type; + + // Version of cached expressionType. + _expressionTypeVersion?: number; + + // Information to resolve definition and hover requests from + // language service interface; used for NamedNode's. + _declaration?: Declaration; + + // "Type source ID", a number that is unique per node within a + // parse tree. for NameNode's. + _typeSourceId?: TypeSourceId; + + //--------------------------------------------------------------- + + // Cleans out all fields that are added by the anlyzer phases + // (after the post-parse walker). + static cleanNodeAnalysisInfo(node: ParseNode) { + const analyzerNode = node as AnalyzerNodeInfo; + + delete analyzerNode._scope; + // delete analyzerNode._definitionInfo; + delete analyzerNode._expressionType; + delete analyzerNode._expressionTypeVersion; + } + + static getNameBindings(node: ParseNode): NameBindings | undefined { + const analyzerNode = node as AnalyzerNodeInfo; + return analyzerNode._nameBindings; + } + + static setNameBindings(node: ParseNode, nameBindings: NameBindings) { + const analyzerNode = node as AnalyzerNodeInfo; + analyzerNode._nameBindings = nameBindings; + } + + static getScope(node: ParseNode): Scope | undefined { + const analyzerNode = node as AnalyzerNodeInfo; + return analyzerNode._scope; + } + + static setScope(node: ParseNode, scope: Scope) { + const analyzerNode = node as AnalyzerNodeInfo; + analyzerNode._scope = scope; + } + + static getImportInfo(node: ParseNode): ImportResult | undefined { + const analyzerNode = node as AnalyzerNodeInfo; + return analyzerNode._importInfo; + } + + static setImportInfo(node: ParseNode, importInfo: ImportResult) { + const analyzerNode = node as AnalyzerNodeInfo; + analyzerNode._importInfo = importInfo; + } + + static getDeclaration(node: ParseNode): Declaration | undefined { + const analyzerNode = node as AnalyzerNodeInfo; + return analyzerNode._declaration; + } + + static setDeclaration(node: ParseNode, declaration: Declaration) { + const analyzerNode = node as AnalyzerNodeInfo; + analyzerNode._declaration = declaration; + } + + static getExpressionType(node: ParseNode): Type | undefined { + const analyzerNode = node as AnalyzerNodeInfo; + return analyzerNode._expressionType; + } + + static setExpressionType(node: ParseNode, typeAnnotation: Type) { + const analyzerNode = node as AnalyzerNodeInfo; + analyzerNode._expressionType = typeAnnotation; + } + + static getExpressionTypeVersion(node: ParseNode): number | undefined { + const analyzerNode = node as AnalyzerNodeInfo; + return analyzerNode._expressionTypeVersion; + } + + static setExpressionTypeVersion(node: ParseNode, version: number) { + const analyzerNode = node as AnalyzerNodeInfo; + analyzerNode._expressionTypeVersion = version; + } + + static getTypeSourceId(node: ParseNode): TypeSourceId { + const analyzerNode = node as AnalyzerNodeInfo; + if (analyzerNode._typeSourceId === undefined) { + analyzerNode._typeSourceId = NextTypeSourceId++; + } + + return analyzerNode._typeSourceId; + } +} diff --git a/server/src/analyzer/definitionProvider.ts b/server/src/analyzer/definitionProvider.ts new file mode 100644 index 000000000..0bd55e27e --- /dev/null +++ b/server/src/analyzer/definitionProvider.ts @@ -0,0 +1,81 @@ +/* +* definitionProvider.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Logic that maps a position within a Python program file into +* a "definition" of the item that is referred to at that position. +* For example, if the location is within an import name, the +* definition is the top of the resolved import file. +*/ + +import { DiagnosticTextPosition, DiagnosticTextRange, DocumentTextRange } from '../common/diagnostic'; +import { isFile } from '../common/pathUtils'; +import { convertPositionToOffset } from '../common/positionUtils'; +import { ModuleNameNode } from '../parser/parseNodes'; +import { ParseResults } from '../parser/parser'; +import { AnalyzerNodeInfo } from './analyzerNodeInfo'; +import { ParseTreeUtils } from './parseTreeUtils'; + +const _startOfFilePosition: DiagnosticTextPosition = { line: 0, column: 0 }; +const _startOfFileRange: DiagnosticTextRange = { start: _startOfFilePosition, end: _startOfFilePosition }; + +export class DefinitionProvider { + static getDefinitionForPosition(parseResults: ParseResults, + position: DiagnosticTextPosition): DocumentTextRange | undefined { + + let offset = convertPositionToOffset(position, parseResults.lines); + if (offset === undefined) { + return undefined; + } + + let node = ParseTreeUtils.findNodeByOffset(parseResults.parseTree, offset); + if (node === undefined) { + return undefined; + } + + if (node instanceof ModuleNameNode) { + // If this is an imported module name, try to map the position + // to the resolved import path. + let importInfo = AnalyzerNodeInfo.getImportInfo(node); + if (!importInfo) { + return undefined; + } + + let pathOffset = node.nameParts.findIndex(range => { + return offset! >= range.start && offset! < range.end; + }); + + if (pathOffset < 0) { + return undefined; + } + + // Handle imports that were resolved partially. + if (pathOffset >= importInfo.resolvedPaths.length) { + return undefined; + } + + // If it's a directory, don't return it. The caller expects + // the path to point to files only. + const path = importInfo.resolvedPaths[pathOffset]; + if (!isFile(path)) { + return undefined; + } + + return { + path, + range: _startOfFileRange + }; + } + + let declaration = AnalyzerNodeInfo.getDeclaration(node); + if (declaration) { + return { + path: declaration.path, + range: declaration.range + }; + } + + return undefined; + } +} diff --git a/server/src/analyzer/expressionUtils.ts b/server/src/analyzer/expressionUtils.ts new file mode 100644 index 000000000..0ba9fbfab --- /dev/null +++ b/server/src/analyzer/expressionUtils.ts @@ -0,0 +1,123 @@ +/* +* expressionUtils.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Collection of static methods that operate on expressions +* (parse node trees). +*/ + +import { ExecutionEnvironment } from '../common/configOptions'; +import { BinaryExpressionNode, ExpressionNode, IndexExpressionNode, MemberAccessExpressionNode, + NameNode, NumberNode, StringNode, TupleExpressionNode } from '../parser/parseNodes'; +import { OperatorType } from '../parser/tokenizerTypes'; + +export class ExpressionUtils { + // Returns undefined if the expression cannot be evaluated + // statically or a value if it can. + static evaluateConstantExpression(node: ExpressionNode, execEnv: ExecutionEnvironment): any | undefined { + if (node instanceof BinaryExpressionNode) { + if (this._isSysVersionInfoExpression(node.leftExpression) && + node.rightExpression instanceof TupleExpressionNode) { + + // Handle the special case of "sys.version_info >= (3, x)" + let comparisonVersion = this._convertTupleToVersion(node.rightExpression); + return this._evaluateNumericBinaryOperation(node.operator, execEnv.pythonVersion, comparisonVersion); + + } else if (node.leftExpression instanceof IndexExpressionNode && + this._isSysVersionInfoExpression(node.leftExpression.baseExpression) && + node.leftExpression.indexExpression instanceof NumberNode && + node.leftExpression.indexExpression.token.value === 0 && + node.rightExpression instanceof NumberNode) { + + // Handle the special case of "sys.version_info[0] >= X" + return this._evaluateNumericBinaryOperation(node.operator, execEnv.pythonVersion / 256, + node.rightExpression.token.value); + } else if (this._isSysPlatformInfoExpression(node.leftExpression) && + node.rightExpression instanceof StringNode) { + // Handle the special case of "sys.platform != 'X'" + let comparisonPlatform = node.rightExpression.getValue(); + if (execEnv.pythonPlatform !== undefined) { + return this._evaluateStringBinaryOperation(node.operator, execEnv.pythonPlatform, comparisonPlatform); + } + } + } + + return undefined; + } + + private static _convertTupleToVersion(node: TupleExpressionNode): number | undefined { + let comparisonVersion: number | undefined; + if (node.expressions.length === 2) { + if (node.expressions[0] instanceof NumberNode && + node.expressions[1] instanceof NumberNode) { + const majorVersion = node.expressions[0] as NumberNode; + const minorVersion = node.expressions[1] as NumberNode; + comparisonVersion = majorVersion.token.value * 256 + minorVersion.token.value; + } + } else if (node.expressions.length === 1) { + const majorVersion = node.expressions[0] as NumberNode; + comparisonVersion = majorVersion.token.value * 256; + } + + return comparisonVersion; + } + + private static _evaluateNumericBinaryOperation(operatorType: OperatorType, leftValue: number | undefined, + rightValue: number | undefined): any | undefined { + if (leftValue !== undefined && rightValue !== undefined) { + if (operatorType === OperatorType.LessThan) { + return leftValue < rightValue; + } else if (operatorType === OperatorType.LessThanOrEqual) { + return leftValue <= rightValue; + } else if (operatorType === OperatorType.GreaterThan) { + return leftValue > rightValue; + } else if (operatorType === OperatorType.GreaterThanOrEqual) { + return leftValue >= rightValue; + } else if (operatorType === OperatorType.Equals) { + return leftValue === rightValue; + } else if (operatorType === OperatorType.NotEquals) { + return leftValue !== rightValue; + } + } + + return undefined; + } + + private static _evaluateStringBinaryOperation(operatorType: OperatorType, + leftValue: string | undefined, rightValue: string | undefined): any | undefined { + if (leftValue !== undefined && rightValue !== undefined) { + if (operatorType === OperatorType.Equals) { + return leftValue === rightValue; + } else if (operatorType === OperatorType.NotEquals) { + return leftValue !== rightValue; + } + } + + return undefined; + } + + private static _isSysVersionInfoExpression(node: ExpressionNode): boolean { + if (node instanceof MemberAccessExpressionNode) { + if (node.leftExpression instanceof NameNode && + node.leftExpression.nameToken.value === 'sys' && + node.memberName.nameToken.value === 'version_info') { + return true; + } + } + + return false; + } + + private static _isSysPlatformInfoExpression(node: ExpressionNode): boolean { + if (node instanceof MemberAccessExpressionNode) { + if (node.leftExpression instanceof NameNode && + node.leftExpression.nameToken.value === 'sys' && + node.memberName.nameToken.value === 'platform') { + return true; + } + } + + return false; + } +} diff --git a/server/src/analyzer/hoverProvider.ts b/server/src/analyzer/hoverProvider.ts new file mode 100644 index 000000000..d54c0e8d0 --- /dev/null +++ b/server/src/analyzer/hoverProvider.ts @@ -0,0 +1,125 @@ +/* +* hoverProvider.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Logic that maps a position within a Python program file into +* markdown text that is displayed when the user hovers over that +* position within a smart editor. +*/ + +import { DiagnosticTextPosition } from '../common/diagnostic'; +import { convertPositionToOffset } from '../common/positionUtils'; +import { ModuleNameNode, NameNode, ParseNode } from '../parser/parseNodes'; +import { ParseResults } from '../parser/parser'; +import { AnalyzerNodeInfo } from './analyzerNodeInfo'; +import { ParseTreeUtils } from './parseTreeUtils'; +import { SymbolCategory } from './symbol'; + +export class HoverProvider { + static getHoverForPosition(parseResults: ParseResults, + position: DiagnosticTextPosition): string | undefined { + + let offset = convertPositionToOffset(position, parseResults.lines); + if (offset === undefined) { + return undefined; + } + + let node = ParseTreeUtils.findNodeByOffset(parseResults.parseTree, offset); + if (node === undefined) { + return undefined; + } + + if (node instanceof ModuleNameNode) { + // If this is an imported module name, try to map the position + // to the resolved import path. + let importInfo = AnalyzerNodeInfo.getImportInfo(node); + if (!importInfo) { + return undefined; + } + + let pathOffset = node.nameParts.findIndex(range => { + return offset! >= range.start && offset! < range.end; + }); + + if (pathOffset < 0) { + return undefined; + } + + if (pathOffset >= importInfo.resolvedPaths.length) { + pathOffset = importInfo.resolvedPaths.length - 1; + } + + if (importInfo.resolvedPaths[pathOffset]) { + return '```\n(module) "' + importInfo.resolvedPaths[pathOffset] + '"\n```'; + } + + return undefined; + } + + let declaration = AnalyzerNodeInfo.getDeclaration(node); + + if (declaration) { + switch (declaration.category) { + case SymbolCategory.Variable: + case SymbolCategory.Import: { + if (node instanceof NameNode) { + return '```\n(variable) ' + node.nameToken.value + + this._getTypeText(node) + '\n```'; + } + break; + } + + case SymbolCategory.Parameter: { + if (node instanceof NameNode) { + return '```\n(parameter) ' + node.nameToken.value + + this._getTypeText(node) + '\n```'; + } + break; + } + + case SymbolCategory.Class: { + if (node instanceof NameNode) { + return '```\n(class) ' + node.nameToken.value + '\n```'; + } + break; + } + + case SymbolCategory.Function: { + if (node instanceof NameNode) { + return '```\n(function) ' + node.nameToken.value + + this._getTypeText(node) + '\n```'; + } + break; + } + + case SymbolCategory.Method: { + if (node instanceof NameNode) { + return '```\n(method) ' + node.nameToken.value + + this._getTypeText(node) + '\n```'; + } + break; + } + + case SymbolCategory.Module: { + if (node instanceof NameNode) { + return '```\n(module) ' + node.nameToken.value + '\n```'; + } + break; + } + } + } + + return undefined; + } + + private static _getTypeText(node: ParseNode): string { + let type = AnalyzerNodeInfo.getExpressionType(node); + let typeString = ''; + if (type) { + typeString = type.asString(); + } + + return ': ' + typeString; + } +} diff --git a/server/src/analyzer/importResolver.ts b/server/src/analyzer/importResolver.ts new file mode 100644 index 000000000..083caf7e8 --- /dev/null +++ b/server/src/analyzer/importResolver.ts @@ -0,0 +1,378 @@ +/* +* importResolver.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Provides the logic for resolving imports according to the +* runtime rules of Python. +*/ + +import * as fs from 'fs'; + +import { ConfigOptions, ExecutionEnvironment } from '../common/configOptions'; +import { combinePaths, getDirectoryPath, getFileSystemEntries, isDirectory, + isFile, stripFileExtension, stripTrailingDirectorySeparator } from '../common/pathUtils'; +import { is3x, versionToString } from '../common/pythonVersion'; +import { ImplicitImport, ImportResult, ImportType } from './importResult'; + +export interface ImportedModuleName { + leadingDots: number; + nameParts: string[]; +} + +export class ImportResolver { + private _sourceFilePath: string; + private _configOptions: ConfigOptions; + private _executionEnvironment: ExecutionEnvironment; + private _cachedSitePackagePath: string | undefined; + + constructor(sourceFilePath: string, configOptions: ConfigOptions, execEnv: ExecutionEnvironment) { + this._sourceFilePath = sourceFilePath; + this._configOptions = configOptions; + this._executionEnvironment = execEnv; + } + + // Resolves the import and returns the path if it exists, otherwise + // returns undefined. + resolveImport(moduleName: ImportedModuleName): ImportResult { + let importName = this._formatImportName(moduleName); + + // Find the site packages for the configured virtual environment. + if (this._cachedSitePackagePath === undefined) { + this._cachedSitePackagePath = this._findSitePackagePath(); + } + + // Is it a built-in path? + if (moduleName.leadingDots === 0 && moduleName.nameParts.length > 0) { + // First check for a typeshed file. + let builtInImport = this._findTypeshedPath(moduleName, importName, true); + if (builtInImport) { + builtInImport.isTypeshedFile = true; + return builtInImport; + } + } + + // Is it a relative import? + if (moduleName.leadingDots > 0) { + let relativeImport = this._resolveRelativeImport(moduleName, importName); + if (relativeImport) { + return relativeImport; + } + } else { + let bestResultSoFar: ImportResult | undefined; + + // Look for it in the root directory of the execution environment. + let localImport = this._resolveAbsoluteImport( + this._executionEnvironment.root, moduleName, importName); + if (localImport && localImport.importFound) { + return localImport; + } + bestResultSoFar = localImport; + + for (let i = 0; i < this._executionEnvironment.extraPaths.length; i++) { + let extraPath = this._executionEnvironment.extraPaths[i]; + localImport = this._resolveAbsoluteImport(extraPath, moduleName, importName); + if (localImport && localImport.importFound) { + return localImport; + } + + if (localImport && (bestResultSoFar === undefined || + localImport.resolvedPaths.length > bestResultSoFar.resolvedPaths.length)) { + bestResultSoFar = localImport; + } + } + + // Check for a typings file. + if (this._configOptions.typingsPath) { + let typingsImport = this._resolveAbsoluteImport( + this._configOptions.typingsPath, moduleName, importName); + if (typingsImport && typingsImport.importFound) { + return typingsImport; + } + } + + // Check for a typeshed file. + let typeshedImport = this._findTypeshedPath(moduleName, importName, false); + if (typeshedImport) { + typeshedImport.isTypeshedFile = true; + return typeshedImport; + } + + // Look for the import in the list of third-party packages. + if (this._cachedSitePackagePath) { + // Allow partial resolution because some third-party packages + // use tricks to populate their package namespaces. + let thirdPartyImport = this._resolveAbsoluteImport( + this._cachedSitePackagePath, moduleName, importName, true); + if (thirdPartyImport) { + thirdPartyImport.importType = ImportType.ThirdParty; + return thirdPartyImport; + } + } + + // We weren't able to find an exact match, so return the best + // partial match. + if (bestResultSoFar) { + return bestResultSoFar; + } + } + + return { + importName, + importFound: false, + resolvedPaths: [], + importType: ImportType.Local, + isNamespacePackage: false, + isStubFile: false, + implicitImports: [] + }; + } + + private _findTypeshedPath(moduleName: ImportedModuleName, importName: string, + isStdLib: boolean): ImportResult | undefined { + + let typeshedPath = ''; + + // Did the user specify a typeshed path? If not, we'll look in the + // default virtual environment, then in the typeshed-fallback directory. + if (this._configOptions.typeshedPath) { + typeshedPath = this._configOptions.typeshedPath; + } else if (this._cachedSitePackagePath) { + typeshedPath = combinePaths(this._cachedSitePackagePath, 'typeshed'); + } else { + // Assume that the 'typeshed-fallback' directory is up one level + // from this javascript file. + const moduleDirectory = (global as any).__basedir; + if (moduleDirectory) { + typeshedPath = combinePaths(getDirectoryPath(moduleDirectory), 'typeshed-fallback'); + } + } + + typeshedPath = combinePaths(typeshedPath, isStdLib ? 'stdlib' : 'third_party'); + + if (!fs.existsSync(typeshedPath) || !isDirectory(typeshedPath)) { + return undefined; + } + + // We currently support only 3.x. + let pythonVersion = this._executionEnvironment.pythonVersion; + if (!is3x(pythonVersion)) { + return undefined; + } + + let minorVersion = pythonVersion & 0xFF; + + // Search for module starting at "3.x" down to "3.1", then "3", then "2and3". + while (true) { + let pythonVersionString = minorVersion > 0 ? versionToString(0x300 + minorVersion) : + minorVersion === 0 ? '3' : '2and3'; + let testPath = combinePaths(typeshedPath, pythonVersionString); + if (fs.existsSync(testPath)) { + let importInfo = this._resolveAbsoluteImport(testPath, moduleName, importName); + if (importInfo && importInfo.importFound) { + if (isStdLib) { + importInfo.importType = ImportType.BuiltIn; + } + return importInfo; + } + } + + // We use -1 to indicate "2and3", which is searched after "3.0". + if (minorVersion === -1) { + break; + } + minorVersion--; + } + + return undefined; + } + + private _resolveRelativeImport(moduleName: ImportedModuleName, importName: string): ImportResult | undefined { + // Determine which search path this file is part of. + let curDir = getDirectoryPath(this._sourceFilePath); + for (let i = 1; i < moduleName.leadingDots; i++) { + // Make sure we don't walk out of the root directory. + if (!curDir.startsWith(this._executionEnvironment.root)) { + return undefined; + } + + curDir = getDirectoryPath(curDir); + } + + // Now try to match the module parts from the current directory location. + return this._resolveAbsoluteImport(curDir, moduleName, importName); + } + + // Follows import resolution algorithm defined in PEP-420: + // https://www.python.org/dev/peps/pep-0420/ + private _resolveAbsoluteImport(rootPath: string, moduleName: ImportedModuleName, + importName: string, allowPartial = false): ImportResult | undefined { + + // Starting at the specified path, walk the file system to find the + // specified module. + let resolvedPaths: string[] = []; + let dirPath = rootPath; + let isNamespacePackage = false; + let isStubFile = false; + let implicitImports: ImplicitImport[] = []; + + for (let i = 0; i < moduleName.nameParts.length; i++) { + dirPath = combinePaths(dirPath, moduleName.nameParts[i]); + if (!fs.existsSync(dirPath) || !isDirectory(dirPath)) { + // We weren't able to find the subdirectory. See if we can + // find a ".py" or ".pyi" file with this name. + let pyFilePath = stripTrailingDirectorySeparator(dirPath) + '.py'; + let pyiFilePath = pyFilePath + 'i'; + if (fs.existsSync(pyiFilePath) && isFile(pyiFilePath)) { + resolvedPaths.push(pyiFilePath); + isStubFile = true; + } else if (fs.existsSync(pyFilePath) && isFile(pyFilePath)) { + resolvedPaths.push(pyFilePath); + } + break; + } + + let pyFilePath = combinePaths(dirPath, '__init__.py'); + let pyiFilePath = pyFilePath + 'i'; + if (fs.existsSync(pyiFilePath) && isFile(pyiFilePath)) { + resolvedPaths.push(pyiFilePath); + isStubFile = true; + } else if (fs.existsSync(pyFilePath) && isFile(pyFilePath)) { + resolvedPaths.push(pyFilePath); + } else { + resolvedPaths.push(dirPath); + if (i === moduleName.nameParts.length - 1) { + isNamespacePackage = true; + } + } + + if (i === moduleName.nameParts.length - 1) { + implicitImports = this._findImplicitImports( + dirPath, [pyFilePath, pyiFilePath]); + } + } + + let importFound: boolean; + if (allowPartial) { + importFound = resolvedPaths.length > 0; + } else { + importFound = resolvedPaths.length === moduleName.nameParts.length; + + // Empty namespace packages are not allowed. + if (isNamespacePackage && implicitImports.length === 0) { + importFound = false; + } + } + + return { + importName, + importFound, + importType: ImportType.Local, + resolvedPaths, + searchPath: rootPath, + isNamespacePackage, + isStubFile, + implicitImports + }; + } + + private _findImplicitImports(dirPath: string, exclusions: string[]): ImplicitImport[] { + let implicitImportMap: { [name: string]: ImplicitImport } = {}; + + let entries = getFileSystemEntries(dirPath); + for (let fileName of entries.files) { + if (fileName.endsWith('.py') || fileName.endsWith('.pyi')) { + let filePath = combinePaths(dirPath, fileName); + + if (!exclusions.find(exclusion => exclusion === filePath)) { + let implicitImport: ImplicitImport = { + isStubFile: fileName.endsWith('.pyi'), + name: stripFileExtension(fileName), + path: filePath + }; + + // Always prefer stub files over non-stub files. + if (!implicitImportMap[implicitImport.name] || + !implicitImportMap[implicitImport.name].isStubFile) { + implicitImportMap[implicitImport.name] = implicitImport; + } + } + } + } + + for (let dirName of entries.directories) { + let pyFilePath = combinePaths(dirPath, dirName, '__init__.py'); + let pyiFilePath = pyFilePath + 'i'; + let isStubFile = false; + let path = ''; + + if (fs.existsSync(pyiFilePath) && isFile(pyiFilePath)) { + isStubFile = true; + path = pyiFilePath; + } else if (fs.existsSync(pyFilePath) && isFile(pyFilePath)) { + path = pyFilePath; + } + + if (path) { + let implicitImport: ImplicitImport = { + isStubFile, + name: dirName, + path + }; + + implicitImportMap[implicitImport.name] = implicitImport; + } + } + + return Object.keys(implicitImportMap).map(key => implicitImportMap[key]); + } + + private _findSitePackagePath(): string | undefined { + let pythonPath: string | undefined; + if (this._executionEnvironment.venv) { + if (this._configOptions.venvPath) { + pythonPath = combinePaths(this._configOptions.venvPath, this._executionEnvironment.venv); + } + } else if (this._configOptions.defaultVenv) { + if (this._configOptions.venvPath) { + pythonPath = combinePaths(this._configOptions.venvPath, this._configOptions.defaultVenv); + } + } else { + pythonPath = this._configOptions.pythonPath; + } + + if (!pythonPath) { + return undefined; + } + + let libPath = combinePaths(pythonPath, 'lib'); + let sitePackagesPath = combinePaths(libPath, 'site-packages'); + if (fs.existsSync(sitePackagesPath)) { + return sitePackagesPath; + } + + // We didn't find a site-packages directory directly in the lib + // directory. Scan for a "python*" directory instead. + let entries = getFileSystemEntries(libPath); + for (let i = 0; i < entries.directories.length; i++) { + let dirName = entries.directories[i]; + if (dirName.startsWith('python')) { + let dirPath = combinePaths(libPath, dirName, 'site-packages'); + if (fs.existsSync(dirPath)) { + return dirPath; + } + } + } + + return undefined; + } + + private _formatImportName(moduleName: ImportedModuleName) { + let name = ''; + for (let i = 0; i < moduleName.leadingDots; i++) { + name += '.'; + } + + return name + moduleName.nameParts.map(iden => iden).join('.'); + } +} diff --git a/server/src/analyzer/importResult.ts b/server/src/analyzer/importResult.ts new file mode 100644 index 000000000..be43f970f --- /dev/null +++ b/server/src/analyzer/importResult.ts @@ -0,0 +1,54 @@ +/* +* importResult.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Interface that describes the output of the import resolver. +*/ + +export enum ImportType { + BuiltIn, + Local, + ThirdParty +} + +export interface ImplicitImport { + isStubFile: boolean; + name: string; + path: string; +} + +export interface ImportResult { + // The formatted import name. Useful for error messages. + importName: string; + + // True if import was resolved to a module or file. + importFound: boolean; + + // Type of import (built-in, local, third-party). + importType: ImportType; + + // The resolved absolute paths for each of the elements in the module name. + resolvedPaths: string[]; + + // Indicates whether the import is a traditional package (with an + // __init__.py in it) or a "namespace" package (defined by PEP-420). + isNamespacePackage: boolean; + + // For absolute imports, the search path that was used to resolve + // (or partially resolve) the module. + searchPath?: string; + + // True if resolved file is a type hint (.pyi) file rather than + // a python (.py) file. + isStubFile: boolean; + + // True if the resolved file is a type hint (.pyi) file that comes + // from typeshed. + isTypeshedFile?: boolean; + + // List of files within the final resolved path that are implicitly + // imported as part of the package — used for both traditional and + // namespace packages. + implicitImports: ImplicitImport[]; +} diff --git a/server/src/analyzer/inferredType.ts b/server/src/analyzer/inferredType.ts new file mode 100644 index 000000000..851f43877 --- /dev/null +++ b/server/src/analyzer/inferredType.ts @@ -0,0 +1,88 @@ +/* +* inferredType.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Object that stores multiple types that combine to create +* a single inferred type. Each of the types come from +* different parse nodes, and they can be updated as type +* analysis proceeds. +*/ + +import { Type, UnknownType } from './types'; +import { TypeUtils } from './typeUtils'; + +// A type can be inferred from multiple sources. Each sources +// has a type and a unique ID, which remains constant through +// multiple passes of type analysis. As new type information +// becomes known, sources can be updated (e.g. from "unknown" +// to a known type). +export interface InferredTypeSource { + type: Type; + sourceId: TypeSourceId; +} + +export type TypeSourceId = number; +export const DefaultTypeSourceId: TypeSourceId = 0; + +export class InferredType { + private _sources: InferredTypeSource[] = []; + private _combinedType: Type = UnknownType.create(); + + getType() { + return this._combinedType; + } + + getPrimarySourceId() { + if (this._sources.length > 0) { + return this._sources[0].sourceId; + } + + return DefaultTypeSourceId; + } + + // Adds a new source (or replaces an existing source) for the + // inferred type. Returns true if the combined type changed. + addSource(type: Type, sourceId: TypeSourceId): boolean { + // Is this source already known? + const sourceIndex = this._sources.findIndex(src => src.sourceId === sourceId); + if (sourceIndex >= 0) { + if (this._sources[sourceIndex].type.isSame(type)) { + return false; + } + + this._sources[sourceIndex] = { sourceId, type }; + } else { + this._sources.push({ sourceId, type }); + } + + // Recompute the combined type. + let newCombinedType: Type | undefined; + for (let source of this._sources) { + if (!newCombinedType) { + newCombinedType = source.type; + } else { + newCombinedType = TypeUtils.combineTypes(newCombinedType, source.type); + } + } + + if (!newCombinedType!.isSame(this._combinedType)) { + this._combinedType = newCombinedType!; + return true; + } + + return false; + } + + addSources(inferredType: InferredType): boolean { + let madeChange = false; + + for (let source of inferredType._sources) { + if (this.addSource(source.type, source.sourceId)) { + madeChange = true; + } + } + + return madeChange; + } +} diff --git a/server/src/analyzer/parseTreeCleaner.ts b/server/src/analyzer/parseTreeCleaner.ts new file mode 100644 index 000000000..4db1f4042 --- /dev/null +++ b/server/src/analyzer/parseTreeCleaner.ts @@ -0,0 +1,34 @@ +/* +* parseTreeCleaner.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* A parse tree walker that's used to clean any analysis +* information hanging off the parse tree. It's used when +* dependent files have been modified and the file requires +* reanalysis. Without this, we'd need to generate a fresh +* parse tree from scratch. +*/ + +import { ModuleNode, ParseNode } from '../parser/parseNodes'; +import { AnalyzerNodeInfo } from './analyzerNodeInfo'; +import { ParseTreeWalker } from './parseTreeWalker'; + +export class ParseTreeCleanerWalker extends ParseTreeWalker { + private _parseTree: ModuleNode; + + constructor(parseTree: ModuleNode) { + super(); + + this._parseTree = parseTree; + } + + clean() { + this.walk(this._parseTree); + } + + visitNode(node: ParseNode): boolean { + AnalyzerNodeInfo.cleanNodeAnalysisInfo(node); + return true; + } +} diff --git a/server/src/analyzer/parseTreeUtils.ts b/server/src/analyzer/parseTreeUtils.ts new file mode 100644 index 000000000..e9fa0567f --- /dev/null +++ b/server/src/analyzer/parseTreeUtils.ts @@ -0,0 +1,106 @@ +/* +* parseTreeUtils.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Utility routines for traversing a parse tree. +*/ + +import { DiagnosticTextPosition } from '../common/diagnostic'; +import { convertPositionToOffset } from '../common/positionUtils'; +import { TextRange } from '../common/textRange'; +import { TextRangeCollection } from '../common/textRangeCollection'; +import { CallExpressionNode, ClassNode, ExpressionNode, + FunctionNode, IndexExpressionNode, MemberAccessExpressionNode, ModuleNode, NameNode, ParseNode } from '../parser/parseNodes'; + +export class ParseTreeUtils { + // Returns the deepest node that contains the specified position. + static findNodeByPosition(node: ParseNode, position: DiagnosticTextPosition, + lines: TextRangeCollection): ParseNode | undefined { + + let offset = convertPositionToOffset(position, lines); + if (offset === undefined) { + return undefined; + } + + return ParseTreeUtils.findNodeByOffset(node, offset); + } + + // Returns the deepest node that contains the specified offset. + static findNodeByOffset(node: ParseNode, offset: number): ParseNode | undefined { + if (offset < node.start || offset >= node.end) { + return undefined; + } + + // The range is found within this node. See if we can localize it + // further by checking its children. + let children = node.getChildrenFlattened(); + for (let child of children) { + let containingChild = ParseTreeUtils.findNodeByOffset(child, offset); + if (containingChild) { + return containingChild; + } + } + + return node; + } + + static printExpression(node: ExpressionNode): string { + if (node instanceof NameNode) { + return node.nameToken.value; + } else if (node instanceof MemberAccessExpressionNode) { + return ParseTreeUtils.printExpression(node.leftExpression) + '.' + + node.memberName.nameToken.value; + } else if (node instanceof CallExpressionNode) { + return ParseTreeUtils.printExpression(node.leftExpression) + '(' + + node.arguments.map(arg => this.printExpression(arg.valueExpression)).join(', ') + + ')'; + } else if (node instanceof IndexExpressionNode) { + return ParseTreeUtils.printExpression(node.baseExpression) + '[' + + this.printExpression(node.indexExpression) + ']'; + } + + // TODO - need to finish + return ''; + } + + static getEnclosingClass(node: ParseNode): ClassNode | undefined { + let curNode = node.parent; + while (curNode) { + if (curNode instanceof ClassNode) { + return curNode; + } + + curNode = curNode.parent; + } + + return undefined; + } + + static isFunctionInClass(functionNode: FunctionNode): boolean { + let curNode = functionNode.parent; + while (curNode) { + if (curNode instanceof ClassNode) { + return true; + } + + if (curNode instanceof FunctionNode || curNode instanceof ModuleNode) { + return false; + } + + curNode = curNode.parent; + } + + return false; + } + + static functionHasDecorator(node: FunctionNode, decoratorName: string): boolean { + let targetDecorator = node.decorators.find(decorator => { + return decorator.callName instanceof NameNode && + decorator.callName.nameToken.value === decoratorName && + decorator.arguments.length === 0; + }); + + return targetDecorator !== undefined; + } +} diff --git a/server/src/analyzer/parseTreeWalker.ts b/server/src/analyzer/parseTreeWalker.ts new file mode 100644 index 000000000..e3db26ffa --- /dev/null +++ b/server/src/analyzer/parseTreeWalker.ts @@ -0,0 +1,466 @@ +/* +* parseTreeWalker.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Class that traverses a parse tree. +*/ + +import * as assert from 'assert'; + +import { ArgumentNode, AssertNode, AssignmentNode, AugmentedAssignemtnExpressionNode, + AwaitExpressionNode, BinaryExpressionNode, BreakNode, CallExpressionNode, ClassNode, + ConditionalExpressionNode, ConstantNode, ContinueNode, DecoratorNode, DelNode, + DictionaryExpandEntryNode, DictionaryKeyEntryNode, DictionaryNode, EllipsisNode, + ExceptNode, ForNode, FunctionNode, GlobalNode, IfNode, ImportAsNode, + ImportFromAsNode, ImportFromNode, ImportNode, IndexExpressionNode, LambdaNode, + ListComprehensionForNode, ListComprehensionIfNode, ListComprehensionNode, ListNode, + MemberAccessExpressionNode, ModuleNameNode, ModuleNode, NameNode, NonlocalNode, NumberNode, + ParameterNode, ParseNode, ParseNodeType, PassNode, RaiseNode, ReturnNode, + SetNode, SliceExpressionNode, StarExpressionNode, StatementListNode, StringNode, + SuiteNode, TryNode, TupleExpressionNode, TypeAnnotationExpressionNode, + UnaryExpressionNode, WhileNode, WithItemNode, WithNode, + YieldExpressionNode, YieldFromExpressionNode } from '../parser/parseNodes'; + +// To use this class, create a subclass and override the +// visitXXX methods that you want to handle. +export class ParseTreeWalker { + walk(node: ParseNode): void { + if (this.visitNode(node)) { + this.walkChildren(node); + } + } + + walkMultiple(nodes: ParseNode[]) { + nodes.forEach(node => { + this.walk(node); + }); + } + + walkChildren(node: ParseNode) { + this.walkMultiple(this.getChildren(node)); + } + + getChildren(node: ParseNode): ParseNode[] { + return node.getChildrenFlattened(); + } + + visitNode(node: ParseNode): boolean { + switch (node.nodeType) { + case ParseNodeType.Argument: + return this.visitArgument(node as ArgumentNode); + + case ParseNodeType.Assert: + return this.visitAssert(node as AssertNode); + + case ParseNodeType.Assignment: + return this.visitAssignment(node as AssignmentNode); + + case ParseNodeType.AugmentedAssignment: + return this.visitAgumentedAssignment(node as AugmentedAssignemtnExpressionNode); + + case ParseNodeType.Await: + return this.visitAwait(node as AwaitExpressionNode); + + case ParseNodeType.BinaryOperation: + return this.visitBinaryOperation(node as BinaryExpressionNode); + + case ParseNodeType.Break: + return this.visitBreak(node as BreakNode); + + case ParseNodeType.Call: + return this.visitCall(node as CallExpressionNode); + + case ParseNodeType.Class: + return this.visitClass(node as ClassNode); + + case ParseNodeType.Conditional: + return this.visitConditional(node as ConditionalExpressionNode); + + case ParseNodeType.Constant: + return this.visitConstant(node as ConstantNode); + + case ParseNodeType.Continue: + return this.visitContinue(node as ContinueNode); + + case ParseNodeType.Decorator: + return this.visitDecorator(node as DecoratorNode); + + case ParseNodeType.Del: + return this.visitDel(node as DelNode); + + case ParseNodeType.Dictionary: + return this.visitDictionary(node as DictionaryNode); + + case ParseNodeType.DictionaryKeyEntry: + return this.visitDictionaryKeyEntry(node as DictionaryKeyEntryNode); + + case ParseNodeType.DictionaryExpandEntry: + return this.visitDictionarExpandEntry(node as DictionaryExpandEntryNode); + + case ParseNodeType.If: + return this.visitIf(node as IfNode); + + case ParseNodeType.Import: + return this.visitImport(node as ImportNode); + + case ParseNodeType.ImportAs: + return this.visitImportAs(node as ImportAsNode); + + case ParseNodeType.ImportFrom: + return this.visitImportFrom(node as ImportFromNode); + + case ParseNodeType.ImportFromAs: + return this.visitImportFromAs(node as ImportFromAsNode); + + case ParseNodeType.Index: + return this.visitIndex(node as IndexExpressionNode); + + case ParseNodeType.Ellipsis: + return this.visitEllipsis(node as EllipsisNode); + + case ParseNodeType.Except: + return this.visitExcept(node as ExceptNode); + + case ParseNodeType.For: + return this.visitFor(node as ForNode); + + case ParseNodeType.Function: + return this.visitFunction(node as FunctionNode); + + case ParseNodeType.Global: + return this.visitGlobal(node as GlobalNode); + + case ParseNodeType.Lambda: + return this.visitLambda(node as LambdaNode); + + case ParseNodeType.List: + return this.visitList(node as ListNode); + + case ParseNodeType.ListComprehension: + return this.visitListComprehension(node as ListComprehensionNode); + + case ParseNodeType.ListComprehensionFor: + return this.visitListComprehensionFor(node as ListComprehensionForNode); + + case ParseNodeType.ListComprehensionIf: + return this.visitListComprehensionIf(node as ListComprehensionIfNode); + + case ParseNodeType.MemberAccess: + return this.visitMemberAccess(node as MemberAccessExpressionNode); + + case ParseNodeType.Module: + return this.visitModule(node as ModuleNode); + + case ParseNodeType.ModuleName: + return this.visitModuleName(node as ModuleNameNode); + + case ParseNodeType.Name: + return this.visitName(node as NameNode); + + case ParseNodeType.Nonlocal: + return this.visitNonlocal(node as NonlocalNode); + + case ParseNodeType.Number: + return this.visitNumber(node as NumberNode); + + case ParseNodeType.Parameter: + return this.visitParameter(node as ParameterNode); + + case ParseNodeType.Pass: + return this.visitPass(node as PassNode); + + case ParseNodeType.Raise: + return this.visitRaise(node as RaiseNode); + + case ParseNodeType.Return: + return this.visitReturn(node as ReturnNode); + + case ParseNodeType.Set: + return this.visitSet(node as SetNode); + + case ParseNodeType.Slice: + return this.visitSlice(node as SliceExpressionNode); + + case ParseNodeType.Star: + return this.visitStar(node as StarExpressionNode); + + case ParseNodeType.StatementList: + return this.visitStatementList(node as StatementListNode); + + case ParseNodeType.String: + return this.visitString(node as StringNode); + + case ParseNodeType.Suite: + return this.visitSuite(node as SuiteNode); + + case ParseNodeType.Tuple: + return this.visitTuple(node as TupleExpressionNode); + + case ParseNodeType.Try: + return this.visitTry(node as TryNode); + + case ParseNodeType.TypeAnnotation: + return this.visitTypeAnnotation(node as TypeAnnotationExpressionNode); + + case ParseNodeType.UnaryOperation: + return this.visitUnaryOperation(node as UnaryExpressionNode); + + case ParseNodeType.While: + return this.visitWhile(node as WhileNode); + + case ParseNodeType.With: + return this.visitWith(node as WithNode); + + case ParseNodeType.WithItem: + return this.visitWithItem(node as WithItemNode); + + case ParseNodeType.Yield: + return this.visitYield(node as YieldExpressionNode); + + case ParseNodeType.YieldFrom: + return this.visitYieldFrom(node as YieldFromExpressionNode); + + case ParseNodeType.Error: + return false; + + case ParseNodeType.None: + default: + assert.fail('Unexpected node type'); + return false; + } + } + + // Override these methods as necessary. + visitArgument(node: ArgumentNode) { + return true; + } + + visitAssert(node: AssertNode) { + return true; + } + + visitAssignment(node: AssignmentNode) { + return true; + } + + visitAgumentedAssignment(node: AugmentedAssignemtnExpressionNode) { + return true; + } + + visitAwait(node: AwaitExpressionNode) { + return true; + } + + visitBinaryOperation(node: BinaryExpressionNode) { + return true; + } + + visitBreak(node: BreakNode) { + return true; + } + + visitCall(node: CallExpressionNode) { + return true; + } + + visitClass(node: ClassNode) { + return true; + } + + visitConditional(node: ConditionalExpressionNode) { + return true; + } + + visitContinue(node: ContinueNode) { + return true; + } + + visitConstant(node: ConstantNode) { + return true; + } + + visitDecorator(node: DecoratorNode) { + return true; + } + + visitDel(node: DelNode) { + return true; + } + + visitDictionary(node: DictionaryNode) { + return true; + } + + visitDictionaryKeyEntry(node: DictionaryKeyEntryNode) { + return true; + } + + visitDictionarExpandEntry(node: DictionaryExpandEntryNode) { + return true; + } + + visitEllipsis(node: EllipsisNode) { + return true; + } + + visitIf(node: IfNode) { + return true; + } + + visitImport(node: ImportNode) { + return true; + } + + visitImportAs(node: ImportAsNode) { + return true; + } + + visitImportFrom(node: ImportFromNode) { + return true; + } + + visitImportFromAs(node: ImportFromAsNode) { + return true; + } + + visitIndex(node: IndexExpressionNode) { + return true; + } + + visitExcept(node: ExceptNode) { + return true; + } + + visitFor(node: ForNode) { + return true; + } + + visitFunction(node: FunctionNode) { + return true; + } + + visitGlobal(node: GlobalNode) { + return true; + } + + visitLambda(node: LambdaNode) { + return true; + } + + visitList(node: ListNode) { + return true; + } + + visitListComprehension(node: ListComprehensionNode) { + return true; + } + + visitListComprehensionFor(node: ListComprehensionForNode) { + return true; + } + + visitListComprehensionIf(node: ListComprehensionIfNode) { + return true; + } + + visitMemberAccess(node: MemberAccessExpressionNode) { + return true; + } + + visitModule(node: ModuleNode) { + return true; + } + + visitModuleName(node: ModuleNameNode) { + return true; + } + + visitName(node: NameNode) { + return true; + } + + visitNonlocal(node: NonlocalNode) { + return true; + } + + visitNumber(node: NumberNode) { + return true; + } + + visitParameter(node: ParameterNode) { + return true; + } + + visitPass(node: PassNode) { + return true; + } + + visitRaise(node: RaiseNode) { + return true; + } + + visitReturn(node: ReturnNode) { + return true; + } + + visitSet(node: SetNode) { + return true; + } + + visitSlice(node: SliceExpressionNode) { + return true; + } + + visitStar(node: StarExpressionNode) { + return true; + } + + visitStatementList(node: StatementListNode) { + return true; + } + + visitString(node: StringNode) { + return true; + } + + visitSuite(node: SuiteNode) { + return true; + } + + visitTuple(node: TupleExpressionNode) { + return true; + } + + visitTry(node: TryNode) { + return true; + } + + visitTypeAnnotation(node: TypeAnnotationExpressionNode) { + return true; + } + + visitUnaryOperation(node: UnaryExpressionNode) { + return true; + } + + visitWhile(node: WhileNode) { + return true; + } + + visitWith(node: WithNode) { + return true; + } + + visitWithItem(node: WithItemNode) { + return true; + } + + visitYield(node: YieldExpressionNode) { + return true; + } + + visitYieldFrom(node: YieldFromExpressionNode) { + return true; + } +} diff --git a/server/src/analyzer/postParseWalker.ts b/server/src/analyzer/postParseWalker.ts new file mode 100644 index 000000000..a9f6e33a2 --- /dev/null +++ b/server/src/analyzer/postParseWalker.ts @@ -0,0 +1,267 @@ +/* +* postParseWalker.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* A parse tree walker that's used immediatley after generating +* the parse tree, effectively as an extension of the parser. +* It does the following: +* Adds parent links to all parse tree nodes +* Builds nameBindings for module, class, function and lambda scopes +* Reports name binding inconsistencies (e.g. if a name is bound +* both locally and globally) +* Builds a list of imported modules +*/ + +import { TextRangeDiagnosticSink } from '../common/diagnosticSink'; +import { NameBindings, NameBindingType } from '../parser/nameBindings'; +import { AssignmentNode, ClassNode, ExpressionNode, ForNode, + FunctionNode, GlobalNode, ImportAsNode, ImportFromAsNode, ImportFromNode, + LambdaNode, ListNode, ModuleNameNode, ModuleNode, NameNode, NonlocalNode, + ParseNode, StarExpressionNode, TupleExpressionNode, TypeAnnotationExpressionNode, + WithNode } from '../parser/parseNodes'; +import { AnalyzerNodeInfo } from './analyzerNodeInfo'; +import { ParseTreeWalker } from './parseTreeWalker'; + +export class PostParseWalker extends ParseTreeWalker { + private _parseTree: ModuleNode; + private _diagnosticSink: TextRangeDiagnosticSink; + private _isStubFile: boolean; + private _moduleNames: ModuleNameNode[] = []; + private _currentNameBindings: NameBindings; + private _currentBindingType: NameBindingType; + + constructor(diagSink: TextRangeDiagnosticSink, parseTree: ModuleNode, isStubFile: boolean) { + super(); + + this._diagnosticSink = diagSink; + this._parseTree = parseTree; + this._isStubFile = isStubFile; + + let moduleNameBindings = new NameBindings(NameBindingType.Global); + AnalyzerNodeInfo.setNameBindings(parseTree, moduleNameBindings); + this._currentNameBindings = moduleNameBindings; + this._currentBindingType = NameBindingType.Global; + } + + analyze() { + this.walk(this._parseTree); + } + + getImportedModules(): ModuleNameNode[] { + return this._moduleNames; + } + + visitNode(node: ParseNode): boolean { + let children = this.getChildren(node); + + // Add the parent link to each of the child nodes. + children.forEach(child => { + child.parent = node; + }); + + return super.visitNode(node); + } + + visitModuleName(node: ModuleNameNode) { + this._moduleNames.push(node); + return true; + } + + visitImportAs(node: ImportAsNode): boolean { + if (node.alias) { + this._addName(node.alias.nameToken.value); + } else if (node.module.nameParts.length > 0) { + this._addName(node.module.nameParts[0].nameToken.value); + } + return true; + } + + visitImportFrom(node: ImportFromNode): boolean { + if (node.imports.length === 0) { + this._currentNameBindings.addWildcard(); + } + return true; + } + + visitImportFromAs(node: ImportFromAsNode): boolean { + if (node.alias) { + this._addName(node.alias.nameToken.value); + } else { + this._addName(node.name.nameToken.value); + } + return false; + } + + visitWith(node: WithNode): boolean { + node.withItems.forEach(item => { + this.walk(item.expression); + }); + + node.withItems.forEach(item => { + if (item.target) { + this._addPossibleTupleNamedTarget(item.target); + } + }); + + this.walk(node.suite); + return false; + } + + visitFunction(node: FunctionNode): boolean { + let nameBindings = new NameBindings(NameBindingType.Local); + AnalyzerNodeInfo.setNameBindings(node, nameBindings); + + // Decorators are executed in the scope outside the function. + this.walkMultiple(node.decorators); + + this._addName(node.name.nameToken.value); + this._createNewScope(nameBindings, () => { + // Populate the new scope with parameter names. + node.parameters.forEach(param => { + if (param.name) { + this._addName(param.name.nameToken.value); + } + }); + + this.walkMultiple(node.parameters); + + if (node.returnTypeAnnotation) { + this.walk(node.returnTypeAnnotation.expression); + } + + this.walk(node.suite); + }); + + return false; + } + + visitClass(node: ClassNode) { + let nameBindings = new NameBindings(NameBindingType.Local); + AnalyzerNodeInfo.setNameBindings(node, nameBindings); + + // Decorators are executed in the scope outside the class. + this.walkMultiple(node.decorators); + + this._addName(node.name.nameToken.value); + this._createNewScope(nameBindings, () => { + this.walkMultiple(node.arguments); + this.walk(node.suite); + }); + + return false; + } + + visitLambda(node: LambdaNode): boolean { + let nameBindings = new NameBindings(NameBindingType.Local); + AnalyzerNodeInfo.setNameBindings(node, nameBindings); + + this._createNewScope(nameBindings, () => { + // Populate the new scope with parameter names. + node.parameters.forEach(param => { + if (param.name) { + this._addName(param.name.nameToken.value); + } + }); + + this.walkMultiple(node.parameters); + + this.walk(node.expression); + }); + + return false; + } + + visitAssignment(node: AssignmentNode) { + this._addPossibleTupleNamedTarget(node.leftExpression); + return true; + } + + visitTypeAnnotation(node: TypeAnnotationExpressionNode): boolean { + if (this._isStubFile) { + this._addPossibleTupleNamedTarget(node.valueExpression); + } + + // Don't walk the type annotation node in this pass. + this.walk(node.valueExpression); + + return false; + } + + visitFor(node: ForNode) { + this._addPossibleTupleNamedTarget(node.targetExpression); + return true; + } + + visitGlobal(node: GlobalNode) { + node.nameList.forEach(name => { + if (!this._currentNameBindings.addName(name.nameToken.value, NameBindingType.Global)) { + this._diagnosticSink.addErrorWithTextRange( + `'${ name.nameToken.value }' is assigned before global declaration`, + name); + } + }); + return true; + } + + visitNonlocal(node: NonlocalNode) { + let moduleNameBindings = AnalyzerNodeInfo.getNameBindings(this._parseTree); + if (this._currentNameBindings === moduleNameBindings) { + this._diagnosticSink.addErrorWithTextRange( + 'Nonlocal declaration not allowed at module level', + node); + } else { + node.nameList.forEach(name => { + if (!this._currentNameBindings.addName(name.nameToken.value, NameBindingType.Nonlocal)) { + this._diagnosticSink.addErrorWithTextRange( + `'${ name.nameToken.value }' is assigned before nonlocal declaration`, + name); + } + }); + } + return true; + } + + private _addPossibleTupleNamedTarget(node: ExpressionNode) { + if (node instanceof TupleExpressionNode) { + node.expressions.forEach(expr => { + this._addPossibleTupleNamedTarget(expr); + }); + } else if (node instanceof ListNode) { + node.entries.forEach(expr => { + this._addPossibleTupleNamedTarget(expr); + }); + } else if (node instanceof TypeAnnotationExpressionNode) { + this._addPossibleTupleNamedTarget(node.valueExpression); + } else if (node instanceof StarExpressionNode) { + if (node.expression instanceof NameNode) { + let name = node.expression.nameToken; + this._addName(name.value); + } + } else if (node instanceof NameNode) { + let name = node.nameToken; + this._addName(name.value); + } + } + + private _addName(name: string) { + let scopeType = this._currentNameBindings.lookUpName(name); + if (scopeType === undefined) { + this._currentNameBindings.addName(name, this._currentBindingType); + } + } + + private _createNewScope(nameBindings: NameBindings, walkInnerScopeCallback: () => void) { + let prevNameBindings = this._currentNameBindings; + this._currentNameBindings = nameBindings; + + let prevBindingScope = this._currentBindingType; + this._currentBindingType = NameBindingType.Local; + + walkInnerScopeCallback(); + + this._currentNameBindings = prevNameBindings; + this._currentBindingType = prevBindingScope; + return false; + } +} diff --git a/server/src/analyzer/program.ts b/server/src/analyzer/program.ts new file mode 100644 index 000000000..5d6a0a4a1 --- /dev/null +++ b/server/src/analyzer/program.ts @@ -0,0 +1,621 @@ +/* +* program.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* An object that tracks all of the source files being analyzed +* and all of their recursive imports. +*/ + +import * as assert from 'assert'; + +import { ConfigOptions } from '../common/configOptions'; +import { ConsoleInterface, StandardConsole } from '../common/console'; +import { DiagnosticTextPosition, DocumentTextRange } from '../common/diagnostic'; +import { FileDiagnostics } from '../common/diagnosticSink'; +import { Duration } from '../common/timing'; +import { ImportMap } from './analyzerFileInfo'; +import { AnalyzerNodeInfo } from './analyzerNodeInfo'; +import { ImportType } from './importResult'; +import { Scope } from './scope'; +import { SourceFile } from './sourceFile'; + +export interface SourceFileInfo { + sourceFile: SourceFile; + isTracked: boolean; + isOpenByClient: boolean; + isTypeshedFile: boolean; + diagnosticsVersion: number; + imports: SourceFileInfo[]; + builtinsImport?: SourceFileInfo; + importedBy: SourceFileInfo[]; +} + +// Container for all of the files that are being analyzed. Files +// can fall into one or more of the following categories: +// Tracked - specified by the config options +// Referenced - part of the transitive closure +// Opened - temporarily opened in the editor +export class Program { + private _console: ConsoleInterface; + private _sourceFileList: SourceFileInfo[] = []; + private _sourceFileMap: { [path: string]: SourceFileInfo } = {}; + + constructor(console?: ConsoleInterface) { + this._console = console || new StandardConsole(); + } + + // Sets the list of tracked files that make up the program. + setTrackedFiles(filePaths: string[]): FileDiagnostics[] { + if (this._sourceFileList.length > 0) { + // We need to determine which files to remove from the existing file list. + let newFileMap: { [path: string]: string } = {}; + filePaths.forEach(path => { + newFileMap[path] = path; + }); + + // Files that are not in the tracked file list are + // marked as no longer tracked. + this._sourceFileList.forEach(oldFile => { + let filePath = oldFile.sourceFile.getFilePath(); + if (newFileMap[filePath] === undefined) { + oldFile.isTracked = false; + } + }); + } + + // Add the new files. Only the new items will be added. + this.addTrackedFiles(filePaths); + + return this._removeUnneededFiles(); + } + + getFileCount() { + return this._sourceFileList.length; + } + + addTrackedFiles(filePaths: string[]) { + filePaths.forEach(filePath => { + this.addTrackedFile(filePath); + }); + } + + addTrackedFile(filePath: string): SourceFile { + let sourceFileInfo = this._sourceFileMap[filePath]; + if (sourceFileInfo) { + sourceFileInfo.isTracked = true; + return sourceFileInfo.sourceFile; + } + + let sourceFile = new SourceFile(filePath, false, this._console); + sourceFileInfo = { + sourceFile, + isTracked: true, + isOpenByClient: false, + isTypeshedFile: false, + diagnosticsVersion: sourceFile.getDiagnosticVersion(), + imports: [], + importedBy: [] + }; + this._sourceFileMap[filePath] = sourceFileInfo; + this._sourceFileList.push(sourceFileInfo); + return sourceFile; + } + + setFileOpened(filePath: string, version: number | null, contents: string) { + let sourceFileInfo = this._sourceFileMap[filePath]; + if (!sourceFileInfo) { + let sourceFile = new SourceFile(filePath, false, this._console); + sourceFileInfo = { + sourceFile, + isTracked: false, + isOpenByClient: true, + isTypeshedFile: false, + diagnosticsVersion: sourceFile.getDiagnosticVersion(), + imports: [], + importedBy: [] + }; + this._sourceFileMap[filePath] = sourceFileInfo; + this._sourceFileList.push(sourceFileInfo); + } else { + sourceFileInfo.isOpenByClient = true; + } + + sourceFileInfo.sourceFile.setClientVersion(version, contents); + } + + setFileClosed(filePath: string): FileDiagnostics[] { + let sourceFileInfo = this._sourceFileMap[filePath]; + if (sourceFileInfo) { + sourceFileInfo.isOpenByClient = false; + sourceFileInfo.sourceFile.setClientVersion(null, ''); + } + + return this._removeUnneededFiles(); + } + + markAllFilesDirty() { + this._sourceFileList.forEach(sourceFileInfo => { + sourceFileInfo.sourceFile.markDirty(); + }); + } + + markFilesDirty(filePaths: string[]) { + let markDirtyMap: { [path: string]: boolean } = {}; + filePaths.forEach(filePath => { + let sourceFileInfo = this._sourceFileMap[filePath]; + if (sourceFileInfo) { + sourceFileInfo.sourceFile.markDirty(); + + // Mark any files that depend on this file as dirty + // also. This will retrigger analysis of these other files. + this._markFileDirtyRecursive(sourceFileInfo, markDirtyMap); + } + }); + } + + getSourceFile(filePath: string): SourceFile | undefined { + let sourceFileInfo = this._sourceFileMap[filePath]; + if (!sourceFileInfo) { + return undefined; + } + return sourceFileInfo.sourceFile; + } + + // Performs parsing and analysis of any source files in the program + // that require it. If a limit time is specified, the operation + // is interrupted when the time expires. The return value indicates + // whether the method needs to be called again to complete the + // analysis. + analyze(options: ConfigOptions, maxTime?: number): boolean { + let elapsedTime = new Duration(); + + let isTimeElapsed = () => { + return maxTime !== undefined && maxTime !== 0 && + elapsedTime.getDurationInMilliseconds() > maxTime; + }; + + let openFiles = this._sourceFileList.filter(sf => sf.isOpenByClient); + + // Start by parsing the open files. + for (let sourceFileInfo of openFiles) { + this._parseFile(sourceFileInfo, options); + + if (isTimeElapsed()) { + return true; + } + } + + // Now do semantic analysis of the open files. + for (let sourceFileInfo of openFiles) { + this._doSemanticAnalysis(sourceFileInfo, options); + + if (isTimeElapsed()) { + return true; + } + } + + // Now do type analysis of the open files. + for (let sourceFileInfo of openFiles) { + if (this._doFullAnalysis(sourceFileInfo, options, isTimeElapsed)) { + return true; + } + } + + // Do type analysis of remaining files. + let allFiles = this._sourceFileList; + + // Now do type parsing and analysis of the remaining. + for (let sourceFileInfo of allFiles) { + if (this._doFullAnalysis(sourceFileInfo, options, isTimeElapsed)) { + return true; + } + } + + return false; + } + + private _parseFile(fileToParse: SourceFileInfo, options: ConfigOptions) { + if (!this._isFileNeeded(fileToParse) || !fileToParse.sourceFile.isParseRequired()) { + return; + } + + if (fileToParse.sourceFile.parse(options)) { + this._updateSourceFileImports(fileToParse); + } + } + + private _doSemanticAnalysis(fileToAnalyze: SourceFileInfo, options: ConfigOptions) { + if (!this._isFileNeeded(fileToAnalyze) || !fileToAnalyze.sourceFile.isSemanticAnalysisRequired()) { + return; + } + + this._parseFile(fileToAnalyze, options); + + // We need to parse and semantically analyze the builtins import first. + let builtinsScope: Scope | undefined; + if (fileToAnalyze.builtinsImport) { + this._doSemanticAnalysis(fileToAnalyze.builtinsImport, options); + + // Get the builtins scope to pass to the semantic analyzer pass. + const parseResults = fileToAnalyze.builtinsImport.sourceFile.getParseResults(); + if (parseResults) { + builtinsScope = AnalyzerNodeInfo.getScope(parseResults.parseTree); + assert(builtinsScope !== undefined); + } + } + + fileToAnalyze.sourceFile.doSemanticAnalysis(options, builtinsScope); + } + + private _doFullAnalysis(fileToAnalyze: SourceFileInfo, options: ConfigOptions, + timeElapsedCallback: () => boolean): boolean { + // If the file isn't needed because it was eliminated from the + // transitive closure or deleted, skip the file rather than wasting + // time on it. + if (!this._isFileNeeded(fileToAnalyze)) { + return false; + } + + // Discover all imports (recursively) that have not yet been finalized. + let closureMap: { [path: string]: boolean } = {}; + let analysisQueue: SourceFileInfo[] = []; + if (this._getNonFinalizedImportsRecursive(fileToAnalyze, closureMap, + analysisQueue, options, timeElapsedCallback)) { + return true; + } + + // Perform type analysis on the files in the analysis queue, which + // is ordered in a way that should minimize the number of passes + // we need to perform (with lower-level imports earlier in the list). + while (true) { + let fileToAnalyze = analysisQueue.shift(); + if (!fileToAnalyze) { + break; + } + + closureMap[fileToAnalyze.sourceFile.getFilePath()] = false; + + if (fileToAnalyze.sourceFile.isTypeAnalysisRequired()) { + // Build the import map for the file. + let importMap: ImportMap = {}; + for (let importedFileInfo of fileToAnalyze.imports) { + let parseResults = importedFileInfo.sourceFile.getParseResults(); + assert(parseResults !== undefined); + importMap[importedFileInfo.sourceFile.getFilePath()] = parseResults!; + } + + // Do a type analysis pass and determine if any internal changes occurred + // during the pass. If so, continue to analyze until it stops changing and + // mark all of its dependencies as needing to be reanalyzed. + let didAnalysisChange = false; + while (true) { + fileToAnalyze.sourceFile.doTypeAnalysis(options, importMap); + + if (timeElapsedCallback()) { + return true; + } + + if (!fileToAnalyze.sourceFile.isTypeAnalysisRequired()) { + break; + } else { + didAnalysisChange = true; + } + } + + // We completed one or more updates to the file in this type + // analysis pass, so we need to add its dependencies back + // onto the queue if they're not already on it. + if (didAnalysisChange) { + for (let dependency of fileToAnalyze.importedBy) { + const dependencyFilePath = dependency.sourceFile.getFilePath(); + + // If the dependency isn't part of the closure, we can ignore it. + if (closureMap[dependencyFilePath] !== undefined) { + dependency.sourceFile.setTypeAnalysisPassNeeded(); + + if (!closureMap[dependencyFilePath]) { + analysisQueue.push(dependency); + closureMap[dependencyFilePath] = true; + } + } + } + } + } + } + + // Mark all files in the closure as finalized. + Object.keys(closureMap).forEach(filePath => { + this._sourceFileMap[filePath].sourceFile.finalizeAnalysis(); + }); + + return false; + } + + // Builds a map of files that includes fileToAnalyze and all of the files + // it imports (recursively) and ensures that all such files have been semantically + // analyzed in preparation for the type analysis phase. If any of these files have + // already been finalized (they and their recursive imports have completed the + // type analysis phase), they are not included in the results. Also builds a + // prioritized queue of files to analyze. Returns true if it ran out of time before + // completing. + private _getNonFinalizedImportsRecursive(fileToAnalyze: SourceFileInfo, + closureMap: { [path: string]: boolean }, analysisQueue: SourceFileInfo[], + options: ConfigOptions, timeElapsedCallback: () => boolean): boolean { + // If the file is already finalized, no need to do any more work. + if (fileToAnalyze.sourceFile.isAnalysisFinalized()) { + return false; + } + + // If the file is already in the closure map, we found a cyclical + // dependency. Don't recurse further. + const filePath = fileToAnalyze.sourceFile.getFilePath(); + if (closureMap[filePath] !== undefined) { + return false; + } + + // Make sure the file is parsed and semantically analyzed. + this._doSemanticAnalysis(fileToAnalyze, options); + if (timeElapsedCallback()) { + return true; + } + + // Add the file to the closure map. + closureMap[filePath] = false; + + // Recursively add the file's imports. + for (let importedFileInfo of fileToAnalyze.imports) { + if (this._getNonFinalizedImportsRecursive(importedFileInfo, closureMap, + analysisQueue, options, timeElapsedCallback)) { + return true; + } + } + + // If the file hasn't already been added to the analysis queue, + // add it now. + if (!closureMap[filePath]) { + closureMap[filePath] = true; + analysisQueue.push(fileToAnalyze); + } + + return false; + } + + private _markFileDirtyRecursive(sourceFileInfo: SourceFileInfo, + markMap: { [path: string]: boolean }) { + let filePath = sourceFileInfo.sourceFile.getFilePath(); + + // Don't mark it again if it's already been visited. + if (markMap[filePath] === undefined) { + sourceFileInfo.sourceFile.markReanalysisRequired(); + markMap[filePath] = true; + + sourceFileInfo.importedBy.forEach(dep => { + this._markFileDirtyRecursive(dep, markMap); + }); + } + } + + getDiagnostics(options: ConfigOptions): FileDiagnostics[] { + let fileDiagnostics: FileDiagnostics[] = this._removeUnneededFiles(); + + this._sourceFileList.forEach(sourceFileInfo => { + let diagnostics = sourceFileInfo.sourceFile.getDiagnostics( + options, sourceFileInfo.diagnosticsVersion); + if (diagnostics !== undefined) { + fileDiagnostics.push({ + filePath: sourceFileInfo.sourceFile.getFilePath(), + diagnostics + }); + + // Update the cached diagnosticsVersion so we can determine + // whether there are any updates next time we call getDiagnostics. + sourceFileInfo.diagnosticsVersion = + sourceFileInfo.sourceFile.getDiagnosticVersion(); + } + }); + + return fileDiagnostics; + } + + getDefinitionForPosition(filePath: string, position: DiagnosticTextPosition): + DocumentTextRange | undefined { + let sourceFile = this.getSourceFile(filePath); + if (!sourceFile) { + return undefined; + } + + return sourceFile.getDefinitionForPosition(position); + } + + getHoverForPosition(filePath: string, position: DiagnosticTextPosition): + string | undefined { + let sourceFile = this.getSourceFile(filePath); + if (!sourceFile) { + return undefined; + } + + return sourceFile.getHoverForPosition(position); + } + + // Returns a list of empty file diagnostic entries for the files + // that have been removed. This is needed to clear out the + // errors for files that have been deleted or closed. + private _removeUnneededFiles(): FileDiagnostics[] { + let fileDiagnostics: FileDiagnostics[] = []; + + // If a file is no longer tracked or opened, it can + // be removed from the program. + for (let i = 0; i < this._sourceFileList.length; ) { + let fileInfo = this._sourceFileList[i]; + if (!this._isFileNeeded(fileInfo)) { + fileDiagnostics.push({ + filePath: fileInfo.sourceFile.getFilePath(), + diagnostics: [] + }); + + fileInfo.sourceFile.prepareForClose(); + delete this._sourceFileMap[fileInfo.sourceFile.getFilePath()]; + this._sourceFileList.splice(i, 1); + + // Unlink any imports and remove them from the list if + // they are no longer referenced. + fileInfo.imports.forEach(importedFile => { + let indexToRemove = importedFile.importedBy.findIndex(fi => fi === fileInfo); + assert(indexToRemove >= 0); + importedFile.importedBy.splice(indexToRemove, 1); + + // See if we need to remove the imported file because it + // is no longer needed. If its index is >= i, it will be + // removed when we get to it. + if (!this._isFileNeeded(importedFile)) { + let indexToRemove = this._sourceFileList.findIndex(fi => fi === importedFile); + if (indexToRemove < i) { + fileDiagnostics.push({ + filePath: importedFile.sourceFile.getFilePath(), + diagnostics: [] + }); + + importedFile.sourceFile.prepareForClose(); + delete this._sourceFileMap[importedFile.sourceFile.getFilePath()]; + this._sourceFileList.splice(indexToRemove, 1); + i--; + } + } + }); + } else { + i++; + } + } + + return fileDiagnostics; + } + + private _isFileNeeded(fileInfo: SourceFileInfo) { + if (fileInfo.isTracked || fileInfo.isOpenByClient) { + return true; + } + + if (fileInfo.importedBy.length === 0) { + return false; + } + + // It's possible for a cycle of files to be imported + // by a tracked file but then abandoned. The import cycle + // will keep the entire group "alive" if we don't detect + // the condition and garbage collect them. + return this._isImportNeededRecursive(fileInfo, {}); + } + + private _isImportNeededRecursive(fileInfo: SourceFileInfo, recursionMap: { [path: string ]: boolean }) { + if (fileInfo.isTracked || fileInfo.isOpenByClient) { + return true; + } + + const filePath = fileInfo.sourceFile.getFilePath(); + + // Avoid infinite recursion. + if (recursionMap[filePath]) { + return false; + } + + recursionMap[filePath] = true; + + for (let importerInfo of fileInfo.importedBy) { + if (this._isImportNeededRecursive(importerInfo, recursionMap)) { + return true; + } + } + + return false; + } + + private _updateSourceFileImports(sourceFileInfo: SourceFileInfo): SourceFileInfo[] { + let filesAdded: SourceFileInfo[] = []; + + // Get the new list of imports and see if it changed from the last + // list of imports for this file. + let imports = sourceFileInfo.sourceFile.getImports(); + + // Create a map of unique imports, since imports can appear more than once. + let newImportPathMap: { [name: string]: boolean } = {}; + imports.forEach(importResult => { + if (importResult.importFound && importResult.resolvedPaths.length > 0) { + if (importResult.importType === ImportType.Local || importResult.isStubFile) { + // Namespace packages have no __init__.py file, so the resolved + // path points to a directory. + if (!importResult.isNamespacePackage) { + let filePath = importResult.resolvedPaths[ + importResult.resolvedPaths.length - 1]; + newImportPathMap[filePath] = !!importResult.isTypeshedFile; + } + + importResult.implicitImports.forEach(implicitImport => { + newImportPathMap[implicitImport.path] = !!importResult.isTypeshedFile; + }); + } + } + }); + + let updatedImportMap: { [name: string]: SourceFileInfo } = {}; + sourceFileInfo.imports.forEach(importInfo => { + let oldFilePath = importInfo.sourceFile.getFilePath(); + + // A previous import was removed. + if (newImportPathMap[oldFilePath] === undefined) { + importInfo.importedBy = importInfo.importedBy.filter( + fi => fi.sourceFile.getFilePath() !== sourceFileInfo.sourceFile.getFilePath()); + } else { + updatedImportMap[oldFilePath] = importInfo; + } + }); + + // See if there are any new imports to be added. + Object.keys(newImportPathMap).forEach(importPath => { + if (updatedImportMap[importPath] === undefined) { + // We found a new import to add. See if it's already part + // of the program. + let importedFileInfo: SourceFileInfo; + if (this._sourceFileMap[importPath] !== undefined) { + importedFileInfo = this._sourceFileMap[importPath]; + } else { + let sourceFile = new SourceFile( + importPath, newImportPathMap[importPath], this._console); + importedFileInfo = { + sourceFile, + isTracked: false, + isOpenByClient: false, + isTypeshedFile: newImportPathMap[importPath], + diagnosticsVersion: sourceFile.getDiagnosticVersion(), + imports: [], + importedBy: [] + }; + + this._sourceFileList.push(importedFileInfo); + this._sourceFileMap[importPath] = importedFileInfo; + filesAdded.push(importedFileInfo); + } + + importedFileInfo.importedBy.push(sourceFileInfo); + updatedImportMap[importPath] = importedFileInfo; + } + }); + + // Update the imports list. It should now map the set of imports + // specified by the source file. + sourceFileInfo.imports = Object.keys(newImportPathMap).map( + importPath => this._sourceFileMap[importPath]); + + // Resolve the builtins import for the file. This needs to be + // analyzed before the file can be analyzed. + sourceFileInfo.builtinsImport = undefined; + let builtinsImport = sourceFileInfo.sourceFile.getBuiltinsImport(); + if (builtinsImport) { + const resolvedBuiltinsPath = builtinsImport.resolvedPaths[ + builtinsImport.resolvedPaths.length - 1]; + sourceFileInfo.builtinsImport = this._sourceFileMap[resolvedBuiltinsPath]; + } + + return filesAdded; + } +} diff --git a/server/src/analyzer/scope.ts b/server/src/analyzer/scope.ts new file mode 100644 index 000000000..4c19da9ce --- /dev/null +++ b/server/src/analyzer/scope.ts @@ -0,0 +1,384 @@ +/* +* scope.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Represents a symbolic scope and its defined symbols. Unlike +* a "Namesspace", a scope object tracks dynamic (runtime) +* bindings between names types. The analyzer stores these types +* in the scope as it walks through the program, effective doing +* what the Python interpreter will do. +*/ + +import * as assert from 'assert'; + +import { DefaultTypeSourceId, InferredType, TypeSourceId } from './inferredType'; +import { Declaration, Symbol, SymbolTable } from './symbol'; +import { TypeConstraint } from './typeConstraint'; +import { Type, UnboundType } from './types'; +import { TypeUtils } from './typeUtils'; + +export enum ScopeType { + // Temporary scopes are used temporarily during analysis + // to represent conditional blocks. + Temporary, + + // Local scopes are used for lambdas, functions and classes. + Local, + + // Global scopes are used for modules. + Global, + + // Built-in scopes are used for all ambient symbols provided + // by the Python environment. + BuiltIn +} + +export class Scope { + // The scope type, as defined in the enumeration. + private _scopeType: ScopeType; + + // The next scope in the hierarchy or undefined if it's the + // top-most scope. + private _parent?: Scope; + + // Associations between names, type, and declarations. + private _symbolTable: SymbolTable = new SymbolTable(); + + // Names in the _hideNameMap will be hidden from child scopes. + private _hiddenNameMap: { [name: string]: string } = {}; + + // Indicates whether the scope is conditionally executed + // (i.e. is not guaranteed to be executed). + private _isConditional: boolean; + + // Indicates whether the scope is guaranteed not to be + // executed because a condition is statically determined + // to be always true or false. + private _isNotExecuted: boolean; + + // Tracks whether the code flow for the scope always returns + // before exiting the block. + private _alwaysReturns = false; + + // Tracks whether the code flow for the scope always raises + // an exception before exiting the block. + private _alwaysRaises = false; + + // Number of nested try statements the scope is currently within. + // This is used to determine whether to set the _alwaysReturnsOrRaises + // flag when a raise statement is encountered. + private _nestedTryDepth = 0; + + // Inferred return type for the scope. + private _returnType = new InferredType(); + + // Active type constraints for this scope -- used for conditional + // scopes where the condition constrains the types of certain + // expressions. + private _typeConstraints: TypeConstraint[] = []; + + constructor(type: ScopeType, parent?: Scope) { + this._scopeType = type; + this._parent = parent; + this._isConditional = false; + this._isNotExecuted = false; + } + + hideName(name: string) { + this._hiddenNameMap[name] = name; + } + + getSymbolTable(): SymbolTable { + return this._symbolTable; + } + + getSymbols(): string[] { + return this._symbolTable.getKeys(); + } + + getType(): ScopeType { + return this._scopeType; + } + + getParent(): Scope | undefined { + return this._parent; + } + + getReturnType(): InferredType { + return this._returnType; + } + + setConditional() { + // Only temporary scopes can be conditional. + assert(this._scopeType === ScopeType.Temporary); + this._isConditional = true; + } + + isConditional() { + return this._isConditional; + } + + setIsNotExecuted() { + this._isNotExecuted = true; + } + + isNotExecuted() { + return this._isNotExecuted; + } + + lookUpSymbol(name: string): Symbol | undefined { + return this._symbolTable.get(name); + } + + lookUpSymbolRecursive(name: string): SymbolWithScope | undefined { + return this._lookUpSymbolRecursiveInternal(name, false); + } + + // Adds a new (unbound) symbol to the scope. + addUnboundSymbol(name: string) { + let symbol = new Symbol(UnboundType.create(), DefaultTypeSourceId); + this._symbolTable.set(name, symbol); + } + + // Binds a type to an existing name in the scope. + setSymbolCurrentType(name: string, type: Type, typeSourceId: TypeSourceId): boolean { + const symbol = this._symbolTable.get(name); + if (symbol) { + return symbol.setCurrentType(type, typeSourceId); + } else { + this._symbolTable.set(name, new Symbol(type, typeSourceId)); + return true; + } + } + + addSymbolDeclaration(name: string, declaration: Declaration) { + const symbol = this._symbolTable.get(name)!; + assert(symbol !== undefined); + + symbol.addDeclaration(declaration); + } + + // Marks all of the types associated with symbols in this + // scope as "conditional". + markAllSymbolsConditional() { + assert(this._isConditional); + + this._symbolTable.forEach(symbol => { + symbol.isConditional = true; + }); + } + + // Merges a specified temporary scope into another scope (which is + // assumed to be its parent or a direct ancestor). Returns true if + // a scope was modified in a meaningful way. + mergeSymbolTable(scopeToMerge: Scope): boolean { + assert(scopeToMerge.getType() === ScopeType.Temporary); + + let modifiedType = false; + + for (let name of scopeToMerge._symbolTable.getKeys()) { + let symbolToMerge = scopeToMerge._symbolTable.get(name)!; + let mergeConditional = !!symbolToMerge.isConditional; + let targetScope: Scope; + + if (this._scopeType === ScopeType.Temporary) { + targetScope = this; + } else { + let scopeWithName = this.lookUpSymbolRecursive(name); + if (!scopeWithName) { + continue; + } + + // Always merge non-local scopes conditionally. + if (scopeWithName.scope !== this) { + mergeConditional = true; + } + targetScope = scopeWithName.scope; + } + + // Determine the merged type. In the non-conditional case, we simply use the + // new type. In the conditional case, we may need to combine two types. + let newType = symbolToMerge.currentType; + let markTypeConditional = false; + if (mergeConditional) { + if (targetScope._isConditional) { + // If the target scope is conditional and we don't know the + // existing type to merge, mark the entry as "conditional" so it + // is properly merged later. + const targetSymbol = targetScope._symbolTable.get(name); + if (targetSymbol) { + newType = TypeUtils.combineTypes(newType, targetSymbol.currentType); + } else { + markTypeConditional = true; + } + } else { + let existingBinding = targetScope.lookUpSymbolRecursive(name); + if (existingBinding) { + newType = TypeUtils.combineTypes(newType, existingBinding.symbol.currentType); + } + } + } + + // Update the current type. + if (targetScope.setSymbolCurrentType(name, newType, + symbolToMerge.inferredType.getPrimarySourceId())) { + if (targetScope.getType() !== ScopeType.Temporary) { + modifiedType = true; + } + } + + // Merge the declarations. + if (symbolToMerge.declarations) { + symbolToMerge.declarations.forEach(decl => { + targetScope.addSymbolDeclaration(name, decl); + }); + } + + // Update the "conditional" flag if requested. + if (markTypeConditional) { + targetScope._symbolTable.get(name)!.isConditional = true; + } + } + + // If the scope we're merging isn't conditional, transfer + // the return and raises flags. + if (!scopeToMerge._isConditional) { + if (scopeToMerge.getAlwaysReturns()) { + this.setAlwaysReturns(); + } + + if (scopeToMerge.getAlwaysRaises()) { + this.setAlwaysRaises(); + } + } + + return modifiedType; + } + + // Combines a conditional scope with another conditional scope -- + // for example, an "if" scope with an "else" scope. + combineConditionalSymbolTable(scope: Scope) { + assert(scope._isConditional && this._isConditional); + + // Handle names that are in the second scope that are also in the first + // scope or are unique to the second scope. + scope._symbolTable.forEach((sourceSymbol, name) => { + const targetSymbol = this._symbolTable.get(name); + + if (targetSymbol) { + this.setSymbolCurrentType(name, + TypeUtils.combineTypes(targetSymbol.currentType, sourceSymbol.currentType), + sourceSymbol.inferredType.getPrimarySourceId()); + + if (sourceSymbol.declarations) { + sourceSymbol.declarations.forEach(decl => { + this.addSymbolDeclaration(name, decl); + }); + } + + if (sourceSymbol.isConditional) { + targetSymbol.isConditional = true; + } + } else { + let newSymbol = new Symbol(sourceSymbol.currentType, + sourceSymbol.inferredType.getPrimarySourceId()); + if (sourceSymbol.declarations) { + sourceSymbol.declarations.forEach(decl => { + newSymbol.addDeclaration(decl); + }); + } + newSymbol.isConditional = true; + this._symbolTable.set(name, newSymbol); + } + }); + + // Handle names that are only in the first scope. + this._symbolTable.forEach((symbol, name) => { + if (!scope._symbolTable.get(name)) { + symbol.isConditional = true; + } + }); + + this._returnType.addSources(scope._returnType); + } + + mergeReturnType(scopeToMerge: Scope): boolean { + return this._returnType.addSources(scopeToMerge._returnType); + } + + setAlwaysReturns() { + this._alwaysReturns = true; + } + + getAlwaysReturns() { + return this._alwaysReturns; + } + + setAlwaysRaises() { + this._alwaysRaises = true; + } + + getAlwaysRaises() { + return this._alwaysRaises; + } + + getAlwaysReturnsOrRaises() { + return this._alwaysReturns || this._alwaysRaises; + } + + incrementNestedTryDepth() { + this._nestedTryDepth++; + } + + decrementNestedTryDepth() { + assert(this._nestedTryDepth > 0); + this._nestedTryDepth--; + } + + getNestedTryDepth() { + return this._nestedTryDepth; + } + + getTypeConstraints() { + return this._typeConstraints; + } + + addTypeConstraint(constraint: TypeConstraint) { + assert(this._scopeType === ScopeType.Temporary); + assert(this._isConditional); + + this._typeConstraints.push(constraint); + } + + private _lookUpSymbolRecursiveInternal(name: string, isOutsideCallerModule: boolean): + SymbolWithScope | undefined { + // If we're searching outside of the original caller's module (global) scope, + // hide any names that are not meant to be visible to importers. + if (isOutsideCallerModule && this._hiddenNameMap[name]) { + return undefined; + } + + const symbol = this._symbolTable.get(name); + if (symbol) { + return { + symbol, + scope: this + }; + } + + if (this._parent) { + // If our recursion is about to take us outside the scope of the current + // module (i.e. into a built-in scope), indicate as such with the second parameter. + return this._parent._lookUpSymbolRecursiveInternal(name, + isOutsideCallerModule || this._scopeType === ScopeType.Global); + } + + return undefined; + } +} + +export interface SymbolWithScope { + symbol: Symbol; + scope: Scope; +} diff --git a/server/src/analyzer/semanticAnalyzer.ts b/server/src/analyzer/semanticAnalyzer.ts new file mode 100644 index 000000000..0128ff0d2 --- /dev/null +++ b/server/src/analyzer/semanticAnalyzer.ts @@ -0,0 +1,1073 @@ +/* +* semanticAnalyzer.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* A parse tree walker that performs general semantic analysis. It does +* this at the scope level. A scope in Python is defined by a module, +* class, function or lambda. +* The analyzer walks the parse tree by scopes starting at the module +* level. When a new scope is detected, it is pushed onto a list and +* analyzed separately at a later time. (The exception is a class scope, +* which is immediately analyzed.) Walking the tree in this manner +* simulates the order in which execution normally occurs in a Python +* file. The analyzer attempts to statically detect runtime errors that +* would be reported by the python interpreter when executing the code. +* This analyzer doesn't perform any static type checking. +*/ + +import * as assert from 'assert'; + +import { DiagnosticLevel } from '../common/configOptions'; +import { convertOffsetsToRange } from '../common/positionUtils'; +import { PythonVersion } from '../common/pythonVersion'; +import { TextRange } from '../common/textRange'; +import { AssignmentNode, ClassNode, DelNode, ExceptNode, ExpressionNode, ForNode, FunctionNode, + GlobalNode, IfNode, ImportAsNode, ImportFromAsNode, IndexExpressionNode, + LambdaNode, ListComprehensionForNode, ListComprehensionNode, ListNode, MemberAccessExpressionNode, + ModuleNameNode, ModuleNode, NameNode, NonlocalNode, ParameterCategory, ParameterNode, + RaiseNode, ReturnNode, StarExpressionNode, TryNode, + TupleExpressionNode, TypeAnnotationExpressionNode, WithNode } from '../parser/parseNodes'; +import { AnalyzerFileInfo } from './analyzerFileInfo'; +import { AnalyzerNodeInfo } from './analyzerNodeInfo'; +import { ExpressionUtils } from './expressionUtils'; +import { ImportType } from './importResult'; +import { DefaultTypeSourceId } from './inferredType'; +import { ParseTreeUtils } from './parseTreeUtils'; +import { ParseTreeWalker } from './parseTreeWalker'; +import { Scope, ScopeType } from './scope'; +import { Declaration, Symbol, SymbolCategory } from './symbol'; +import { TypeAnnotation } from './typeAnnotation'; +import { AnyType, ClassType, ClassTypeFlags, FunctionParameter, FunctionType, + FunctionTypeFlags, ModuleType, OverloadedFunctionType, Type, TypeCategory, UnboundType, UnknownType } from './types'; +import { TypeUtils } from './typeUtils'; + +type ScopedNode = ModuleNode | ClassNode | FunctionNode | LambdaNode; + +export abstract class SemanticAnalyzer extends ParseTreeWalker { + protected readonly _scopedNode: ScopedNode; + protected readonly _fileInfo: AnalyzerFileInfo; + + // A queue of scoped nodes that need to be analyzed. + protected _subscopesToAnalyze: SemanticAnalyzer[] = []; + + // The current scope in effect. This is either the base scope or a + // "temporary scope", used for analyzing conditional code blocks. Their + // contents are eventually merged in to the base scope. + protected _currentScope: Scope; + + constructor(node: ScopedNode, parentScope: Scope | undefined, fileInfo: AnalyzerFileInfo) { + super(); + + this._scopedNode = node; + this._fileInfo = fileInfo; + + // Allocate a new scope and associate it with the node + // we've been asked to analyze. + let scopeType = parentScope === undefined ? ScopeType.BuiltIn : + this._scopedNode instanceof ModuleNode ? + ScopeType.Global : ScopeType.Local; + this._currentScope = new Scope(scopeType, parentScope); + + // If this is the built-in scope, we need to hide symbols + // that are in the stub file but are not officially part of + // the built-in list of symbols in Python. + if (scopeType === ScopeType.BuiltIn) { + const namesToHide = ['sys', 'TypeVar', 'Iterator', 'Iterable', 'NoReturn', 'overload', 'Container', + 'Sequence', 'MutableSequence', 'Mapping', 'MutableMapping', 'Tuple', 'List', 'Any', 'Dict', 'Callable', 'Generic', + 'Set', 'AbstractSet', 'FrozenSet', 'MutableSet', 'Sized', 'Reversible', 'SupportsInt', 'SupportsFloat', 'SupportsAbs', + 'SupportsComplex', 'SupportsRound', 'IO', 'BinaryIO', 'Union', + 'ItemsView', 'KeysView', 'ValuesView', 'ByteString', 'Optional', 'AnyStr', 'Type', 'Text', + '_T', '_T_co', '_KT', '_VT', '_S', '_T1', '_T2', '_T3', '_T4', '_T5', '_TT' + ]; + namesToHide.forEach(name => { + this._currentScope.hideName(name); + }); + } + + AnalyzerNodeInfo.setScope(this._scopedNode, this._currentScope); + } + + // We separate analysis into two passes. The first happens immediately when + // the scope analyzer is created. The second happens after its parent scope + // has been fully analyzed. + abstract analyzeImmediate(): void; + abstract analyzeDeferred(): void; + + visitModule(node: ModuleNode): boolean { + // Tree walking should start with the children of + // the node, so we should never get here. + assert.fail('We should never get here'); + return false; + } + + visitModuleName(node: ModuleNameNode): boolean { + let importResult = AnalyzerNodeInfo.getImportInfo(node); + assert(importResult !== undefined); + if (importResult) { + if (!importResult.importFound) { + this._addDiagnostic(this._fileInfo.configOptions.reportMissingImports, + `Import '${ importResult.importName }' could not be resolved`, node); + } else if (importResult.importType === ImportType.ThirdParty) { + if (!importResult.isStubFile) { + this._addWarning(`Stub file not found for '${ importResult.importName }'`, node); + } + } + } + + return true; + } + + visitClass(node: ClassNode): boolean { + this.walkMultiple(node.decorators); + + let classFlags = ClassTypeFlags.None; + if (this._currentScope.getType() === ScopeType.BuiltIn || this._fileInfo.isTypingStubFile) { + classFlags |= ClassTypeFlags.BuiltInClass; + } + if (node.decorators.length > 0) { + classFlags |= ClassTypeFlags.HasDecorators; + } + + let classType = new ClassType(node.name.nameToken.value, classFlags); + + // Don't walk the arguments for stub files because of forward + // declarations. + if (!this._fileInfo.isStubFile) { + this.walkMultiple(node.arguments); + } + + let sawMetaclass = false; + node.arguments.forEach(arg => { + let argType: Type; + + if (this._fileInfo.isStubFile) { + // For stub files, we won't try to evaluate the type at this + // time because forward declarations are supported in stub files. + argType = UnknownType.create(); + } else { + argType = TypeAnnotation.getType(arg.valueExpression, + this._currentScope, this._fileInfo.diagnosticSink, false); + } + + let isMetaclass = false; + + if (arg.name) { + if (arg.name.nameToken.value === 'metaclass') { + if (sawMetaclass) { + this._addError(`Only one metaclass can be provided`, arg); + } + isMetaclass = true; + sawMetaclass = true; + } else { + this._addError(`Named parameter '${ arg.name.nameToken.value }' not supported for classes`, arg); + } + } + + if (!argType.isAny()) { + if (argType.category !== TypeCategory.Class) { + this._addError(`Argument to class must be a base class`, arg); + } + } + + classType.addBaseClass(argType, isMetaclass); + }); + + if (node.arguments.length === 0) { + let objectType = TypeAnnotation.getBuiltInType(this._currentScope, 'object'); + // Make sure we don't have 'object' derive from itself. Infinite + // recursion will result. + if (objectType !== classType) { + classType.addBaseClass(objectType, false); + } + } + + let declaration: Declaration = { + category: SymbolCategory.Class, + node: node.name, + path: this._fileInfo.filePath, + range: convertOffsetsToRange(node.name.start, node.name.end, this._fileInfo.lines) + }; + this._bindNameNodeToType(node.name, classType, true, declaration); + + AnalyzerNodeInfo.setExpressionType(node, classType); + AnalyzerNodeInfo.setExpressionType(node.name, classType); + + let analyzer = new ClassScopeAnalyzer(node, this._currentScope, classType, this._fileInfo); + this._queueSubScopeAnalyzer(analyzer); + + return false; + } + + visitFunction(node: FunctionNode): boolean { + const isMethod = ParseTreeUtils.isFunctionInClass(node); + + let functionFlags = FunctionTypeFlags.None; + if (node.decorators.length > 0) { + functionFlags |= FunctionTypeFlags.HasCustomDecorators; + } + if (isMethod) { + if (ParseTreeUtils.functionHasDecorator(node, 'staticmethod')) { + functionFlags &= ~FunctionTypeFlags.HasCustomDecorators; + } else if (ParseTreeUtils.functionHasDecorator(node, 'classmethod')) { + functionFlags |= FunctionTypeFlags.ClassMethod; + functionFlags &= ~FunctionTypeFlags.HasCustomDecorators; + } else { + functionFlags |= FunctionTypeFlags.InstanceMethod; + } + } + + let functionType = new FunctionType(functionFlags); + + this.walkMultiple(node.decorators); + node.parameters.forEach(param => { + if (param.defaultValue) { + this.walk(param.defaultValue); + } + + let typeParam: FunctionParameter = { + category: param.category, + name: param.name ? param.name.nameToken.value : undefined, + hasDefault: !!param.defaultValue, + type: UnknownType.create(), + node: param + }; + + functionType.addParameter(typeParam); + }); + + let decoratedType: Type = functionType; + let warnIfDuplicate = true; + + // Handle overload decorators specially. + let overloadedType: OverloadedFunctionType | undefined; + [overloadedType, warnIfDuplicate] = TypeAnnotation.getOverloadedFunctionType(node, + functionType, this._currentScope); + if (overloadedType) { + functionType.clearHasCustomDecoratorsFlag(); + decoratedType = overloadedType; + } else { + // Determine if the function is a property getter or setter. + if (ParseTreeUtils.isFunctionInClass(node)) { + functionType.clearHasCustomDecoratorsFlag(); + let propertyType = TypeAnnotation.getPropertyType(node, functionType, this._currentScope); + if (propertyType) { + decoratedType = propertyType; + + // Allow setters or deleters to replace the getter. + warnIfDuplicate = false; + } else { + this._validateMethod(node); + } + } + } + + let declaration: Declaration = { + category: isMethod ? SymbolCategory.Method : SymbolCategory.Function, + node: node.name, + path: this._fileInfo.filePath, + range: convertOffsetsToRange(node.name.start, node.name.end, this._fileInfo.lines) + }; + this._bindNameNodeToType(node.name, decoratedType, warnIfDuplicate, declaration); + + AnalyzerNodeInfo.setExpressionType(node, functionType); + AnalyzerNodeInfo.setExpressionType(node.name, functionType); + + // Find the function or module that contains this function and use its scope. + // We can't simply use this._currentScope because functions within a class use + // the scope of the containing function or module when they execute. + let functionOrModuleNode = node.parent; + while (functionOrModuleNode) { + if (functionOrModuleNode instanceof ModuleNode || + functionOrModuleNode instanceof FunctionNode) { + break; + } + + functionOrModuleNode = functionOrModuleNode.parent; + } + assert(functionOrModuleNode !== undefined); + + let functionOrModuleScope = AnalyzerNodeInfo.getScope(functionOrModuleNode!); + assert(functionOrModuleScope !== undefined); + + let analyzer = new FunctionScopeAnalyzer(node, functionOrModuleScope!, this._fileInfo); + this._queueSubScopeAnalyzer(analyzer); + return false; + } + + visitLambda(node: LambdaNode): boolean { + // Analyze the parameters in the context of the parent's scope + // before we add any names from the function's scope. + node.parameters.forEach(param => { + if (param.defaultValue) { + this.walk(param.defaultValue); + } + }); + + let analyzer = new LambdaScopeAnalyzer(node, this._currentScope, this._fileInfo); + this._queueSubScopeAnalyzer(analyzer); + + return false; + } + + visitFor(node: ForNode): boolean { + this.walk(node.sequenceExpression); + + // Populate the new scope with target parameters. + this._addNamedTarget(node.targetExpression); + + this.walk(node.targetExpression); + this.walk(node.forSuite); + + if (node.elseSuite) { + this.walk(node.elseSuite); + } + + return false; + } + + visitListComprehension(node: ListComprehensionNode): boolean { + // We need to "execute" the comprehension clauses first, even + // though they appear afterward in the syntax. We'll do so + // within a temporary scope so we can throw away the target + // when complete. + this._enterTemporaryScope(() => { + node.comprehensions.forEach(compr => { + if (compr instanceof ListComprehensionForNode) { + this.walk(compr.sequenceExpression); + + this._addNamedTarget(compr.targetExpression); + } else { + this.walk(compr.testExpression); + } + }); + + this.walk(node.baseExpression); + }); + + return false; + } + + visitIf(node: IfNode): boolean { + let ifScope: Scope | undefined; + let elseScope: Scope | undefined; + let isUnconditional = false; + + this.walk(node.testExpression); + + // Determine if the if condition is always true or always false. If so, + // we can treat either the if or the else clause as unconditional. + let constExprValue = ExpressionUtils.evaluateConstantExpression( + node.testExpression, this._fileInfo.executionEnvironment); + + // Push a temporary scope so we can track + // which variables have been assigned to conditionally. + ifScope = this._enterTemporaryScope(() => { + this.walk(node.ifSuite); + }, true, constExprValue === false); + + // Now handle the else statement if it's present. If there + // are chained "else if" statements, they'll be handled + // recursively here. + if (node.elseSuite) { + elseScope = this._enterTemporaryScope(() => { + this.walk(node.elseSuite!); + }, true, constExprValue === true); + } + + if (constExprValue !== undefined) { + isUnconditional = true; + if (constExprValue) { + elseScope = undefined; + } else { + ifScope = undefined; + } + } + + if (ifScope && ifScope.getAlwaysReturnsOrRaises() && elseScope && elseScope.getAlwaysReturnsOrRaises()) { + // If both an if and else clause are executed but they both return or raise an exception, + // mark the current scope as always returning or raising an exception. + if (ifScope.getAlwaysRaises() && elseScope.getAlwaysRaises()) { + this._currentScope.setAlwaysRaises(); + } else { + this._currentScope.setAlwaysReturns(); + } + } + + if (ifScope && ifScope.getAlwaysReturnsOrRaises()) { + ifScope = undefined; + isUnconditional = true; + } + + if (elseScope && elseScope.getAlwaysReturnsOrRaises()) { + elseScope = undefined; + isUnconditional = true; + } + + // Figure out how to combine the scopes. + if (ifScope && elseScope) { + // If both an "if" and an "else" scope exist, combine the names from both scopes. + ifScope.combineConditionalSymbolTable(elseScope); + this._currentScope.mergeSymbolTable(ifScope); + } else if (ifScope) { + // If there's only an "if" scope executed, mark all of its contents as conditional. + if (!isUnconditional) { + ifScope.markAllSymbolsConditional(); + } + this._currentScope.mergeSymbolTable(ifScope); + } else if (elseScope) { + // If there's only an "else" scope executed, mark all of its contents as conditional. + if (!isUnconditional) { + elseScope.markAllSymbolsConditional(); + } + this._currentScope.mergeSymbolTable(elseScope); + } + + return false; + } + + visitWith(node: WithNode): boolean { + node.withItems.forEach(item => { + this.walk(item.expression); + }); + + node.withItems.forEach(item => { + if (item.target) { + this._addNamedTarget(item.target); + } + }); + + this.walk(node.suite); + return false; + } + + visitReturn(node: ReturnNode): boolean { + this._currentScope.setAlwaysReturns(); + return true; + } + + visitRaise(node: RaiseNode): boolean { + if (this._currentScope.getNestedTryDepth() === 0) { + this._currentScope.setAlwaysRaises(); + } + return true; + } + + visitExcept(node: ExceptNode): boolean { + if (node.typeExpression) { + this.walk(node.typeExpression); + } + + let exceptScope: Scope | undefined; + this._enterTemporaryScope(() => { + if (node.typeExpression && node.name) { + this._currentScope.addUnboundSymbol(node.name.nameToken.value); + this._bindNameNodeToType(node.name, UnknownType.create()); + } + + exceptScope = this._enterTemporaryScope(() => { + this.walk(node.exceptSuite); + }); + }); + + this._currentScope.mergeSymbolTable(exceptScope!); + + return false; + } + + visitTry(node: TryNode): boolean { + this._currentScope.incrementNestedTryDepth(); + this.walk(node.trySuite); + this._currentScope.decrementNestedTryDepth(); + + // Wrap the except clauses in a conditional scope + // so we can throw away any names that are bound + // in this scope. + node.exceptClauses.forEach(exceptNode => { + this._enterTemporaryScope(() => { + this.walk(exceptNode); + }); + }); + + if (node.elseSuite) { + this.walk(node.elseSuite); + } + + if (node.finallySuite) { + this.walk(node.finallySuite); + } + + return false; + } + + visitAssignment(node: AssignmentNode): boolean { + if (!this._fileInfo.isStubFile) { + this.walk(node.rightExpression); + } + + // See if this is a simple or tuple assignment. + if (!this._addNamedTarget(node.leftExpression)) { + // Bind the name to an instance or class variable if appropriate. + this._bindPossibleMember(node.leftExpression); + } + + this.walk(node.leftExpression); + return false; + } + + visitMemberAccess(node: MemberAccessExpressionNode) { + this.walk(node.leftExpression); + + // Don't walk the member name. + return false; + } + + visitName(node: NameNode): boolean { + let valueWithScope = this._currentScope.lookUpSymbolRecursive(node.nameToken.value); + + if (!valueWithScope) { + this._addError(`'${ node.nameToken.value }' is not defined`, node.nameToken); + } else { + if (valueWithScope.symbol.currentType.isUnbound()) { + // It's possible that the name is unbound in the current scope + // at this point in the code but is available in an outer scope. + // Like this: + // a = 3 + // def foo(): + // b = a # 'a' is unbound locally but is available in outer scope + // a = None + let isReallyUnbound = true; + let parentScope = valueWithScope.scope.getParent(); + if (parentScope) { + valueWithScope = parentScope.lookUpSymbolRecursive(node.nameToken.value); + if (valueWithScope && !valueWithScope.symbol.currentType.isUnbound()) { + isReallyUnbound = false; + } + } + + // Don't report unbound error in stub files, which support out-of-order + // delcarations of classes. + if (isReallyUnbound && !this._fileInfo.isStubFile) { + this._addError(`'${ node.nameToken.value }' is not bound`, node.nameToken); + } + } else if (valueWithScope.symbol.currentType.isPossiblyUnbound()) { + this._fileInfo.diagnosticSink.addWarningWithTextRange( + `'${ node.nameToken.value }' may be unbound`, node.nameToken); + } + } + + return true; + } + + visitImportAs(node: ImportAsNode): boolean { + if (node.alias || node.module.nameParts.length > 0) { + let nameNode = node.alias ? node.alias : node.module.nameParts[0]; + this._bindNameNodeToType(nameNode, UnknownType.create(), !!node.alias); + } + return true; + } + + visitImportFromAs(node: ImportFromAsNode): boolean { + let nameNode = node.alias ? node.alias : node.name; + this._bindNameNodeToType(nameNode, UnknownType.create(), !!node.alias); + + return false; + } + + visitGlobal(node: GlobalNode): boolean { + node.nameList.forEach(name => { + let valueWithScope = this._currentScope.lookUpSymbolRecursive(name.nameToken.value); + if (!valueWithScope || valueWithScope.scope.getType() !== ScopeType.Global) { + this._addError(`No binding for global '${ name.nameToken.value }' found`, name); + } + }); + return true; + } + + visitNonlocal(node: NonlocalNode): boolean { + node.nameList.forEach(name => { + let valueWithScope = this._currentScope.lookUpSymbolRecursive(name.nameToken.value); + if (!valueWithScope || valueWithScope.scope.getType() !== ScopeType.Local) { + this._addError(`No binding for nonlocal '${ name.nameToken.value }' found`, name); + } + }); + return true; + } + + visitDel(node: DelNode): boolean { + this.walkMultiple(node.expressions); + + node.expressions.forEach(expr => { + if (expr instanceof NameNode) { + let symbolWithScope = this._currentScope.lookUpSymbolRecursive(expr.nameToken.value); + if (symbolWithScope) { + if (symbolWithScope.symbol.declarations) { + const category = symbolWithScope.symbol.declarations[0].category; + if (category === SymbolCategory.Function || category === SymbolCategory.Method) { + this._addError('Del should not be applied to function', expr); + } else if (category === SymbolCategory.Class) { + this._addError('Del should not be applied to class', expr); + } else if (category === SymbolCategory.Parameter) { + this._addError('Del should not be applied to parameter', expr); + } + } + } + + this._bindNameNodeToType(expr, UnboundType.create()); + } + }); + + return false; + } + + visitTypeAnnotation(node: TypeAnnotationExpressionNode): boolean { + // For now, the type is unknown. We'll fill in the type during + // the type hint phase. + this._addNamedTarget(node.valueExpression); + + // Don't walk the type annotation node in this pass. + this.walk(node.valueExpression); + + return false; + } + + protected _addNamesToScope(namesToAdd: string[]) { + // Add the names for this scope. They are initially unbound. + namesToAdd.forEach(name => { + // Don't overwrite the implicit bound names that have already + // been added to the scope. + if (!this._currentScope.lookUpSymbol(name)) { + this._currentScope.addUnboundSymbol(name); + } + }); + } + + protected _addParametersToScope(parameters: ParameterNode[]) { + parameters.forEach(param => { + if (param.name) { + if (param.name) { + this._bindNameNodeToType(param.name, UnknownType.create(), false); + } + } + }); + } + + // Analyzes the subscopes that are discovered during the first analysis pass. + protected _analyzeSubscopesDeferred() { + for (let subscope of this._subscopesToAnalyze) { + subscope.analyzeDeferred(); + } + + this._subscopesToAnalyze = []; + } + + protected _bindNameNodeToType(nameNode: NameNode, type: Type, warnIfDuplicate = false, + declaration?: Declaration) { + const nameValue = nameNode.nameToken.value; + + if (!this._currentScope.lookUpSymbol(nameValue)) { + this._currentScope.addUnboundSymbol(nameValue); + } + + if (warnIfDuplicate) { + let currentBinding = this._currentScope.lookUpSymbol(nameValue); + if (!currentBinding || !(currentBinding.currentType instanceof UnboundType)) { + this._fileInfo.diagnosticSink.addWarningWithTextRange( + `'${ nameValue }' is already defined`, nameNode); + } + } + + this._currentScope.setSymbolCurrentType(nameValue, type, + AnalyzerNodeInfo.getTypeSourceId(nameNode)); + if (declaration) { + this._currentScope.addSymbolDeclaration(nameValue, declaration); + } + } + + // This is a variant of _bindNameNodeToType that takes a raw name. It should be + // used only for implicit name binding. + protected _bindNameToType(nameValue: string, type: Type) { + if (!this._currentScope.lookUpSymbol(nameValue)) { + this._currentScope.addUnboundSymbol(nameValue); + } + + this._currentScope.setSymbolCurrentType(nameValue, type, DefaultTypeSourceId); + } + + protected _enterTemporaryScope(callback: () => void, isConditional?: boolean, + isNotExecuted?: boolean) { + let prevScope = this._currentScope; + let newScope = new Scope(ScopeType.Temporary, prevScope); + if (isConditional) { + newScope.setConditional(); + } + if (this._currentScope.isNotExecuted() || isNotExecuted) { + newScope.setIsNotExecuted(); + } + this._currentScope = newScope; + + callback(); + + this._currentScope = prevScope; + return newScope; + } + + private _bindPossibleMember(node: ExpressionNode) { + if (node instanceof MemberAccessExpressionNode) { + let targetNode = node.leftExpression; + if (targetNode instanceof NameNode) { + const nameValue = targetNode.nameToken.value; + + if (nameValue === 'self') { + this._bindMemberVariable(node.memberName, true); + } else if (nameValue === 'cls' || nameValue === 'metacls') { + this._bindMemberVariable(node.memberName, false); + } + } + } else if (node instanceof TupleExpressionNode) { + for (let expression of node.expressions) { + this._bindPossibleMember(expression); + } + } + } + + private _bindMemberVariable(memberNameNode: NameNode, isInstance: boolean) { + let classDef = ParseTreeUtils.getEnclosingClass(memberNameNode); + if (classDef) { + let classType = AnalyzerNodeInfo.getExpressionType(classDef); + if (classType && classType instanceof ClassType) { + let memberName = memberNameNode.nameToken.value; + let memberInfo = TypeUtils.lookUpClassMember(classType, memberName); + + if (!memberInfo) { + const memberFields = isInstance ? + classType.getInstanceFields() : classType.getClassFields(); + memberFields.set(memberName, + new Symbol(UnboundType.create(), DefaultTypeSourceId)); + } + } + } + } + + private _queueSubScopeAnalyzer(analyzer: SemanticAnalyzer) { + analyzer.analyzeImmediate(); + this._subscopesToAnalyze.push(analyzer); + } + + // Returns true if the node was handled by this method, false if it was + // of an unhandled type. + private _addNamedTarget(node: ExpressionNode): boolean { + if (node instanceof TupleExpressionNode) { + let isHandled = true; + node.expressions.forEach(expr => { + if (!this._addNamedTarget(expr)) { + isHandled = false; + } + }); + + return isHandled; + } else if (node instanceof ListNode) { + node.entries.forEach(expr => { + this._addNamedTarget(expr); + }); + + return true; + } else if (node instanceof TypeAnnotationExpressionNode) { + return this._addNamedTarget(node.valueExpression); + } else if (node instanceof StarExpressionNode) { + if (node.expression instanceof NameNode) { + this._bindNameNodeToType(node.expression, UnknownType.create()); + return true; + } else { + // TODO - need to handle this case. + this._addError( + 'Internal error: Unhandled target expression type', + node.expression); + } + } else if (node instanceof NameNode) { + this._bindNameNodeToType(node, UnknownType.create()); + return true; + } else if (node instanceof MemberAccessExpressionNode) { + // Nothing to do here. The target isn't introducing a new name. + } else if (node instanceof IndexExpressionNode) { + // Nothing to do here. The target isn't introducing a new name. + } else { + // We should never get here. + this._addError('Internal error: Unhandled target expression type', node); + } + + return false; + } + + // Performs checks on a function that is located within a class + // and has been determined not to be a property accessor. + private _validateMethod(node: FunctionNode) { + if (node.name && node.name.nameToken.value === '__new__') { + // __new__ overrides should have a "cls" parameter. + if (node.parameters.length === 0 || !node.parameters[0].name || + node.parameters[0].name.nameToken.value !== 'cls') { + this._addError( + `The __new__ override should take a 'cls' parameter`, + node.parameters.length > 0 ? node.parameters[0] : node.name); + } + } else if (node.name && node.name.nameToken.value === '__init_subclass__') { + // __init_subclass__ overrides should have a "cls" parameter. + if (node.parameters.length === 0 || !node.parameters[0].name || + node.parameters[0].name.nameToken.value !== 'cls') { + this._addError( + `The __init_subclass__ override should take a 'cls' parameter`, + node.parameters.length > 0 ? node.parameters[0] : node.name); + } + } else if (ParseTreeUtils.functionHasDecorator(node, 'staticmethod')) { + // Static methods should not have "self" or "cls" parameters. + if (node.parameters.length > 0 && node.parameters[0].name) { + let paramName = node.parameters[0].name.nameToken.value; + if (paramName === 'self' || paramName === 'cls') { + this._addError( + `Static methods should not take a 'self' or 'cls' parameter`, + node.parameters[0].name); + } + } + } else if (ParseTreeUtils.functionHasDecorator(node, 'classmethod')) { + let paramName = ''; + if (node.parameters.length > 0 && node.parameters[0].name) { + paramName = node.parameters[0].name.nameToken.value; + } + // Class methods should have a "cls" parameter. We'll exempt parameter + // names that start with an underscore since those are used in a few + // cases in the stdlib pyi files. + if (paramName !== 'cls') { + if (!this._fileInfo.isStubFile || (!paramName.startsWith('_') && paramName !== 'metacls')) { + this._addError( + `Class methods should take a 'cls' parameter`, + node.parameters.length > 0 ? node.parameters[0] : node.name); + } + } + } else { + // The presence of a decorator can change the behavior, so we need + // to back off from this check if a decorator is present. + if (node.decorators.length === 0) { + let paramName = ''; + let firstParamIsSimple = true; + if (node.parameters.length > 0) { + if (node.parameters[0].name) { + paramName = node.parameters[0].name.nameToken.value; + } + + if (node.parameters[0].category !== ParameterCategory.Simple) { + firstParamIsSimple = false; + } + } + + // Instance methods should have a "self" parameter. We'll exempt parameter + // names that start with an underscore since those are used in a few + // cases in the stdlib pyi files. + if (firstParamIsSimple && paramName !== 'self' && !paramName.startsWith('_')) { + // Special-case the ABCMeta.register method in abc.pyi. + const isRegisterMethod = this._fileInfo.isStubFile && + paramName === 'cls' && + node.name.nameToken.value === 'register'; + + if (!isRegisterMethod) { + this._addError( + `Instance methods should take a 'self' parameter`, + node.parameters.length > 0 ? node.parameters[0] : node.name); + } + } + } + } + } + + private _addDiagnostic(diagLevel: DiagnosticLevel, message: string, textRange: TextRange) { + if (diagLevel === 'error') { + this._addError(message, textRange); + } else if (diagLevel === 'warn') { + this._addWarning(message, textRange); + } + } + + private _addError(message: string, textRange: TextRange) { + // Don't emit error if the scope is guaranteed not to be executed. + if (!this._currentScope.isNotExecuted()) { + this._fileInfo.diagnosticSink.addErrorWithTextRange(message, textRange); + } + } + + private _addWarning(message: string, textRange: TextRange) { + // Don't emit error if the scope is guaranteed not to be executed. + if (!this._currentScope.isNotExecuted()) { + this._fileInfo.diagnosticSink.addWarningWithTextRange(message, textRange); + } + } +} + +export class ModuleScopeAnalyzer extends SemanticAnalyzer { + constructor(node: ModuleNode, fileInfo: AnalyzerFileInfo) { + super(node, fileInfo.builtinsScope, fileInfo); + } + + analyze() { + this.analyzeImmediate(); + this.analyzeDeferred(); + } + + analyzeImmediate() { + this._bindImplicitNames(); + let nameBindings = AnalyzerNodeInfo.getNameBindings(this._scopedNode); + assert(nameBindings !== undefined); + this._addNamesToScope(nameBindings!.getGlobalNames()); + + this.walkChildren(this._scopedNode); + + // Associate the module's scope with the module type. + let moduleType = new ModuleType(this._currentScope.getSymbolTable()); + AnalyzerNodeInfo.setExpressionType(this._scopedNode, moduleType); + } + + analyzeDeferred() { + // Analyze any sub-scopes that were discovered during the earlier pass. + this._analyzeSubscopesDeferred(); + } + + private _bindImplicitNames() { + // List taken from https://docs.python.org/3/reference/import.html#__name__ + this._bindNameToType('__name__', TypeAnnotation.getBuiltInObject(this._currentScope, 'str')); + this._bindNameToType('__loader__', AnyType.create()); + this._bindNameToType('__package__', TypeAnnotation.getBuiltInObject(this._currentScope, 'str')); + this._bindNameToType('__spec__', AnyType.create()); + this._bindNameToType('__path__', TypeAnnotation.getBuiltInObject(this._currentScope, 'str')); + this._bindNameToType('__file__', TypeAnnotation.getBuiltInObject(this._currentScope, 'str')); + this._bindNameToType('__cached__', TypeAnnotation.getBuiltInObject(this._currentScope, 'str')); + } +} + +export class ClassScopeAnalyzer extends SemanticAnalyzer { + private _classType: ClassType; + + constructor(node: ClassNode, parentScope: Scope, classType: ClassType, fileInfo: AnalyzerFileInfo) { + super(node, parentScope, fileInfo); + this._classType = classType; + } + + analyzeImmediate() { + this._bindImplicitNames(); + let nameBindings = AnalyzerNodeInfo.getNameBindings(this._scopedNode); + assert(nameBindings !== undefined); + this._addNamesToScope(nameBindings!.getLocalNames()); + + // Analyze the suite. + let classNode = this._scopedNode as ClassNode; + + // Create a temporary scope so we can track modifications to + // non-local names. + let suiteScope = this._enterTemporaryScope(() => { + this.walk(classNode.suite); + }); + this._currentScope.mergeSymbolTable(suiteScope); + + // Record the class fields for this class. + this._classType.setClassFields(this._currentScope.getSymbolTable()); + } + + analyzeDeferred() { + // Analyze any sub-scopes that were discovered during the earlier pass. + this._analyzeSubscopesDeferred(); + } + + private _bindImplicitNames() { + let classType = AnalyzerNodeInfo.getExpressionType(this._scopedNode); + assert(classType instanceof ClassType); + this._bindNameToType('__class__', classType!); + this._bindNameToType('__dict__', AnyType.create()); + this._bindNameToType('__name__', TypeAnnotation.getBuiltInObject(this._currentScope, 'str')); + } +} + +export class FunctionScopeAnalyzer extends SemanticAnalyzer { + constructor(node: FunctionNode, parentScope: Scope, fileInfo: AnalyzerFileInfo) { + super(node, parentScope, fileInfo); + } + + analyzeImmediate() { + this._bindImplicitNames(); + + // Functions don't get analyzed immediately. They are analyzed in a deferred manner. + } + + analyzeDeferred() { + let functionNode = this._scopedNode as FunctionNode; + + // Add the names for this scope. They are initially unbound. We + // do this because current versions of Python use static namespace + // resolution for functions. + let nameBindings = AnalyzerNodeInfo.getNameBindings(this._scopedNode); + assert(nameBindings !== undefined); + this._addNamesToScope(nameBindings!.getLocalNames()); + + // Bind the parameters to the local names. + this._addParametersToScope(functionNode.parameters); + + // Create a temporary scope so we can track modifications to + // non-local names. + let suiteScope = this._enterTemporaryScope(() => { + // Walk the statements that make up the function. + this.walk(functionNode.suite); + }); + this._currentScope.mergeSymbolTable(suiteScope); + + // Analyze any sub-scopes that were discovered during the earlier pass. + this._analyzeSubscopesDeferred(); + } + + private _bindImplicitNames() { + // List taken from https://docs.python.org/3/reference/datamodel.html + this._bindNameToType('__doc__', TypeAnnotation.getBuiltInObject(this._currentScope, 'str')); + this._bindNameToType('__name__', TypeAnnotation.getBuiltInObject(this._currentScope, 'str')); + if (this._fileInfo.executionEnvironment.pythonVersion >= PythonVersion.V33) { + this._bindNameToType('__qualname__', TypeAnnotation.getBuiltInObject(this._currentScope, 'str')); + } + this._bindNameToType('__module__', TypeAnnotation.getBuiltInObject(this._currentScope, 'str')); + this._bindNameToType('__defaults__', AnyType.create()); + this._bindNameToType('__code__', AnyType.create()); + this._bindNameToType('__globals__', AnyType.create()); + this._bindNameToType('__dict__', AnyType.create()); + this._bindNameToType('__closure__', AnyType.create()); + this._bindNameToType('__annotations__', AnyType.create()); + this._bindNameToType('__kwdefaults__', AnyType.create()); + } +} + +export class LambdaScopeAnalyzer extends SemanticAnalyzer { + constructor(node: LambdaNode, parentScope: Scope, fileInfo: AnalyzerFileInfo) { + super(node, parentScope, fileInfo); + } + + analyzeImmediate() { + // Lambdas don't get analyzed immediately. They are analyzed in a deferred manner. + } + + analyzeDeferred() { + let lambdaNode = this._scopedNode as LambdaNode; + + // Add the names for this scope. They are initially unbound. We + // do this because current versions of Python use static namespace + // resolution for functions. + let nameBindings = AnalyzerNodeInfo.getNameBindings(this._scopedNode); + assert(nameBindings !== undefined); + this._addNamesToScope(nameBindings!.getLocalNames()); + + // Bind the parameters to the local names. + this._addParametersToScope(lambdaNode.parameters); + + // Create a temporary scope so we can track modifications to + // non-local names. + let suiteScope = this._enterTemporaryScope(() => { + // Walk the expression that make up the lambda body. + this.walk(lambdaNode.expression); + }); + this._currentScope.mergeSymbolTable(suiteScope); + + // Analyze any sub-scopes that were discovered during the earlier pass. + this._analyzeSubscopesDeferred(); + } +} diff --git a/server/src/analyzer/service.ts b/server/src/analyzer/service.ts new file mode 100644 index 000000000..9437b2931 --- /dev/null +++ b/server/src/analyzer/service.ts @@ -0,0 +1,475 @@ +/* +* service.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* A persistent service that is able to analyze a collection of +* Python files. +*/ + +import * as fs from 'fs'; + +import { CommandLineOptions } from '../common/commandLineOptions'; +import { ConfigOptions } from '../common/configOptions'; +import { ConsoleInterface, StandardConsole } from '../common/console'; +import { DiagnosticTextPosition, DocumentTextRange } from '../common/diagnostic'; +import { FileDiagnostics } from '../common/diagnosticSink'; +import { combinePaths, ensureTrailingDirectorySeparator, forEachAncestorDirectory, + getDirectoryPath, getFileSystemEntries, isFile, normalizePath } from '../common/pathUtils'; +import { Duration, timingStats } from '../common/timing'; +import { Program } from './program'; + +const _defaultConfigFileName = 'pyrightconfig.json'; + +export interface AnalysisResults { + diagnostics: FileDiagnostics[]; + filesInProgram: number; + fatalErrorOccurred: boolean; + elapsedTime: number; +} + +export type AnalysisCompleteCallback = (results: AnalysisResults) => void; + +export class AnalyzerService { + private _program: Program; + private _configOptions: ConfigOptions; + private _executionRootPath: string; + private _console: ConsoleInterface; + private _sourceFileWatcher: fs.FSWatcher[] | undefined; + private _configFileWatcher: fs.FSWatcher | undefined; + private _onCompletionCallback: AnalysisCompleteCallback | undefined; + private _watchForChanges = false; + private _maxAnalysisTimeInMs: number | undefined; + private _analyzeTimer: any; + private _requireTrackedFileUpdate = true; + + constructor(console?: ConsoleInterface) { + this._console = console || new StandardConsole(); + this._program = new Program(this._console); + this._configOptions = new ConfigOptions(process.cwd()); + this._executionRootPath = '/'; + } + + setCompletionCallback(callback: AnalysisCompleteCallback | undefined): void { + this._onCompletionCallback = callback; + } + + setMaxAnalysisDuration(maxTimeInMs?: number) { + this._maxAnalysisTimeInMs = maxTimeInMs; + } + + setOptions(commandLineOptions: CommandLineOptions): void { + this._watchForChanges = !!commandLineOptions.watch; + this._configOptions = this._getConfigOptions(commandLineOptions); + + this._executionRootPath = normalizePath(combinePaths( + commandLineOptions.executionRoot, this._configOptions.projectRoot)); + this._applyConfigOptions(); + } + + setFileOpened(path: string, version: number | null, contents: string) { + this._program.setFileOpened(path, version, contents); + this._scheduleReanalysis(false); + } + + updateOpenFileContents(path: string, version: number | null, contents: string) { + this._program.setFileOpened(path, version, contents); + this._program.markFilesDirty([path]); + this._scheduleReanalysis(false); + } + + setFileClosed(path: string) { + let fileDiagnostics = this._program.setFileClosed(path); + this._reportDiagnosticsForRemovedFiles(fileDiagnostics); + this._scheduleReanalysis(false); + } + + markFilesChanged(fileList: string[]) { + this._program.markFilesDirty(fileList); + this._scheduleReanalysis(false); + } + + getDefinitionForPosition(filePath: string, position: DiagnosticTextPosition): + DocumentTextRange | undefined { + return this._program.getDefinitionForPosition(filePath, position); + } + + getHoverForPosition(filePath: string, position: DiagnosticTextPosition): + string | undefined { + return this._program.getHoverForPosition(filePath, position); + } + + test_getConfigOptions(commandLineOptions: CommandLineOptions): ConfigOptions { + return this._getConfigOptions(commandLineOptions); + } + + // Calculates the effective options based on the command-line options, + // an optional config file, and default values. + private _getConfigOptions(commandLineOptions: CommandLineOptions): ConfigOptions { + let projectRoot = commandLineOptions.executionRoot; + let configFilePath: string | undefined; + + if (commandLineOptions.fileSpecs && commandLineOptions.fileSpecs.length > 0) { + // If file specs were passed in to the command line, no config file + // will be used. In this case, all file specs are assumed to be + // relative to the current working directory. + if (commandLineOptions.configFilePath) { + this._console.log('Project can not be mixed with source files on a command line.'); + } + } else if (commandLineOptions.configFilePath) { + // If the config file path was specified, determine whether it's + // a directory (in which case the default config file name is assumed) + // or a file. + configFilePath = combinePaths(commandLineOptions.executionRoot, + normalizePath(commandLineOptions.configFilePath)); + if (!fs.existsSync(configFilePath)) { + this._console.log(`Configuration file not found at ${ configFilePath }.`); + configFilePath = commandLineOptions.executionRoot; + } else { + if (configFilePath.toLowerCase().endsWith('.json')) { + projectRoot = getDirectoryPath(configFilePath); + } else { + projectRoot = configFilePath; + configFilePath = combinePaths(configFilePath, _defaultConfigFileName); + if (!fs.existsSync(configFilePath)) { + this._console.log(`Configuration file not found at ${ configFilePath }.`); + configFilePath = undefined; + } + } + } + } else { + configFilePath = this._findConfigFile(projectRoot); + if (configFilePath) { + projectRoot = getDirectoryPath(configFilePath); + } else { + this._console.log(`No configuration file found.`); + configFilePath = undefined; + } + } + + let configOptions = new ConfigOptions(projectRoot); + + if (commandLineOptions.fileSpecs) { + configOptions.include.push(...commandLineOptions.fileSpecs); + } + + // If we found a config file, parse it to compute the effective options. + if (configFilePath) { + this._console.log(`Loading configuration file at ${ configFilePath }`); + let configJsonObj = this._parseConfigFile(configFilePath); + if (configJsonObj) { + configOptions.initializeFromJson(configJsonObj, this._console); + } + this._updateConfigFileWatcher(configFilePath); + } + + if (commandLineOptions.venvPath) { + configOptions.venvPath = commandLineOptions.venvPath; + } + + if (commandLineOptions.pythonPath) { + configOptions.pythonPath = commandLineOptions.pythonPath; + } + + if (commandLineOptions.typeshedPath) { + configOptions.typeshedPath = commandLineOptions.typeshedPath; + } + + return configOptions; + } + + private _findConfigFile(searchPath: string): string | undefined { + return forEachAncestorDirectory(searchPath, ancestor => { + const fileName = combinePaths(ancestor, _defaultConfigFileName); + return fs.existsSync(fileName) ? fileName : undefined; + }); + } + + private _parseConfigFile(configPath: string): any | undefined { + let configContents = ''; + let parseAttemptCount = 0; + + while (true) { + // Attempt to read the config file contents. + try { + configContents = fs.readFileSync(configPath, { encoding: 'utf8' }); + } catch { + this._console.log(`Config file "${ configPath }" could not be read.`); + return undefined; + } + + // Attempt to parse the config file. + let configObj: any; + let parseFailed = false; + try { + configObj = JSON.parse(configContents); + return configObj; + } catch { + parseFailed = true; + } + + if (!parseFailed) { + break; + } + + // If we attempt to read the config file immediately after it + // was saved, it may have been partially written when we read it, + // resulting in parse errors. We'll give it a little more time and + // try again. + if (parseAttemptCount++ >= 5) { + this._console.log(`Config file "${ configPath }" could not be parsed.`); + return undefined; + } + } + } + + test_getFileNamesFromFileSpecs(): string[] { + return this._getFileNamesFromFileSpecs(); + } + + private _getFileNamesFromFileSpecs(): string[] { + // Use a map to generate a list of unique files. + const fileMap: { [key: string]: string } = {}; + + timingStats.findFilesTime.timeOperation(() => { + let matchedFiles = this._matchFiles(this._configOptions.include, + this._configOptions.exclude, this._executionRootPath); + + for (const file of matchedFiles) { + fileMap[file] = file; + } + }); + + return Object.keys(fileMap); + } + + private _updateTrackedFileList() { + this._console.log(`Finding source files`); + let fileList = this._getFileNamesFromFileSpecs(); + + let fileDiagnostics = this._program.setTrackedFiles(fileList); + this._reportDiagnosticsForRemovedFiles(fileDiagnostics); + this._program.markAllFilesDirty(); + if (fileList.length === 0) { + this._console.log(`No source files found.`); + } else { + this._console.log(`Found ${ fileList.length } source files`); + } + + this._requireTrackedFileUpdate = false; + } + + private _isInExcludePath(path: string, excludePaths: string[]) { + return !!excludePaths.find(excl => path.startsWith(excl)); + } + + private _matchFiles(include: string[], exclude: string[], basePath: string): string[] { + let results: string[] = []; + + let visitDirectory = (absolutePath: string) => { + const includeFileRegex = /\.pyi?$/; + const { files, directories } = getFileSystemEntries(absolutePath); + + for (const file of files) { + const filePath = combinePaths(absolutePath, file); + + if (!this._isInExcludePath(filePath, excludePaths) && includeFileRegex.test(filePath)) { + results.push(filePath); + } + } + + for (const directory of directories) { + const dirPath = combinePaths(absolutePath, directory); + if (!this._isInExcludePath(absolutePath, excludePaths)) { + visitDirectory(dirPath); + } + } + }; + + // Build a normalized list of exclusion paths. + let excludePaths = exclude.map(excludeSpec => { + let absolutePath = normalizePath(combinePaths(basePath, excludeSpec)); + if (!absolutePath.endsWith('.py')) { + absolutePath = ensureTrailingDirectorySeparator(absolutePath); + } + return absolutePath; + }); + + include.forEach(includeSpec => { + let absolutePath = normalizePath(combinePaths(basePath, includeSpec)); + let foundFileSpec = false; + + if (!this._isInExcludePath(absolutePath, excludePaths) && fs.existsSync(absolutePath)) { + try { + let stat = fs.statSync(absolutePath); + if (stat.isFile()) { + results.push(absolutePath); + foundFileSpec = true; + } else if (stat.isDirectory()) { + visitDirectory(absolutePath); + foundFileSpec = true; + } + } catch { + // Ignore the exception. + } + } + + if (!foundFileSpec) { + this._console.log(`File or directory "${ includeSpec }" does not exist.`); + } + }); + + return results; + } + + private _updateSourceFileWatchers() { + if (this._sourceFileWatcher) { + this._sourceFileWatcher.forEach(watcher => { + watcher.close(); + }); + this._sourceFileWatcher = undefined; + } + + if (!this._watchForChanges) { + return; + } + + if (this._configOptions.include.length > 0) { + let fileList = this._configOptions.include.map(spec => { + return combinePaths(this._executionRootPath, spec); + }); + + this._sourceFileWatcher = fileList.map(fileSpec => { + return fs.watch(fileSpec, { recursive: true }, (event, fileName) => { + if (event === 'change') { + let filePath = fileSpec; + if (!isFile(filePath)) { + filePath = combinePaths(fileSpec, fileName); + } + this._program.markFilesDirty([filePath]); + this._scheduleReanalysis(false); + } else if (event === 'rename') { + this._scheduleReanalysis(true); + } + }); + }); + } + } + + private _updateConfigFileWatcher(configFilePath: string) { + if (this._configFileWatcher) { + this._configFileWatcher.close(); + this._configFileWatcher = undefined; + } + + if (this._watchForChanges) { + this._configFileWatcher = fs.watch(configFilePath, {}, (event, fileName) => { + if (event === 'change') { + this._reloadConfigFile(configFilePath); + } + }); + } + } + + private _reloadConfigFile(configFilePath: string) { + this._console.log(`Found configuration file at ${ configFilePath }`); + let configJsonObj = this._parseConfigFile(configFilePath); + if (configJsonObj) { + this._configOptions.initializeFromJson(configJsonObj, this._console); + } + + this._applyConfigOptions(); + } + + private _applyConfigOptions() { + this._updateSourceFileWatchers(); + this._updateTrackedFileList(); + this._scheduleReanalysis(false); + } + + private _clearReanalysisTimer() { + if (this._analyzeTimer) { + clearTimeout(this._analyzeTimer); + this._analyzeTimer = undefined; + } + } + + private _scheduleReanalysis(requireTrackedFileUpdate: boolean) { + if (requireTrackedFileUpdate) { + this._requireTrackedFileUpdate = true; + } + + // Remove any existing analysis timer. + this._clearReanalysisTimer(); + + // Schedule a new timer. + this._analyzeTimer = setTimeout(() => { + if (this._requireTrackedFileUpdate) { + this._updateTrackedFileList(); + } + + let moreToAnalyze = this._reanalyze(); + this._analyzeTimer = undefined; + + if (moreToAnalyze) { + this._scheduleReanalysis(false); + } + }, 0); + } + + // Performs analysis for a while (up to this._maxAnalysisTimeInMs) before + // returning some results. Return value indicates whether more analysis is + // required to finish the entire program. + private _reanalyze(): boolean { + let moreToAnalyze = false; + + try { + let duration = new Duration(); + moreToAnalyze = this._program.analyze(this._configOptions, this._maxAnalysisTimeInMs); + + let results: AnalysisResults = { + diagnostics: this._program.getDiagnostics(this._configOptions), + filesInProgram: this._program.getFileCount(), + fatalErrorOccurred: false, + elapsedTime: duration.getDurationInSeconds() + }; + + let fileCount = results.diagnostics.length; + if (fileCount > 0) { + this._console.log( + `Analyzed ${ fileCount } file${ fileCount === 1 ? '' : 's' } ` + + `in ${ results.elapsedTime }sec`); + + if (this._onCompletionCallback) { + this._onCompletionCallback(results); + } + } + } catch (err) { + this._console.log('Error performing analysis: ' + JSON.stringify(err)); + + if (this._onCompletionCallback) { + this._onCompletionCallback({ + diagnostics: [], + filesInProgram: 0, + fatalErrorOccurred: true, + elapsedTime: 0 + }); + } + } + + return moreToAnalyze; + } + + private _reportDiagnosticsForRemovedFiles(fileDiags: FileDiagnostics[]) { + if (fileDiags.length > 0) { + if (this._onCompletionCallback) { + this._onCompletionCallback({ + diagnostics: fileDiags, + filesInProgram: 0, + fatalErrorOccurred: false, + elapsedTime: 0 + }); + } + } + } +} diff --git a/server/src/analyzer/sourceFile.ts b/server/src/analyzer/sourceFile.ts new file mode 100644 index 000000000..b822466dd --- /dev/null +++ b/server/src/analyzer/sourceFile.ts @@ -0,0 +1,493 @@ +/* +* sourceFile.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Class that represents a source file. +*/ + +import * as assert from 'assert'; +import * as fs from 'fs'; + +import { ConfigOptions, ExecutionEnvironment } from '../common/configOptions'; +import { ConsoleInterface, StandardConsole } from '../common/console'; +import { Diagnostic, DiagnosticCategory, DiagnosticTextPosition, DocumentTextRange } from '../common/diagnostic'; +import { DiagnosticSink, TextRangeDiagnosticSink } from '../common/diagnosticSink'; +import { getFileName } from '../common/pathUtils'; +import { timingStats } from '../common/timing'; +import { ModuleNameNode, ModuleNode } from '../parser/parseNodes'; +import { ParseOptions, Parser, ParseResults } from '../parser/parser'; +import { AnalyzerFileInfo, ImportMap } from './analyzerFileInfo'; +import { AnalyzerNodeInfo } from './analyzerNodeInfo'; +import { DefinitionProvider } from './definitionProvider'; +import { HoverProvider } from './hoverProvider'; +import { ImportResolver } from './importResolver'; +import { ImportResult } from './importResult'; +import { ParseTreeCleanerWalker } from './parseTreeCleaner'; +import { PostParseWalker } from './postParseWalker'; +import { Scope } from './scope'; +import { ModuleScopeAnalyzer } from './semanticAnalyzer'; +import { TypeAnalyzer } from './typeAnalyzer'; + +export enum AnalysisPhase { + Parse = 0, + SemanticAnalysis = 1, + TypeAnalysis = 2, + + FirstAnalysisPhase = SemanticAnalysis, + LastAnalysisPhase = TypeAnalysis +} + +// Represents a pending or completed parse or analysis operation. +export interface AnalysisJob { + fileContentsVersion: number; + nextPhaseToRun: AnalysisPhase; + parseTreeNeedsCleaning: boolean; + parseResults?: ParseResults; + + parseDiagnostics: Diagnostic[]; + semanticAnalysisDiagnostics: Diagnostic[]; + typeHintAnalysisDiagnostics: Diagnostic[]; + typeAnalysisLastPassDiagnostics: Diagnostic[]; + typeAnalysisFinalDiagnostics: Diagnostic[]; + + typeAnalysisPassNumber: number; + isTypeAnalysisPassNeeded: boolean; + isTypeAnalysisFinalized: boolean; + + imports?: ImportResult[]; + builtinsImport?: ImportResult; +} + +export class SourceFile { + // Console interface to use for debugging. + private _console: ConsoleInterface; + + // File path on disk. + private readonly _filePath: string; + + // True if file is a type-hint (.pyi) file versus a python + // (.py) file. + private readonly _isStubFile: boolean; + + // True if the file is a typeshed stub file. + private readonly _isTypeshedStubFile: boolean; + + // True if the file is the "typing.pyi" file, which needs + // special-case handling. + private readonly _isTypingStubFile: boolean; + + // Latest analysis job that has completed at least one phase + // of anlaysis. + private _analysisJob: AnalysisJob = { + fileContentsVersion: -1, + nextPhaseToRun: AnalysisPhase.SemanticAnalysis, + parseTreeNeedsCleaning: false, + + parseDiagnostics: [], + semanticAnalysisDiagnostics: [], + typeHintAnalysisDiagnostics: [], + typeAnalysisLastPassDiagnostics: [], + typeAnalysisFinalDiagnostics: [], + + typeAnalysisPassNumber: 1, + isTypeAnalysisPassNeeded: true, + isTypeAnalysisFinalized: false + }; + + // Number that is incremented every time the diagnostics + // are updated. + private _diagnosticVersion = 0; + + // Generation count of the file contents. When the contents + // change, this is incremented. + private _fileContentsVersion = 0; + + // Client's version of the file. Null implies that contents + // need to be read from disk. + private _clientVersion: number | null = null; + + // In-memory contents if sent from the language client. If + // clientVersion is null, we'll ignore this and read the + // contents from disk. + private _fileContents: string | undefined; + + constructor(filePath: string, isTypeshedStubFile: boolean, console?: ConsoleInterface) { + this._console = console || new StandardConsole(); + if (this._console) { + // This is here to prevent the compiler from complaining + // about an unused instance variable. + } + this._filePath = filePath; + this._isStubFile = filePath.endsWith('.pyi'); + this._isTypeshedStubFile = isTypeshedStubFile; + const fileName = getFileName(filePath); + this._isTypingStubFile = this._isStubFile && ( + fileName === 'typing.pyi' || fileName === 'typing_extensions.pyi'); + } + + getFilePath(): string { + return this._filePath; + } + + getDiagnosticVersion(): number { + return this._diagnosticVersion; + } + + // Returns a list of cached diagnostics from the latest analysis job. + // If the prevVersion is specified, the method returns undefined if + // the diagnostics haven't changed. + getDiagnostics(options: ConfigOptions, prevDiagnosticVersion?: number): Diagnostic[] | undefined { + if (this._diagnosticVersion === prevDiagnosticVersion) { + return undefined; + } + + let diagList: Diagnostic[] = []; + diagList = diagList.concat( + this._analysisJob.parseDiagnostics, + this._analysisJob.semanticAnalysisDiagnostics, + this._analysisJob.typeHintAnalysisDiagnostics, + this._analysisJob.typeAnalysisFinalDiagnostics); + + if (this._isTypeshedStubFile) { + if (options.reportTypeshedErrors === 'none') { + return undefined; + } else if (options.reportTypeshedErrors === 'warn') { + // Convert all the errors to warnings. + diagList = diagList.map(diag => { + if (diag.category === DiagnosticCategory.Error) { + return new Diagnostic(DiagnosticCategory.Warning, + diag.message, diag.range); + } + return diag; + }); + } + } + + return diagList; + } + + getImports(): ImportResult[] { + return this._analysisJob.imports || []; + } + + getBuiltinsImport(): ImportResult | undefined { + return this._analysisJob.builtinsImport; + } + + markDirty(): void { + this._fileContentsVersion++; + this._analysisJob.isTypeAnalysisFinalized = false; + this._analysisJob.nextPhaseToRun = AnalysisPhase.SemanticAnalysis; + } + + markReanalysisRequired(): void { + // Keep the parse info, but reset the analysis to the beginning. + this._analysisJob.nextPhaseToRun = AnalysisPhase.SemanticAnalysis; + this._analysisJob.parseTreeNeedsCleaning = true; + this._analysisJob.isTypeAnalysisFinalized = false; + } + + setClientVersion(version: number | null, contents: string): void { + this._clientVersion = version; + + if (version === null) { + this._fileContents = undefined; + } else { + if (this._fileContents !== undefined) { + if (this._fileContents !== contents) { + this.markDirty(); + } + } + + this._fileContents = contents; + } + } + + prepareForClose() { + // Nothing to do currently. + } + + isParseRequired() { + return this._analysisJob.fileContentsVersion !== this._fileContentsVersion; + } + + isSemanticAnalysisRequired() { + return this._analysisJob.nextPhaseToRun <= AnalysisPhase.SemanticAnalysis; + } + + isTypeAnalysisRequired() { + // If the analysis is complete, no more analysis is required. + if (this._analysisJob.nextPhaseToRun < AnalysisPhase.TypeAnalysis || + this._analysisJob.isTypeAnalysisPassNeeded) { + return true; + } + + return false; + } + + isAnalysisFinalized() { + return !this.isTypeAnalysisRequired() && this._analysisJob.isTypeAnalysisFinalized; + } + + getParseResults(): ParseResults | undefined { + if (!this.isParseRequired()) { + return this._analysisJob.parseResults; + } + + return undefined; + } + + // Parse the file and update the state. Callers should wait for completion + // (or at least cancel) prior to calling again. It returns true if a parse + // was required and false if the parse information was up to date already. + parse(configOptions: ConfigOptions): boolean { + // If the file is already parsed, we can skip. + if (!this.isParseRequired()) { + return false; + } + + let diagSink = new DiagnosticSink(); + let fileContents = this._fileContents; + if (this._clientVersion === null) { + try { + timingStats.readFileTime.timeOperation(() => { + // Read the file's contents. + fileContents = fs.readFileSync(this._filePath, { encoding: 'utf8' }); + }); + } catch (error) { + diagSink.addError(`Source file could not be read`); + fileContents = ''; + } + } + + // Use the configuration options to determine the environment in which + // this source file will be executed. + let execEnvironment = configOptions.findExecEnvironment(this._filePath); + + let parseOptions = new ParseOptions(); + if (this._filePath.endsWith('pyi')) { + parseOptions.isStubFile = true; + } + parseOptions.pythonVersion = execEnvironment.pythonVersion; + + try { + // Parse the token stream, building the abstract syntax tree. + let parser = new Parser(); + let parseResults = parser.parseSourceFile(fileContents!, parseOptions, diagSink); + + // Convert the diagnostic sink into one that knows how to convert + // to line numbers. + let textRangeDiagSink = new TextRangeDiagnosticSink(parseResults.lines, diagSink.diagnostics); + + // Fill in the parent links and get the list of imports. + let walker = new PostParseWalker(textRangeDiagSink, parseResults.parseTree, this._isStubFile); + timingStats.postParseWalkerTime.timeOperation(() => { + walker.analyze(); + }); + + // Save information in the analysis job. + this._analysisJob.fileContentsVersion = this._fileContentsVersion; + this._analysisJob.nextPhaseToRun = AnalysisPhase.SemanticAnalysis; + this._analysisJob.parseTreeNeedsCleaning = false; + this._analysisJob.parseResults = parseResults; + [this._analysisJob.imports, this._analysisJob.builtinsImport] = + this._resolveImports(parseResults.parseTree, + walker.getImportedModules(), configOptions, execEnvironment); + + this._analysisJob.parseDiagnostics = diagSink.diagnostics; + this._diagnosticVersion++; + } catch (e) { + let message: string; + if (e instanceof Error) { + message = e.message; + } else { + message = JSON.stringify(e); + } + + this._console.log( + `An internal error occurred while parsing ${ this.getFilePath() }: ` + message); + } + + return true; + } + + getDefinitionForPosition(position: DiagnosticTextPosition): DocumentTextRange | undefined { + // If we have no completed analysis job, there's nothing to do. + if (!this._analysisJob.parseResults) { + return; + } + + return DefinitionProvider.getDefinitionForPosition( + this._analysisJob.parseResults, position); + } + + getHoverForPosition(position: DiagnosticTextPosition): string | undefined { + // If we have no completed analysis job, there's nothing to do. + if (!this._analysisJob.parseResults) { + return; + } + + return HoverProvider.getHoverForPosition( + this._analysisJob.parseResults, position); + } + + setTypeAnalysisPassNeeded() { + this._analysisJob.isTypeAnalysisPassNeeded = true; + this._analysisJob.isTypeAnalysisFinalized = false; + } + + doSemanticAnalysis(configOptions: ConfigOptions, builtinsScope?: Scope) { + assert(!this.isParseRequired()); + assert(this.isSemanticAnalysisRequired()); + assert(this._analysisJob.parseResults); + assert(this._analysisJob.nextPhaseToRun === AnalysisPhase.SemanticAnalysis); + + const fileInfo = this._buildFileInfo(configOptions, undefined, builtinsScope); + + try { + this._cleanParseTreeIfRequired(); + + // Perform semantic analysis. + let scopeAnalyzer = new ModuleScopeAnalyzer( + this._analysisJob.parseResults!.parseTree, fileInfo); + timingStats.semanticAnalyzerTime.timeOperation(() => { + scopeAnalyzer.analyze(); + this._analysisJob.semanticAnalysisDiagnostics = fileInfo.diagnosticSink.diagnostics; + this._analysisJob.nextPhaseToRun = AnalysisPhase.TypeAnalysis; + this._diagnosticVersion++; + }); + + // Prepare for the next stage of the anlaysis. + this._analysisJob.typeAnalysisPassNumber = 1; + this._analysisJob.isTypeAnalysisPassNeeded = true; + this._analysisJob.isTypeAnalysisFinalized = false; + this._analysisJob.nextPhaseToRun = AnalysisPhase.TypeAnalysis; + } catch (e) { + let message: string; + if (e instanceof Error) { + message = e.message; + } else { + message = JSON.stringify(e); + } + + this._console.log( + `An internal error occurred while analyzing ${ this.getFilePath() }: ` + message); + } + } + + doTypeAnalysis(configOptions: ConfigOptions, importMap: ImportMap) { + assert(!this.isParseRequired()); + assert(!this.isSemanticAnalysisRequired()); + assert(this.isTypeAnalysisRequired()); + assert(this._analysisJob.parseResults); + assert(this._analysisJob.nextPhaseToRun === AnalysisPhase.TypeAnalysis); + + const fileInfo = this._buildFileInfo(configOptions, importMap, undefined); + + try { + // Perform static type analysis. + let typeAnalyzer = new TypeAnalyzer(this._analysisJob.parseResults!.parseTree, + fileInfo, this._analysisJob.typeAnalysisPassNumber); + this._analysisJob.typeAnalysisPassNumber++; + + timingStats.typeAnalyzerTime.timeOperation(() => { + // Repeatedly call the analyzer until everything converges. + this._analysisJob.isTypeAnalysisPassNeeded = typeAnalyzer.analyze(); + this._analysisJob.typeAnalysisLastPassDiagnostics = fileInfo.diagnosticSink.diagnostics; + }); + } catch (e) { + let message: string; + if (e instanceof Error) { + message = e.message; + } else { + message = JSON.stringify(e); + } + + this._console.log( + `An internal error occurred while analyzing ${ this.getFilePath() }: ` + message); + } + } + + // This method should be called once type analysis has completed for + // this file and all of its dependent files. + finalizeAnalysis() { + assert(!this.isTypeAnalysisRequired()); + + // Mark the type analysis as final. + this._analysisJob.isTypeAnalysisFinalized = true; + + // Finalize the diagnostics from the last pass of type analysis + // so they become visible. + this._analysisJob.typeAnalysisFinalDiagnostics = + this._analysisJob.typeAnalysisLastPassDiagnostics; + this._analysisJob.typeAnalysisLastPassDiagnostics = []; + this._diagnosticVersion++; + } + + private _buildFileInfo(configOptions: ConfigOptions, importMap?: ImportMap, builtinsScope?: Scope) { + assert(this._analysisJob.parseResults !== undefined); + let analysisDiagnostics = new TextRangeDiagnosticSink(this._analysisJob.parseResults!.lines); + + let fileInfo: AnalyzerFileInfo = { + importMap: importMap || {}, + builtinsScope, + diagnosticSink: analysisDiagnostics, + executionEnvironment: configOptions.findExecEnvironment(this._filePath), + configOptions, + lines: this._analysisJob.parseResults!.lines, + filePath: this._filePath, + isStubFile: this._isStubFile, + isTypingStubFile: this._isTypingStubFile + }; + return fileInfo; + } + + private _cleanParseTreeIfRequired() { + if (this._analysisJob && this._analysisJob.parseResults) { + if (this._analysisJob.parseTreeNeedsCleaning) { + let cleanerWalker = new ParseTreeCleanerWalker( + this._analysisJob.parseResults.parseTree); + cleanerWalker.clean(); + this._analysisJob.parseTreeNeedsCleaning = false; + } + } + } + + private _resolveImports(moduleNode: ModuleNode, moduleNameNodes: ModuleNameNode[], + configOptions: ConfigOptions, execEnv: ExecutionEnvironment): + [ImportResult[], ImportResult?] { + let imports: ImportResult[] = []; + + let resolver = new ImportResolver(this._filePath, configOptions, execEnv); + + // Always include an implicit import of the builtins module. + let builtinsImportResult: ImportResult | undefined = resolver.resolveImport({ + leadingDots: 0, + nameParts: ['builtins'] + }); + + // Avoid importing builtins from the builtins.pyi file itself. + if (builtinsImportResult.resolvedPaths.length === 0 || + builtinsImportResult.resolvedPaths[0] !== this.getFilePath()) { + imports.push(builtinsImportResult); + + // Associate the builtins import with the module node so we can find it later. + AnalyzerNodeInfo.setImportInfo(moduleNode, builtinsImportResult); + } else { + builtinsImportResult = undefined; + } + + for (let moduleNameNode of moduleNameNodes) { + let importResult = resolver.resolveImport({ + leadingDots: moduleNameNode.leadingDots, + nameParts: moduleNameNode.nameParts.map(p => p.nameToken.value) + }); + imports.push(importResult); + + AnalyzerNodeInfo.setImportInfo(moduleNameNode, importResult); + } + + return [imports, builtinsImportResult]; + } +} diff --git a/server/src/analyzer/symbol.ts b/server/src/analyzer/symbol.ts new file mode 100644 index 000000000..4a5aa71e7 --- /dev/null +++ b/server/src/analyzer/symbol.ts @@ -0,0 +1,103 @@ +/* +* symbol.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Represents an association between a name and the type +* (or multiple types) that the symbol is associated with +* in the program. +*/ + +import { DiagnosticTextRange } from '../common/diagnostic'; +import StringMap from '../common/stringMap'; +import { ParseNode } from '../parser/parseNodes'; +import { InferredType, TypeSourceId } from './inferredType'; +import { Type, TypeCategory } from './types'; + +export enum SymbolCategory { + Variable, + Import, + Parameter, + Function, + Method, + Class, + Module +} + +export interface Declaration { + // Category of this symbol (function, variable, etc.). + // Used by hover provider to display helpful text. + category: SymbolCategory; + + // The node that contains the definition. + node: ParseNode; + + // Declared type (if specified) of the symbol. + declaredType?: Type; + + // The file and range within that file that + // contains the declaration. + path: string; + range: DiagnosticTextRange; +} + +export class Symbol { + // Inferred type of the symbol. + inferredType: InferredType = new InferredType(); + + // Information about the node that declared the value - + // i.e. where the editor will take the user if "show definition" + // is selected. Multiple declarations can exist for variables, + // properties, and functions (in the case of @overload). + declarations?: Declaration[]; + + // Type currently bound to the name as analyzer progresses through + // the code flow. Can be UnboundType. + currentType: Type; + + // Indicates that the type is conditionally bound (e.g. inside of an + // if statement). Used during analysis to determine how and whether to + // merge types. For example, if both parts of an if/else statement + // conditionally set a value, the combination of the two is unconditional. + // This is used only in temporary scopes. + isConditional?: boolean; + + constructor(currentType: Type, typeSourceId: TypeSourceId) { + this.currentType = currentType; + this.addInferredType(currentType, typeSourceId); + } + + // Returns true if inferred type changed. + setCurrentType(currentType: Type, typeSourceId: TypeSourceId): boolean { + this.currentType = currentType; + return this.addInferredType(currentType, typeSourceId); + } + + // Returns true if inferred type changed. + addInferredType(type: Type, typeSourceId: TypeSourceId): boolean { + if (type.category !== TypeCategory.Unbound) { + return this.inferredType.addSource(type, typeSourceId); + } + + return false; + } + + addDeclaration(declaration: Declaration) { + if (this.declarations) { + // See if this node was already identified as a declaration. If so, + // replace it. Otherwise, add it as a new declaration to the end of + // the list. + let declIndex = this.declarations.findIndex(decl => decl.node === declaration.node); + if (declIndex >= 0) { + this.declarations[declIndex] = declaration; + } else { + this.declarations.push(declaration); + } + } else { + this.declarations = [declaration]; + } + } +} + +// Maps names to symbol information. +export class SymbolTable extends StringMap {} diff --git a/server/src/analyzer/typeAnalyzer.ts b/server/src/analyzer/typeAnalyzer.ts new file mode 100644 index 000000000..e13e65a61 --- /dev/null +++ b/server/src/analyzer/typeAnalyzer.ts @@ -0,0 +1,2185 @@ +/* +* typeAnalyzer.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* A parse tree walker that performs static type checking. It assumes +* that the semanticAnalyzer and typeHintAnalyzer have already run +* and added information to the parse nodes. +*/ + +import * as assert from 'assert'; + +import { TextRangeDiagnosticSink } from '../common/diagnosticSink'; +import { convertOffsetsToRange } from '../common/positionUtils'; +import StringMap from '../common/stringMap'; +import { TextRange } from '../common/textRange'; +import { ArgumentCategory, AssignmentNode, AwaitExpressionNode, BinaryExpressionNode, CallExpressionNode, + ClassNode, ConditionalExpressionNode, ConstantNode, DictionaryNode, EllipsisNode, ExceptNode, + ExpressionNode, ForNode, FunctionNode, IfNode, ImportAsNode, ImportFromNode, + IndexExpressionNode, LambdaNode, ListComprehensionForNode, ListComprehensionNode, + ListNode, MemberAccessExpressionNode, ModuleNode, NameNode, NumberNode, ParameterCategory, + ParseNode, RaiseNode, ReturnNode, SetNode, SliceExpressionNode, + StarExpressionNode, StringNode, TryNode, TupleExpressionNode, + TypeAnnotationExpressionNode, UnaryExpressionNode, WithNode, + YieldExpressionNode, YieldFromExpressionNode } from '../parser/parseNodes'; +import { KeywordType, OperatorType, QuoteTypeFlags } from '../parser/tokenizerTypes'; +import { AnalyzerFileInfo } from './analyzerFileInfo'; +import { AnalyzerNodeInfo } from './analyzerNodeInfo'; +import { ExpressionUtils } from './expressionUtils'; +import { ImportResult } from './importResult'; +import { DefaultTypeSourceId, TypeSourceId } from './inferredType'; +import { ParseTreeUtils } from './parseTreeUtils'; +import { ParseTreeWalker } from './parseTreeWalker'; +import { Scope, ScopeType } from './scope'; +import { Declaration, Symbol, SymbolCategory, SymbolTable } from './symbol'; +import { TypeAnnotation } from './typeAnnotation'; +import { TypeConstraint, TypeConstraintBuilder, TypeConstraintResults } from './typeConstraint'; +import { AnyType, ClassType, ClassTypeFlags, EllipsisType, FunctionType, + FunctionTypeFlags, ModuleType, NoneType, ObjectType, + OverloadedFunctionType, PropertyType, TupleType, Type, TypeCategory, TypeVarType, UnboundType, UnionType, UnknownType } from './types'; +import { TypeUtils } from './typeUtils'; + +interface ParamAssignmentInfo { + argsNeeded: number; + argsReceived: number; +} + +interface EnumClassInfo { + enumClass: ClassType; + valueType: Type; +} + +export class TypeAnalyzer extends ParseTreeWalker { + private readonly _moduleNode: ModuleNode; + private readonly _fileInfo: AnalyzerFileInfo; + private _currentScope: Scope; + + // Indicates where there was a change in the type analysis + // the last time analyze() was called. Callers should repeatedly + // call analyze() until this returns false. + private _didAnalysisChange: boolean; + + // Analysis verison is incremented each time an analyzer pass + // is performed. It allows the code to determine when cached + // type information needs to be regenerated because it was + // from a previous pass. + private _analysisVersion = 0; + + // Temporarily suppress the output of diagnostics? + private _isDiagnosticsSuppressed = false; + + // List of type constraints that are currently in effect + // when walking a multi-part AND expression (e.g. A and B + // and C). + private _expressionTypeConstraints: TypeConstraint[] = []; + + constructor(node: ModuleNode, fileInfo: AnalyzerFileInfo, analysisVersion: number) { + super(); + + this._moduleNode = node; + this._fileInfo = fileInfo; + this._currentScope = AnalyzerNodeInfo.getScope(node)!; + this._didAnalysisChange = false; + this._analysisVersion = analysisVersion; + } + + analyze() { + this._didAnalysisChange = false; + + let declaration: Declaration = { + category: SymbolCategory.Module, + node: this._moduleNode, + path: this._fileInfo.filePath, + range: { start: { line: 0, column: 0 }, end: { line: 0, column: 0 } } + }; + + AnalyzerNodeInfo.setDeclaration(this._moduleNode, declaration); + + this.walk(this._moduleNode); + + return this._didAnalysisChange; + } + + visitClass(node: ClassNode): boolean { + this.walkMultiple(node.decorators); + + // We should have already resolved most of the base class + // parameters in the semantic analyzer, but if these parameters + // are variables, they may not have been resolved at that time. + this.walkMultiple(node.arguments); + let classType = AnalyzerNodeInfo.getExpressionType(node) as ClassType; + assert(classType instanceof ClassType); + + node.arguments.forEach((arg, index) => { + let argType = TypeAnnotation.getType(arg.valueExpression, + this._currentScope, this._getConditionalDiagnosticSink(), false); + + // In some stub files, classes are conditionally defined (e.g. based + // on platform type). We'll assume that the conditional logic is correct + // and strip off the "unbound" union. + if (argType instanceof UnionType) { + argType = argType.removeUnbound(); + } + + if (!argType.isAny() && argType.category !== TypeCategory.Class) { + this._addError(`Argument to class must be a base class`, arg); + } + + if (classType.updateBaseClassType(index, argType)) { + this._setAnalysisChanged(); + } + }); + + this._enterScope(node, () => { + this.walk(node.suite); + }); + + let declaration: Declaration = { + category: SymbolCategory.Class, + node: node.name, + path: this._fileInfo.filePath, + range: convertOffsetsToRange(node.name.start, node.name.end, this._fileInfo.lines) + }; + this._bindNameNodeToType(node.name, classType, declaration); + + return false; + } + + visitFunction(node: FunctionNode): boolean { + const isMethod = ParseTreeUtils.isFunctionInClass(node); + this.walkMultiple(node.decorators); + + const functionType = AnalyzerNodeInfo.getExpressionType(node) as FunctionType; + assert(functionType instanceof FunctionType); + + const functionParams = functionType.getParameters(); + node.parameters.forEach((param, index) => { + let annotatedType: Type | undefined; + if (param.typeAnnotation) { + this.walk(param.typeAnnotation.expression); + + annotatedType = TypeAnnotation.getType(param.typeAnnotation.expression, + this._currentScope, this._getConditionalDiagnosticSink()); + + // PEP 484 indicates that if a parameter has a default value of 'None' + // the type checker should assume that the type is optional (i.e. a union + // of the specified type and 'None'). + // TODO - tighten this up, perhaps using a config flag + if (param.defaultValue instanceof ConstantNode) { + if (param.defaultValue.token.keywordType === KeywordType.None) { + annotatedType = TypeUtils.combineTypes(annotatedType, NoneType.create()); + } + } + + functionParams[index].type = annotatedType; + + if (param.defaultValue) { + // Verify that the default value matches the type annotation. + let defaultValueType = this._getTypeOfExpressionWithTypeConstraints(param.defaultValue); + if (annotatedType && !TypeUtils.canAssignType(annotatedType, defaultValueType)) { + this._addError( + `Value of type '${ defaultValueType.asString() }' cannot` + + ` be assiged to parameter of type '${ annotatedType.asString() }'`, + param.defaultValue); + } + } + } else if (index === 0 && param.name) { + let classNode = this._getEnclosingClass(node); + if (classNode) { + let inferredClassType = AnalyzerNodeInfo.getExpressionType(classNode) as ClassType; + if (inferredClassType) { + if (param.name.nameToken.value === 'self') { + functionParams[index].type = new ObjectType(inferredClassType); + } else if (param.name.nameToken.value === 'cls') { + functionParams[index].type = inferredClassType; + } + } + } + } + }); + + if (node.returnTypeAnnotation) { + this.walk(node.returnTypeAnnotation.expression); + + const returnType = TypeAnnotation.getType(node.returnTypeAnnotation.expression, + this._currentScope, this._getConditionalDiagnosticSink()); + if (functionType.setDeclaredReturnType(returnType)) { + this._setAnalysisChanged(); + } + } else if (this._fileInfo.isStubFile) { + // If a return type annotation is missing in a stub file, assume + // it's an "any" type. In normal source files, we can infer the + // type from the implementation. + functionType.setDeclaredReturnType(AnyType.create()); + } + + let functionScope = this._enterScope(node, () => { + // Add the parameters to the scope and bind their types. + functionType.getParameters().forEach(param => { + if (param.name) { + if (param.category === ParameterCategory.Simple) { + let declaration: Declaration | undefined; + if (param.node) { + declaration = { + category: SymbolCategory.Parameter, + node: param.node, + path: this._fileInfo.filePath, + range: convertOffsetsToRange(param.node.start, param.node.end, this._fileInfo.lines) + }; + } + let typeSourceId = param.node ? + AnalyzerNodeInfo.getTypeSourceId(param.node) : + DefaultTypeSourceId; + this._bindNameToType(param.name, param.type, typeSourceId, declaration); + } + } + }); + + node.parameters.forEach(param => { + if (param.name) { + // Cache the type for the hover provider. + this._getTypeOfExpression(param.name); + + // Set the declaration on the node for the definition language service. + const symbol = this._currentScope.lookUpSymbol(param.name.nameToken.value); + if (symbol && symbol.declarations) { + AnalyzerNodeInfo.setDeclaration(param.name, symbol.declarations[0]); + } + } + }); + + // If this function is part of a class, add an implied "super" method. + let classNode = this._getEnclosingClass(node); + if (classNode) { + let classType = AnalyzerNodeInfo.getExpressionType(classNode) as ClassType; + assert(classType !== undefined && classType instanceof ClassType); + + let superType = new FunctionType(FunctionTypeFlags.None); + superType.addParameter({ + category: ParameterCategory.VarArgList, + name: 'args', + type: UnknownType.create(), + node: classNode + }); + superType.addParameter({ + category: ParameterCategory.VarArgDictionary, + name: 'kwargs', + type: UnknownType.create(), + node: classNode + }); + if (classType.getBaseClasses().length > 0) { + let baseClass = classType.getBaseClasses()[0]; + if (baseClass instanceof ClassType) { + superType.setDeclaredReturnType(new ObjectType(baseClass)); + } else { + superType.setDeclaredReturnType(UnknownType.create()); + } + } + + this._bindNameToType('super', superType, DefaultTypeSourceId); + } + + this.walk(node.suite); + }); + + if (!this._fileInfo.isStubFile) { + // Add all of the return types that were found within the function. + let inferredReturnType = functionType.getInferredReturnType(); + if (inferredReturnType.addSources(functionScope.getReturnType())) { + this._setAnalysisChanged(); + } + + // Add the "None" type if the function doesn't always return. + if (!functionScope.getAlwaysReturnsOrRaises()) { + if (inferredReturnType.addSource(NoneType.create(), DefaultTypeSourceId)) { + this._setAnalysisChanged(); + } + + // If the declared type isn't compatible with 'None', flag an error. + const declaredReturnType = functionType.getDeclaredReturnType(); + if (declaredReturnType && node.returnTypeAnnotation) { + if (!TypeUtils.canAssignType(declaredReturnType, NoneType.create())) { + this._addError(`Function with declared type of ${ declaredReturnType.asString() }` + + ` must return value`, node.returnTypeAnnotation.rawExpression); + } + } + } + } + + let decoratedType: Type = functionType; + + // Handle overload decorators specially. + let overloadedType: OverloadedFunctionType | undefined; + [overloadedType] = TypeAnnotation.getOverloadedFunctionType(node, + functionType, this._currentScope); + if (overloadedType) { + decoratedType = overloadedType; + } else { + // Determine if the function is a property getter or setter. + if (ParseTreeUtils.isFunctionInClass(node)) { + let propertyType = TypeAnnotation.getPropertyType( + node, functionType, this._currentScope); + if (propertyType) { + decoratedType = propertyType; + } + } + } + + let declaration: Declaration = { + category: isMethod ? SymbolCategory.Method : SymbolCategory.Function, + node: node.name, + path: this._fileInfo.filePath, + range: convertOffsetsToRange(node.name.start, node.name.end, this._fileInfo.lines) + }; + this._bindNameNodeToType(node.name, decoratedType, declaration); + this._updateExpressionTypeForNode(node.name, functionType); + + return false; + } + + visitLambda(node: LambdaNode): boolean { + this._enterScope(node, () => { + this.walkChildren(node); + }); + return false; + } + + visitCall(node: CallExpressionNode): boolean { + let callType = this._getTypeOfExpressionWithTypeConstraints(node.leftExpression); + + if (!this._validateCallArguments(node, callType, this._isCallOnObjectOrClass(node))) { + this._addError( + `'${ ParseTreeUtils.printExpression(node.leftExpression) }' has type ` + + `'${ callType.asString() }' and is not callable`, + node.leftExpression); + } + return true; + } + + visitFor(node: ForNode): boolean { + this.walk(node.sequenceExpression); + + let exprType = this._getTypeOfExpressionWithTypeConstraints(node.sequenceExpression); + if (exprType.category === TypeCategory.Unbound) { + exprType = UnknownType.create(); + } else { + // TODO - need to figure out correct type of iterated items. + exprType = UnknownType.create(); + } + + this._assignTypeToPossibleTuple(node.targetExpression, exprType); + + this.walk(node.targetExpression); + this.walk(node.forSuite); + + if (node.elseSuite) { + this.walk(node.elseSuite); + } + + return false; + } + + visitListComprehension(node: ListComprehensionNode): boolean { + // We need to "execute" the comprehension clauses first, even + // though they appear afterward in the syntax. We'll do so + // within a temporary scope so we can throw away the target + // when complete. + this._enterTemporaryScope(() => { + node.comprehensions.forEach(compr => { + if (compr instanceof ListComprehensionForNode) { + this.walk(compr.sequenceExpression); + + // TODO - need to figure out right type for target expression. + // let exprType = this._getTypeOfExpressionWithTypeConstraints(compr.sequenceExpression); + let exprType = UnknownType.create(); + + this._assignTypeToPossibleTuple(compr.targetExpression, exprType); + this.walk(compr.targetExpression); + } else { + this.walk(compr.testExpression); + } + }); + + this.walk(node.baseExpression); + }); + + return false; + } + + visitIf(node: IfNode): boolean { + let ifScope: Scope | undefined; + let elseScope: Scope | undefined; + let ifIsUnconditional = false; + let elseIsUnconditional = false; + + // Determine if the if condition is always true or always false. If so, + // we can treat either the if or the else clause as unconditional. + let constExprValue = ExpressionUtils.evaluateConstantExpression( + node.testExpression, this._fileInfo.executionEnvironment); + + this.walk(node.testExpression); + + let typeConstraints = this._buildTypeConstraints(node.testExpression); + + // Push a temporary scope so we can track + // which variables have been assigned to conditionally. + ifScope = this._enterTemporaryScope(() => { + // Add any applicable type constraints. + if (typeConstraints) { + typeConstraints.ifConstraints.forEach(constraint => { + this._currentScope.addTypeConstraint(constraint); + }); + } + + this.walk(node.ifSuite); + }, true, constExprValue === false); + + // Now handle the else statement if it's present. If there + // are chained "else if" statements, they'll be handled + // recursively here. + if (node.elseSuite) { + elseScope = this._enterTemporaryScope(() => { + // Add any applicable type constraints. + if (typeConstraints) { + typeConstraints.elseConstraints.forEach(constraint => { + this._currentScope.addTypeConstraint(constraint); + }); + } + + this.walk(node.elseSuite!); + }, true, constExprValue === true); + } + + // Evaluate the expression so the expression type is cached. + this._getTypeOfExpression(node.testExpression); + + if (constExprValue !== undefined) { + if (constExprValue) { + ifIsUnconditional = true; + elseScope = undefined; + } else { + elseIsUnconditional = true; + ifScope = undefined; + } + } + + // Figure out how to combine the scopes. + if (ifScope && !ifScope.getAlwaysReturnsOrRaises() && elseScope && !elseScope.getAlwaysReturnsOrRaises()) { + // If both an "if" and an "else" scope exist, combine the names from both scopes. + ifScope.combineConditionalSymbolTable(elseScope); + this._mergeToCurrentScope(ifScope); + } else if (ifScope && !ifScope.getAlwaysReturnsOrRaises()) { + // If there's only an "if" scope executed, mark all of its contents as conditional. + if (!elseScope && !ifIsUnconditional) { + ifScope.markAllSymbolsConditional(); + } + this._mergeToCurrentScope(ifScope); + } else if (elseScope && !elseScope.getAlwaysReturnsOrRaises()) { + // If there's only an "else" scope executed, mark all of its contents as conditional. + if (!ifScope && !elseIsUnconditional) { + elseScope.markAllSymbolsConditional(); + } + this._mergeToCurrentScope(elseScope); + } else if (ifScope && ifScope.getAlwaysReturnsOrRaises() && elseScope && elseScope.getAlwaysReturnsOrRaises()) { + // If both an if and else clause are executed but they both return or raise an exception, + // mark the current scope as always returning or raising an exception. + if (ifScope.getAlwaysRaises() && elseScope.getAlwaysRaises()) { + this._currentScope.setAlwaysRaises(); + } else { + this._currentScope.setAlwaysReturns(); + } + } + + if (ifScope) { + this._mergeReturnTypeToCurrentScope(ifScope); + } + + if (elseScope) { + this._mergeReturnTypeToCurrentScope(elseScope); + } + + return false; + } + + visitWith(node: WithNode): boolean { + node.withItems.forEach(item => { + this.walk(item.expression); + }); + + node.withItems.forEach(item => { + if (item.target) { + let exprType = this._getTypeOfExpressionWithTypeConstraints(item.expression); + + // If the type has an "__enter__" method, it can return + // a type other than its own type. + const enterMethodName = node.isAsync ? '__aenter__' : '__enter__'; + let enterTypeMember = TypeUtils.lookUpObjectMember(exprType, enterMethodName); + if (enterTypeMember) { + const memberType = TypeUtils.getEffectiveTypeOfMember(enterTypeMember); + if (memberType instanceof FunctionType) { + exprType = memberType.getEffectiveReturnType(); + } + } + + this._assignTypeToPossibleTuple(item.target, exprType); + } + }); + + this.walk(node.suite); + return false; + } + + visitConditional(node: ConditionalExpressionNode) { + this.walk(node.leftExpression); + + // Apply the type constraint when evaluating the if and else clauses. + let typeConstraints = this._buildTypeConstraints(node.leftExpression); + + // Start by evaluating the if statement. + this._useExpressionTypeConstraint(typeConstraints, true, () => { + this.walk(node.ifExpression); + }); + + // And now the else statement. + this._useExpressionTypeConstraint(typeConstraints, false, () => { + this.walk(node.elseExpression); + }); + + return false; + } + + visitReturn(node: ReturnNode): boolean { + let declaredReturnType: Type | undefined; + let returnType: Type; + let typeSourceId = DefaultTypeSourceId; + + let enclosingFunctionNode = this._getEnclosingFunction(node); + if (enclosingFunctionNode) { + let functionType = AnalyzerNodeInfo.getExpressionType( + enclosingFunctionNode) as FunctionType; + if (functionType) { + assert(functionType instanceof FunctionType); + declaredReturnType = functionType.getDeclaredReturnType(); + } + } + + if (node.returnExpression) { + returnType = this._getTypeOfExpressionWithTypeConstraints(node.returnExpression); + typeSourceId = AnalyzerNodeInfo.getTypeSourceId(node); + } else { + // There is no return expression, so "None" is assumed. + returnType = NoneType.create(); + } + + this._currentScope.getReturnType().addSource(returnType, typeSourceId); + if (declaredReturnType) { + if (!TypeUtils.canAssignType(declaredReturnType, returnType)) { + this._addError( + `Expression of type '${ returnType.asString() }' cannot not assigned ` + + `to return type '${ declaredReturnType.asString() }'`, + node.returnExpression ? node.returnExpression : node); + } + } + + this._currentScope.setAlwaysReturns(); + return true; + } + + visitYield(node: YieldExpressionNode) { + let yieldType = this._getTypeOfExpressionWithTypeConstraints(node.expression); + let typeSourceId = AnalyzerNodeInfo.getTypeSourceId(node.expression); + this._currentScope.getReturnType().addSource(yieldType, typeSourceId); + + return true; + } + + visitYieldFrom(node: YieldFromExpressionNode) { + // TODO - determine the right type to use for the iteration. + let typeSourceId = AnalyzerNodeInfo.getTypeSourceId(node.expression); + this._currentScope.getReturnType().addSource( + UnknownType.create(), typeSourceId); + + return true; + } + + visitRaise(node: RaiseNode): boolean { + if (this._currentScope.getNestedTryDepth() === 0) { + this._currentScope.setAlwaysRaises(); + } + return true; + } + + visitExcept(node: ExceptNode): boolean { + if (node.typeExpression) { + this.walk(node.typeExpression); + } + + if (node.typeExpression && node.name) { + this._currentScope.addUnboundSymbol(node.name.nameToken.value); + let exceptionType = TypeAnnotation.getType(node.typeExpression, + this._currentScope, this._getConditionalDiagnosticSink(), false); + + // If more than one type was specified for the exception, + // handle that here. + if (exceptionType instanceof TupleType) { + let tuple = exceptionType; + let unionType = new UnionType(); + unionType.addTypes(tuple.getEntryTypes().map(t => { + return this._validateExceptionType(t, node.typeExpression!); + })); + exceptionType = unionType; + } else { + exceptionType = this._validateExceptionType( + exceptionType, node.typeExpression); + } + + let declaration: Declaration = { + category: SymbolCategory.Variable, + node: node.name, + path: this._fileInfo.filePath, + range: convertOffsetsToRange(node.name.start, node.name.end, this._fileInfo.lines) + }; + this._bindNameNodeToType(node.name, exceptionType, declaration); + this._updateExpressionTypeForNode(node.name, exceptionType); + } + + this.walk(node.exceptSuite); + + return false; + } + + visitTry(node: TryNode): boolean { + this._currentScope.incrementNestedTryDepth(); + this.walk(node.trySuite); + this._currentScope.decrementNestedTryDepth(); + + // Wrap the except clauses in a conditional scope + // so we can throw away any names that are bound + // in this scope. + node.exceptClauses.forEach(exceptNode => { + let exceptScope = this._enterTemporaryScope(() => { + this.walk(exceptNode); + }); + this._mergeReturnTypeToCurrentScope(exceptScope); + }); + + if (node.elseSuite) { + this.walk(node.elseSuite); + } + + if (node.finallySuite) { + this.walk(node.finallySuite); + } + + return false; + } + + visitAssignment(node: AssignmentNode): boolean { + // Special-case the typing.pyi file, which contains some special + // types that the type analyzer needs to interpret differently. + if (this._fileInfo.isTypingStubFile) { + if (node.leftExpression instanceof NameNode) { + const assignedName = node.leftExpression.nameToken.value; + let specialType: Type | undefined; + + if (assignedName === 'Any') { + specialType = AnyType.create(); + } else { + const specialTypes = ['overload', 'TypeVar', '_promote', 'no_type_check', + 'NoReturn', 'Union', 'Optional', 'List', 'Dict', 'DefaultDict', + 'Set', 'FrozenSet', 'Counter', 'Deque', 'ChainMap']; + if (specialTypes.find(t => t === assignedName)) { + // Synthesize a class. + specialType = new ClassType(assignedName, + ClassTypeFlags.BuiltInClass | ClassTypeFlags.SpecialBuiltIn); + } + } + + if (specialType) { + let declaration: Declaration = { + category: SymbolCategory.Class, + node: node.leftExpression, + path: this._fileInfo.filePath, + range: convertOffsetsToRange(node.leftExpression.start, + node.leftExpression.end, this._fileInfo.lines) + }; + this._bindNameNodeToType(node.leftExpression, specialType, declaration); + this._updateExpressionTypeForNode(node.leftExpression, specialType); + return false; + } + } + } + + this.walk(node.rightExpression); + + let typeOfExpr = this._getTypeOfExpressionWithTypeConstraints(node.rightExpression); + + // In a stub file, an assignment to ellipsis means "any". + if (this._fileInfo.isStubFile) { + if (typeOfExpr instanceof EllipsisType) { + typeOfExpr = AnyType.create(); + } + } + + if (!(node.leftExpression instanceof NameNode) || + !this._assignTypeForPossibleEnumeration(node.leftExpression, typeOfExpr)) { + this._assignTypeToPossibleTuple(node.leftExpression, typeOfExpr); + } + + this.walk(node.leftExpression); + return false; + } + + visitName(node: NameNode) { + let symbolInScope = this._currentScope.lookUpSymbolRecursive(node.nameToken.value); + + if (symbolInScope && symbolInScope.symbol.declarations) { + // For now, always assume it's the first declaration + // that applies here. This is correct in all cases except for + // possibly properties (getters/setters/deleters) and functions + // (@overload). + AnalyzerNodeInfo.setDeclaration(node, symbolInScope.symbol.declarations[0]); + } + + // Call _getTypeOfExpression so the type is cached in the + // node, allowing it to be accessed for hover and definition + // information. + this._getTypeOfExpression(node); + return true; + } + + visitMemberAccess(node: MemberAccessExpressionNode) { + this.walk(node.leftExpression); + + let leftType = this._getTypeOfExpressionWithTypeConstraints(node.leftExpression); + this._validateMemberAccess(leftType, node.memberName); + + // Set the member type for the hover provider. + this._updateExpressionTypeForNode(node.memberName, this._getTypeOfExpression(node)); + + // Don't walk the member name. + return false; + } + + visitBinaryOperation(node: BinaryExpressionNode) { + this.walk(node.leftExpression); + + // Is this an AND operator? If so, we can assume that the + // rightExpression won't be evaluated at runtime unless the + // leftExpression evaluates to true. + let typeConstraints: TypeConstraintResults | undefined; + if (node.operator === OperatorType.And) { + typeConstraints = this._buildTypeConstraints(node.leftExpression); + } + + this._useExpressionTypeConstraint(typeConstraints, true, () => { + this.walk(node.rightExpression); + }); + + return false; + } + + visitImportAs(node: ImportAsNode): boolean { + let importInfo = AnalyzerNodeInfo.getImportInfo(node.module); + assert(importInfo !== undefined); + + if (importInfo && importInfo.importFound && importInfo.resolvedPaths.length > 0) { + let resolvedPath = importInfo.resolvedPaths[importInfo.resolvedPaths.length - 1]; + let moduleType = this._getModuleTypeForImportPath(importInfo, resolvedPath); + + if (moduleType) { + // Import the implicit imports in the module's namespace. + importInfo.implicitImports.forEach(implicitImport => { + let implicitModuleType = this._getModuleTypeForImportPath( + importInfo, implicitImport.path); + if (implicitModuleType) { + const moduleFields = moduleType!.getFields(); + let importedModule = this._fileInfo.importMap[implicitImport.path]; + + let declaration: Declaration = { + category: SymbolCategory.Module, + node: importedModule.parseTree, + path: implicitImport.path, + range: { start: { line: 0, column: 0 }, end: { line: 0, column: 0 }} + }; + + let newSymbol = new Symbol(implicitModuleType, DefaultTypeSourceId); + newSymbol.declarations = [declaration]; + moduleFields.set(implicitImport.name, newSymbol); + } + }); + + let moduleDeclaration: Declaration | undefined; + if (this._fileInfo.importMap[resolvedPath]) { + moduleDeclaration = AnalyzerNodeInfo.getDeclaration( + this._fileInfo.importMap[resolvedPath].parseTree); + } + + if (node.alias) { + this._bindNameNodeToType(node.alias, moduleType, moduleDeclaration); + this._updateExpressionTypeForNode(node.alias, moduleType); + } else { + this._bindMultiPartModuleNameToType(node.module.nameParts, + moduleType, moduleDeclaration); + } + } + } + + return false; + } + + visitImportFrom(node: ImportFromNode): boolean { + let importInfo = AnalyzerNodeInfo.getImportInfo(node.module); + + if (importInfo && importInfo.importFound && importInfo.resolvedPaths.length > 0) { + let resolvedPath = importInfo.resolvedPaths[importInfo.resolvedPaths.length - 1]; + + // Empty list implies "import *" + if (node.imports.length === 0) { + let moduleType = this._getModuleTypeForImportPath(importInfo, resolvedPath); + if (moduleType) { + // Import the fields in the module's namespace. + const moduleFields = moduleType.getFields(); + moduleFields.forEach((boundValue, fieldName) => { + this._bindNameToType(fieldName, boundValue.inferredType.getType(), + DefaultTypeSourceId, + boundValue.declarations ? boundValue.declarations[0] : undefined); + }); + + // Import the implicit imports in the module's namespace. + importInfo.implicitImports.forEach(implicitImport => { + let moduleType = this._getModuleTypeForImportPath(importInfo, resolvedPath); + if (moduleType) { + this._bindNameToType(implicitImport.name, moduleType, DefaultTypeSourceId); + } + }); + } + } else { + node.imports.forEach(importAs => { + const name = importAs.name.nameToken.value; + let symbolType: Type | undefined; + const aliasNode = importAs.alias || importAs.name; + let declaration: Declaration | undefined; + + // Is the name referring to an implicit import? + let implicitImport = importInfo!.implicitImports.find(impImport => impImport.name === name); + if (implicitImport) { + let moduleType = this._getModuleTypeForImportPath(importInfo, implicitImport.path); + if (moduleType) { + symbolType = moduleType; + declaration = AnalyzerNodeInfo.getDeclaration( + this._fileInfo.importMap[implicitImport.path].parseTree); + } + } else { + let moduleType = this._getModuleTypeForImportPath(importInfo, resolvedPath); + if (moduleType) { + const moduleFields = moduleType.getFields(); + const symbol = moduleFields.get(name); + if (symbol) { + symbolType = symbol.currentType; + if (symbol.declarations) { + declaration = symbol.declarations[0]; + } + } else { + this._addError( + `'${ importAs.name.nameToken.value }' is unknown import symbol`, + importAs.name + ); + } + } + } + + if (!symbolType) { + symbolType = UnknownType.create(); + } + + this._updateExpressionTypeForNode(importAs.name, symbolType); + if (importAs.alias) { + this._updateExpressionTypeForNode(importAs.name, symbolType); + } + + if (declaration) { + AnalyzerNodeInfo.setDeclaration(importAs.name, declaration); + if (importAs.alias) { + AnalyzerNodeInfo.setDeclaration(importAs.name, declaration); + } + } + + this._bindNameNodeToType(aliasNode, symbolType, declaration); + }); + } + } else { + // We were unable to resolve the import. Bind the names (or aliases) + // to an unknown type. + if (node.imports.length !== 0) { + node.imports.forEach(importAs => { + const aliasNode = importAs.alias || importAs.name; + let symbolType = UnknownType.create(); + + this._updateExpressionTypeForNode(importAs.name, symbolType); + if (importAs.alias) { + this._updateExpressionTypeForNode(importAs.name, symbolType); + } + + this._bindNameNodeToType(aliasNode, symbolType); + }); + } + } + + return false; + } + + visitTypeAnnotation(node: TypeAnnotationExpressionNode): boolean { + // Special-case the typing.pyi file, which contains some special + // types that the type analyzer needs to interpret differently. + if (this._fileInfo.isTypingStubFile) { + // Special-case the typing file. + if (node.valueExpression instanceof NameNode) { + const assignedName = node.valueExpression.nameToken.value; + let specialType: Type | undefined; + + const specialTypes = ['Tuple', 'Generic', 'Protocol', 'Callable', 'Type', 'ClassVar', + 'Final', 'Literal']; + if (specialTypes.find(t => t === assignedName)) { + // Synthesize a class. + specialType = new ClassType(assignedName, + ClassTypeFlags.BuiltInClass | ClassTypeFlags.SpecialBuiltIn); + } + + if (specialType) { + let declaration: Declaration = { + category: SymbolCategory.Class, + node: node.valueExpression, + path: this._fileInfo.filePath, + range: convertOffsetsToRange(node.valueExpression.start, + node.valueExpression.end, this._fileInfo.lines) + }; + this._bindNameNodeToType(node.valueExpression, specialType, declaration); + this._updateExpressionTypeForNode(node.valueExpression, specialType); + return false; + } + } + } + + let typeHint = TypeAnnotation.getType(node.typeAnnotation.expression, + this._currentScope, this._getConditionalDiagnosticSink()); + if (typeHint) { + if (!(node.valueExpression instanceof NameNode) || + !this._assignTypeForPossibleEnumeration(node.valueExpression, typeHint)) { + this._assignTypeToPossibleTuple(node.valueExpression, typeHint); + } + } + + this.walk(node.valueExpression); + + // Walk the type expression to fill in the type information + // for the hover provider. + this.walk(node.typeAnnotation.expression); + + return false; + } + + // Determine if this is a call through an object or class, in + // which case a "self" or "cls" argument needs to be synthesized. + private _isCallOnObjectOrClass(node: CallExpressionNode): boolean { + let skipFirstMethodParam = false; + if (node.leftExpression instanceof MemberAccessExpressionNode) { + let leftType = this._getTypeOfExpressionWithTypeConstraints( + node.leftExpression.leftExpression); + + // TODO - what should we do about UnionType here? + if (leftType instanceof ObjectType || leftType instanceof ClassType) { + skipFirstMethodParam = true; + } + } + + return skipFirstMethodParam; + } + + private _validateCallArguments(node: CallExpressionNode, callType: Type, + skipFirstMethodParam: boolean): boolean { + let isCallable = true; + + if (callType instanceof TypeVarType) { + // TODO - need to remove once we resolve type vars + return true; + } + + if (!callType.isAny()) { + if (callType instanceof FunctionType) { + this._validateFunctionArguments(node, callType, skipFirstMethodParam); + } else if (callType instanceof OverloadedFunctionType) { + if (!this._findOverloadedFunctionType(callType, node, skipFirstMethodParam)) { + const exprString = ParseTreeUtils.printExpression(node.leftExpression); + this._addError( + `No overloads for '${ exprString }' match parameters`, + node.leftExpression); + } + } else if (callType instanceof ClassType) { + if (!callType.isSpecialBuiltIn()) { + this._validateConstructorArguments(node, callType); + } + } else if (callType instanceof ObjectType) { + isCallable = false; + const callMethod = TypeUtils.lookUpObjectMember(callType, '__call__'); + if (callMethod) { + const callMethodType = TypeUtils.getEffectiveTypeOfMember(callMethod); + if (callMethodType instanceof FunctionType) { + isCallable = this._validateCallArguments(node, callMethodType, true); + } + } + } else if (callType instanceof UnionType) { + for (let type of callType.getTypes()) { + if (type instanceof NoneType) { + // TODO - for now, assume that optional + // types (unions with None) are valid. Tighten + // this later. + } else if (!this._validateCallArguments(node, type, skipFirstMethodParam)) { + isCallable = false; + break; + } + } + } else { + isCallable = false; + } + } + + return isCallable; + } + + private _findOverloadedFunctionType(callType: OverloadedFunctionType, + node: CallExpressionNode, skipFirstMethodParam: boolean): FunctionType | undefined { + let validOverload: FunctionType | undefined; + + // Temporarily suppress diagnostics. + this._suppressDiagnostics(() => { + for (let overload of callType.getOverloads()) { + if (this._validateCallArguments(node, overload.type, skipFirstMethodParam)) { + validOverload = overload.type; + } + } + }); + + return validOverload; + } + + private _validateExceptionType(exceptionType: Type, errorNode: ParseNode) { + if (exceptionType.isAny()) { + return exceptionType; + } + + // Convert the class into an object type. + if (exceptionType instanceof ClassType) { + return new ObjectType(exceptionType); + } else if (exceptionType instanceof TupleType) { + return exceptionType; + } else if (exceptionType instanceof ObjectType) { + // TODO - we need to determine whether the type is an iterable + // collection of classes. For now, just see if it derives + // from one of the built-in iterable types. + const classType = exceptionType.getClassType(); + const validTypes = ['list', 'tuple', 'set']; + const isValid = validTypes.find(t => { + const builtInType = TypeAnnotation.getBuiltInType(this._currentScope, t); + if (!builtInType || !(builtInType instanceof ClassType)) { + return false; + } + return classType.isDerivedFrom(builtInType); + }) !== undefined; + if (isValid) { + return exceptionType; + } + } + + this._addError( + `'${ exceptionType.asString() }' is not valid exception class`, + errorNode); + return exceptionType; + } + + private _bindMemberVariableToType(node: MemberAccessExpressionNode, + typeOfExpr: Type, isInstanceMember: boolean) { + + let classDef = this._getEnclosingClass(node); + if (!classDef) { + return; + } + + let classType = AnalyzerNodeInfo.getExpressionType(classDef); + if (classType && classType instanceof ClassType) { + let memberName = node.memberName.nameToken.value; + let memberInfo = TypeUtils.lookUpClassMember(classType, memberName); + + let createDeclaration = () => { + let declaration: Declaration = { + category: typeOfExpr instanceof FunctionType ? + SymbolCategory.Method : SymbolCategory.Variable, + node: node.memberName, + path: this._fileInfo.filePath, + range: convertOffsetsToRange(node.memberName.start, node.memberName.end, this._fileInfo.lines) + }; + return declaration; + }; + + const memberFields = isInstanceMember ? classType.getInstanceFields() : classType.getClassFields(); + + let addNewMemberToLocalClass = false; + if (memberInfo) { + if (memberInfo.class === classType && memberInfo.isInstanceMember === isInstanceMember) { + const symbol = memberFields.get(memberName)!; + assert(symbol !== undefined); + if (symbol.setCurrentType(typeOfExpr, AnalyzerNodeInfo.getTypeSourceId(node.memberName))) { + this._setAnalysisChanged(); + } + + // If there is no declaration yet, assign one now. + let declaration = createDeclaration(); + symbol.addDeclaration(declaration); + AnalyzerNodeInfo.setDeclaration(node.memberName, symbol.declarations![0]); + } else { + // Handle the case where there is a class variable defined with the same + // name, but there's also now an instance variable introduced. Combine the + // type of the class variable with that of the new instance variable. + if (memberInfo.symbol && !memberInfo.isInstanceMember && isInstanceMember) { + typeOfExpr = TypeUtils.combineTypes(typeOfExpr, TypeUtils.getEffectiveTypeOfMember(memberInfo)); + } + addNewMemberToLocalClass = true; + } + } else { + // The member name hasn't been seen previously, so add it to the local class. + addNewMemberToLocalClass = true; + } + + if (addNewMemberToLocalClass) { + let newSymbol = new Symbol(typeOfExpr, AnalyzerNodeInfo.getTypeSourceId(node.memberName)); + newSymbol.addDeclaration(createDeclaration()); + memberFields.set(memberName, newSymbol); + this._setAnalysisChanged(); + + AnalyzerNodeInfo.setDeclaration(node.memberName, newSymbol.declarations![0]); + } + } + } + + private _mergeToCurrentScope(scopeToMerge: Scope) { + if (this._currentScope.mergeSymbolTable(scopeToMerge)) { + this._setAnalysisChanged(); + } + + this._mergeReturnTypeToCurrentScope(scopeToMerge); + } + + private _mergeReturnTypeToCurrentScope(scopeToMerge: Scope) { + if (this._currentScope.mergeReturnType(scopeToMerge)) { + if (this._currentScope.getType() !== ScopeType.Temporary) { + this._setAnalysisChanged(); + } + } + } + + private _getModuleTypeForImportPath(importResult: ImportResult | undefined, + path: string): ModuleType | undefined { + if (this._fileInfo.importMap[path]) { + let moduleNode = this._fileInfo.importMap[path].parseTree; + if (moduleNode) { + let moduleType = AnalyzerNodeInfo.getExpressionType(moduleNode) as ModuleType; + if (moduleType) { + return moduleType; + } + } + } else if (importResult) { + // There was no module even though the import was resolved. This + // happens in the case of namespace packages, where an __init__.py + // is not necessarily present. We'll synthesize a module type in + // this case. + let symbolTable = new SymbolTable(); + let moduleType = new ModuleType(symbolTable); + + // Add the implicit imports. + importResult.implicitImports.forEach(implicitImport => { + let implicitModuleType = this._getModuleTypeForImportPath( + undefined, implicitImport.path); + if (implicitModuleType) { + symbolTable.set(implicitImport.name, new Symbol(implicitModuleType, DefaultTypeSourceId)); + } + }); + + return moduleType; + } + + return undefined; + } + + private _getTypeOfExpressionWithTypeConstraints(node: ExpressionNode): Type { + let type = this._getTypeOfExpression(node); + return this._applyTypeConstraint(node, type); + } + + private _getTypeOfExpression(node: ExpressionNode): Type { + // If there's an up-to-date cached version, return it. + let cachedVersion = AnalyzerNodeInfo.getExpressionTypeVersion(node); + if (cachedVersion === this._analysisVersion) { + let cachedType = AnalyzerNodeInfo.getExpressionType(node); + assert(cachedType !== undefined); + return cachedType!; + } + + let exprType: Type | undefined; + + if (node instanceof NameNode) { + exprType = this._getTypeOfName(node.nameToken.value); + } else if (node instanceof StringNode) { + if (node.tokens[0].quoteTypeFlags & QuoteTypeFlags.Byte) { + exprType = TypeAnnotation.getBuiltInObject(this._currentScope, 'byte'); + } else { + exprType = TypeAnnotation.getBuiltInObject(this._currentScope, 'str'); + } + } else if (node instanceof NumberNode) { + if (node.token.isInteger) { + exprType = TypeAnnotation.getBuiltInObject(this._currentScope, 'int'); + } else { + exprType = TypeAnnotation.getBuiltInObject(this._currentScope, 'float'); + } + } else if (node instanceof ConstantNode) { + if (node.token.keywordType === KeywordType.True || + node.token.keywordType === KeywordType.False || + node.token.keywordType === KeywordType.Debug) { + exprType = TypeAnnotation.getBuiltInObject(this._currentScope, 'bool'); + } else { + assert(node.token.keywordType === KeywordType.None); + exprType = NoneType.create(); + } + } else if (node instanceof EllipsisNode) { + exprType = EllipsisType.create(); + } else if (node instanceof MemberAccessExpressionNode) { + exprType = this._getTypeOfMemberAccessNode(node); + } else if (node instanceof CallExpressionNode) { + let callType = this._getTypeOfExpression(node.leftExpression); + exprType = this._getTypeOfCallNode(node, callType); + } else if (node instanceof UnaryExpressionNode) { + // TODO - need to implement + this._getTypeOfExpression(node.expression); + } else if (node instanceof BinaryExpressionNode) { + // TODO - need to implement + this._getTypeOfExpression(node.leftExpression); + this._getTypeOfExpression(node.rightExpression); + } else if (node instanceof TupleExpressionNode) { + let tupleType = new TupleType( + TypeAnnotation.getBuiltInType(this._currentScope, 'tuple') as ClassType); + node.expressions.forEach(expr => { + tupleType.addEntryType(this._getTypeOfExpression(expr)); + }); + exprType = tupleType; + } else if (node instanceof IndexExpressionNode) { + // TODO - need to implement + this._getTypeOfExpression(node.baseExpression); + this._getTypeOfExpression(node.indexExpression); + } else if (node instanceof ListNode) { + node.entries.forEach(expr => { + this._getTypeOfExpression(expr); + }); + exprType = TypeAnnotation.getBuiltInObject(this._currentScope, 'list'); + } else if (node instanceof SliceExpressionNode) { + // TODO - need to implement + if (node.startValue) { + this._getTypeOfExpression(node.startValue); + } + if (node.endValue) { + this._getTypeOfExpression(node.endValue); + } + if (node.stepValue) { + this._getTypeOfExpression(node.stepValue); + } + exprType = TypeAnnotation.getBuiltInObject(this._currentScope, 'set'); + } else if (node instanceof AwaitExpressionNode) { + // TODO - need to implement + exprType = this._getTypeOfExpression(node.expression); + } else if (node instanceof ConditionalExpressionNode) { + this._getTypeOfExpression(node.ifExpression); + + let leftType = this._getTypeOfExpression(node.leftExpression); + let rightType = this._getTypeOfExpression(node.elseExpression); + exprType = TypeUtils.combineTypes(leftType, rightType); + } else if (node instanceof ListComprehensionNode) { + // TODO - need to implement + this._getTypeOfExpression(node.baseExpression); + exprType = TypeAnnotation.getBuiltInObject(this._currentScope, 'list'); + } else if (node instanceof DictionaryNode) { + exprType = TypeAnnotation.getBuiltInObject(this._currentScope, 'dict'); + } else if (node instanceof LambdaNode) { + exprType = AnalyzerNodeInfo.getExpressionType(node); + } else if (node instanceof SetNode) { + node.entries.forEach(expr => { + this._getTypeOfExpression(expr); + }); + exprType = TypeAnnotation.getBuiltInObject(this._currentScope, 'set'); + } else if (node instanceof AssignmentNode) { + this._getTypeOfExpression(node.rightExpression); + exprType = this._getTypeOfExpression(node.leftExpression); + } else if (node instanceof YieldExpressionNode) { + exprType = this._getTypeOfExpression(node.expression); + } else { + // TODO - need to finish + this._addError(`Unsupported expression type'`, node); + } + + if (!exprType) { + exprType = UnknownType.create(); + } + + // Cache the type so we don't need to compute it again. + this._updateExpressionTypeForNode(node, exprType); + + return exprType; + } + + private _getTypeOfMemberAccessNode(node: MemberAccessExpressionNode): Type | undefined { + let exprType: Type | undefined; + let leftType = this._getTypeOfExpression(node.leftExpression); + let memberName = node.memberName.nameToken.value; + + if (memberName && !leftType.isAny()) { + if (leftType instanceof ObjectType) { + let classMemberType = TypeUtils.lookUpClassMember( + leftType.getClassType(), node.memberName.nameToken.value, true); + if (classMemberType) { + exprType = TypeUtils.getEffectiveTypeOfMember(classMemberType); + if (exprType instanceof PropertyType) { + exprType = exprType.getEffectiveReturnType(); + } + } + } else if (leftType instanceof ClassType) { + let classMemberType = TypeUtils.lookUpClassMember( + leftType, node.memberName.nameToken.value); + if (classMemberType) { + exprType = TypeUtils.getEffectiveTypeOfMember(classMemberType); + if (exprType instanceof PropertyType) { + exprType = exprType.getEffectiveReturnType(); + } + } + } else if (leftType instanceof ModuleType) { + const moduleFields = leftType.getFields(); + let fieldInfo = moduleFields.get(memberName); + if (fieldInfo) { + exprType = fieldInfo.currentType; + } + } else if (leftType instanceof PropertyType) { + // TODO - handle this case properly. This is hit + // when we encounter the pattern "@prop.setter" for + // defining setters. + exprType = new FunctionType(FunctionTypeFlags.None); + } + } + + return exprType; + } + + private _getTypeOfCallNode(node: CallExpressionNode, callType: Type): Type | undefined { + let exprType: Type | undefined; + + if (callType.isAny()) { + exprType = UnknownType.create(); + } else { + let skipFirstMethodParam = this._isCallOnObjectOrClass(node); + if (callType instanceof FunctionType) { + exprType = callType.getEffectiveReturnType(); + } else if (callType instanceof OverloadedFunctionType) { + // Determine which of the overloads (if any) match. + let functionType = this._findOverloadedFunctionType( + callType, node, skipFirstMethodParam); + if (functionType) { + exprType = functionType.getEffectiveReturnType(); + } + } else if (callType instanceof ClassType) { + if (callType.isBuiltIn()) { + const className = callType.getClassName(); + if (className === 'type') { + // Handle the 'type' call specially. + if (node.arguments.length >= 1) { + let argType = this._getTypeOfExpression( + node.arguments[0].valueExpression); + if (argType instanceof ObjectType) { + exprType = argType.getClassType(); + } + } + + // If the parameter to type() is not statically known, + // fall back to unknown. + if (!exprType) { + exprType = UnknownType.create(); + } + } else if (className === 'TypeVar') { + exprType = TypeAnnotation.getTypeVarType(node, + this._currentScope, this._getConditionalDiagnosticSink()); + } else if (className === 'NamedTuple') { + // Handle the NamedTuple case specially because it's a class factory. + exprType = TypeAnnotation.getNamedTupleType(node, true, + this._currentScope, this._getConditionalDiagnosticSink()); + } + } + + if (!exprType) { + exprType = new ObjectType(callType); + } + } else if (callType instanceof UnionType) { + let returnTypes: Type[] = []; + callType.getTypes().forEach(typeEntry => { + if (typeEntry instanceof NoneType) { + // TODO - ignore None for now. + } else { + let returnType = this._getTypeOfCallNode(node, typeEntry); + if (returnType) { + returnTypes.push(returnType); + } + } + }); + + if (returnTypes.length > 0) { + exprType = TypeUtils.combineTypesArray(returnTypes); + } + } else { + // TODO - report error + } + } + + return exprType; + } + + private _getTypeOfName(name: string): Type | undefined { + let beyondLocalScope = false; + + // Look for the scope that contains the value definition and + // see if it has a declared type. + let scope: Scope | undefined = this._currentScope; + while (scope) { + let symbol = scope.lookUpSymbol(name); + if (symbol) { + let declaration = symbol.declarations ? symbol.declarations[0] : undefined; + + // Was there a defined type hint? + if (declaration && declaration.declaredType) { + return declaration.declaredType; + } + + // If this is a non-variable type (e.g. a class, function, method), we + // can assume that it's not going to be modified outside the local scope. + if (declaration && declaration.category !== SymbolCategory.Variable) { + return symbol.currentType; + } + + // If we haven't already gone beyond the local scope, we can + // trust the current type. If we've moved beyond the local + // scope to some other outer scope (e.g. the global scope), we + // cannot trust the current type. + if (beyondLocalScope) { + return symbol.inferredType.getType(); + } else { + return symbol.currentType; + } + + break; + } + + if (scope.getType() !== ScopeType.Temporary) { + beyondLocalScope = true; + } + scope = scope.getParent(); + } + + return undefined; + } + + private _updateExpressionTypeForNode(node: ParseNode, exprType: Type) { + let oldType = AnalyzerNodeInfo.getExpressionType(node); + AnalyzerNodeInfo.setExpressionTypeVersion(node, this._analysisVersion); + + if (!oldType || !oldType.isSame(exprType)) { + AnalyzerNodeInfo.setExpressionType(node, exprType); + this._setAnalysisChanged(); + } + } + + private _assignTypeToPossibleTuple(target: ExpressionNode, type: Type): void { + if (target instanceof MemberAccessExpressionNode) { + let targetNode = target.leftExpression; + if (targetNode instanceof NameNode) { + if (targetNode.nameToken.value === 'self') { + this._bindMemberVariableToType(target, type, true); + } else if (targetNode.nameToken.value === 'cls') { + this._bindMemberVariableToType(target, type, false); + } + } + + // TODO - need to validate type compatibility for assignment + } else if (target instanceof TupleExpressionNode) { + let assignedTypes = false; + + if (type instanceof TupleType) { + const entryTypes = type.getEntryTypes(); + if (entryTypes.length !== target.expressions.length) { + this._addError( + `Tuple size mismatch: expected ${ target.expressions.length }` + + ` but got ${ entryTypes.length }`, + target); + } else { + target.expressions.forEach((expr, index) => { + // TODO - need to perform better type compatibility checking here + this._assignTypeToPossibleTuple(expr, entryTypes[index]); + }); + assignedTypes = true; + } + } + + if (!assignedTypes) { + // TODO - need to perform better type compatibility checking here + target.expressions.forEach(expr => { + this._assignTypeToPossibleTuple(expr, UnknownType.create()); + }); + } + } else if (target instanceof TypeAnnotationExpressionNode) { + let typeHint = TypeAnnotation.getType(target.typeAnnotation.expression, + this._currentScope, this._getConditionalDiagnosticSink()); + + if (!TypeUtils.canAssignType(typeHint, type)) { + this._addError( + `Expression of type '${ type.asString() }' cannot be assigned to type '${ typeHint.asString() }'`, + target.typeAnnotation.expression); + } + + this._assignTypeToPossibleTuple(target.valueExpression, typeHint); + } else if (target instanceof StarExpressionNode) { + if (target.expression instanceof NameNode) { + let name = target.expression.nameToken; + let declaration: Declaration = { + category: SymbolCategory.Variable, + node: target.expression, + path: this._fileInfo.filePath, + range: convertOffsetsToRange(name.start, name.end, this._fileInfo.lines) + }; + // TODO - need to figure out right type + this._bindNameNodeToType(target.expression, type, declaration); + } + } else if (target instanceof NameNode) { + let name = target.nameToken; + let declaration: Declaration = { + category: SymbolCategory.Variable, + node: target, + path: this._fileInfo.filePath, + range: convertOffsetsToRange(name.start, name.end, this._fileInfo.lines) + }; + this._bindNameNodeToType(target, type, declaration); + } + } + + private _bindMultiPartModuleNameToType(nameParts: NameNode[], type: ModuleType, + declaration?: Declaration): void { + let targetSymbolTable = this._currentScope.getSymbolTable(); + let symbol = new Symbol(type, DefaultTypeSourceId); + if (declaration) { + symbol.addDeclaration(declaration); + } + + for (let i = 0; i < nameParts.length; i++) { + let name = nameParts[i].nameToken.value; + + const targetSymbol = targetSymbolTable.get(name); + if (targetSymbol && targetSymbol.currentType instanceof ModuleType) { + let moduleType = targetSymbol.currentType; + const moduleFields = moduleType.getFields(); + + // Are we replacing a partial module? + if (i === nameParts.length - 1 && moduleType.isPartialModule) { + // Combine the names in the existing partial module into + // the new module's symbol table. + moduleFields.getKeys().forEach(name => { + type.getFields().set(name, moduleFields.get(name)!); + }); + targetSymbolTable.set(name, symbol); + } + + targetSymbolTable = moduleFields; + } else if (i === nameParts.length - 1) { + targetSymbolTable.set(name, symbol); + if (declaration) { + AnalyzerNodeInfo.setDeclaration(nameParts[i], declaration); + } + } else { + // Build a "partial module" to contain the references + // to the next part of the name. + let newPartialModule = new ModuleType(new SymbolTable()); + newPartialModule.setIsPartialModule(); + targetSymbolTable.set(name, new Symbol(newPartialModule, DefaultTypeSourceId)); + targetSymbolTable = newPartialModule.getFields(); + } + } + } + + private _bindNameNodeToType(nameNode: NameNode, type: Type, declaration?: Declaration) { + const name = nameNode.nameToken.value; + this._bindNameToType(name, type, AnalyzerNodeInfo.getTypeSourceId(nameNode), declaration); + + // Set the declaration on itself so hovering over the definition will + // provide hover information. + let symbolDeclaration = declaration; + if (!symbolDeclaration) { + // If the caller didn't specify a declaration, look it up. + const symbolWithScope = this._currentScope.lookUpSymbolRecursive(nameNode.nameToken.value); + if (symbolWithScope && symbolWithScope.symbol && symbolWithScope.symbol.declarations) { + symbolDeclaration = symbolWithScope.symbol.declarations[0]; + } + } + if (symbolDeclaration) { + AnalyzerNodeInfo.setDeclaration(nameNode, symbolDeclaration); + } + } + + private _bindNameToType(name: string, type: Type, typeSourceId: TypeSourceId, + declaration?: Declaration) { + // If this is a temporary scope, it may not yet have the name + // added. We'll add it here because bindName expects it + // to be present already. + if (!this._currentScope.lookUpSymbol(name)) { + this._currentScope.addUnboundSymbol(name); + } + + this._currentScope.setSymbolCurrentType(name, type, typeSourceId); + if (declaration) { + this._currentScope.addSymbolDeclaration(name, declaration); + } + } + + private _getEnclosingClass(node: ParseNode): ClassNode | undefined { + let curNode = node.parent; + while (curNode) { + if (curNode instanceof ClassNode) { + return curNode; + } + + curNode = curNode.parent; + } + + return undefined; + } + + private _getEnclosingFunction(node: ParseNode): FunctionNode | undefined { + let curNode = node.parent; + while (curNode) { + if (curNode instanceof FunctionNode) { + return curNode; + } + if (curNode instanceof ClassNode) { + return undefined; + } + + curNode = curNode.parent; + } + + return undefined; + } + + private _assignTypeForPossibleEnumeration(node: NameNode, typeOfExpr?: Type): boolean { + let enumClassInfo = this._getEnclosingEnumClassInfo(node); + if (enumClassInfo) { + if (typeOfExpr && !TypeUtils.canAssignType(enumClassInfo.valueType, typeOfExpr)) { + this._addError( + `Expression of type '${ typeOfExpr.asString() }' cannot be assigned ` + + `to type '${ enumClassInfo.valueType.asString() }'`, + node); + } else { + // The type of each enumerated item is an instance of the enum class. + let enumObj = new ObjectType(enumClassInfo.enumClass); + this._assignTypeToPossibleTuple(node, enumObj); + } + + return true; + } + + return false; + } + + // If the node is within a class that derives from the metaclass + // "EnumMeta", we need to treat assignments differently. + private _getEnclosingEnumClassInfo(node: ParseNode): EnumClassInfo | undefined { + let enclosingClassNode = this._getEnclosingClass(node); + if (enclosingClassNode) { + const enumClass = AnalyzerNodeInfo.getExpressionType(enclosingClassNode) as ClassType; + assert(enumClass instanceof ClassType); + + // Handle several built-in classes specially. We don't + // want to interpret their class variables as enumerations. + if (this._fileInfo.isStubFile) { + const className = enumClass.getClassName(); + const builtInEnumClasses = ['Enum', 'IntEnum', 'Flag', 'IntFlag']; + if (builtInEnumClasses.find(c => c === className)) { + return undefined; + } + } + + let metaclass = TypeUtils.getMetaclass(enumClass); + if (metaclass && metaclass instanceof ClassType && metaclass.getClassName() === 'EnumMeta') { + let valueMember = TypeUtils.lookUpClassMember(enumClass, 'value', false); + let valueType: Type; + if (valueMember) { + valueType = TypeUtils.getEffectiveTypeOfMember(valueMember); + } else { + valueType = UnknownType.create(); + } + + return { + enumClass: enumClass, + valueType + }; + } + } + + return undefined; + } + + // Tries to assign the call arguments to the function parameter + // list and reports any mismatches in types or counts. + // If skipFirstMethodParam is true and the callee is a method, + // the logic assumes that it can skip the validation of the first + // parameter because it's a "self" or "cls" parameter. + // This logic is based on PEP 3102: https://www.python.org/dev/peps/pep-3102/ + private _validateFunctionArguments(node: CallExpressionNode, type: FunctionType, + skipFirstMethodParam: boolean) { + let argIndex = 0; + const typeParams = type.getParameters(); + + // If it's a raw function (versus a method call), no need to skip the first parameter. + const skipFirstParam = skipFirstMethodParam && type.isInstanceMethod(); + + // Evaluate all of the argument values and generate errors if appropriate. + // The expression type will be cached in the node so we don't re-evaluate + // it below. + node.arguments.forEach(arg => { + this._getTypeOfExpressionWithTypeConstraints(arg.valueExpression); + }); + + // If the function has decorators, we need to back off because the decorator + // parameter lists may differ from those of the function. + // TODO - improve this + if (type.hasCustomDecorators()) { + return; + } + + // The last parameter might be a var arg dictionary. If so, strip it off. + let hasVarArgDictParam = typeParams.find( + param => param.category === ParameterCategory.VarArgDictionary) !== undefined; + let reportedArgError = false; + + // Build a map of parameters by name. + let paramMap = new StringMap(); + typeParams.forEach((param, index) => { + // Skip the first named param if appropriate. + if (param.name && (index > 0 || !skipFirstParam)) { + paramMap.set(param.name, { + argsNeeded: param.category === ParameterCategory.Simple && !param.hasDefault ? 1 : 0, + argsReceived: 0 + }); + } + }); + + // Is there a bare (nameless) "*" parameter? If so, it signifies the end + // of the positional parameter list. + let positionalParamCount = typeParams.findIndex( + param => param.category === ParameterCategory.VarArgList && !param.name); + + // Is there a var-arg (named "*") parameter? If so, it is the last of + // the positional parameters. + if (positionalParamCount < 0) { + positionalParamCount = typeParams.findIndex( + param => param.category === ParameterCategory.VarArgList); + if (positionalParamCount >= 0) { + positionalParamCount++; + } + } + + // Is there a keyword var-arg ("**") parameter? If so, it's not included + // in the list of positional parameters. + if (positionalParamCount < 0) { + positionalParamCount = typeParams.findIndex( + param => param.category === ParameterCategory.VarArgDictionary); + } + + // If we didn't see any special cases, then all parameters are positional. + if (positionalParamCount < 0) { + positionalParamCount = typeParams.length; + } + + // Determine how many positional args are being passed before + // we see a named arg. + let positionalArgCount = node.arguments.findIndex( + arg => arg.argumentCategory === ArgumentCategory.Dictionary || arg.name !== undefined); + if (positionalArgCount < 0) { + positionalArgCount = node.arguments.length; + } + + // Map the positional args to parameters. + let paramIndex = skipFirstParam ? 1 : 0; + while (argIndex < positionalArgCount) { + if (paramIndex >= positionalParamCount) { + this._addError( + `Expected ${ positionalParamCount } positional argument${ positionalParamCount === 1 ? '' : 's' }`, + node.arguments[argIndex]); + reportedArgError = true; + break; + } + + if (typeParams[paramIndex].category === ParameterCategory.VarArgList) { + // Consume the remaining positional args. + argIndex = positionalArgCount; + } else { + let paramType = typeParams[paramIndex].type; + this._validateArgType(paramType, node.arguments[argIndex].valueExpression); + + // Note that the parameter has received an argument. + const paramName = typeParams[paramIndex].name; + if (paramName) { + paramMap.get(paramName)!.argsReceived++; + } + + argIndex++; + } + + paramIndex++; + } + + if (!reportedArgError) { + let foundDictionaryArg = false; + let foundListArg = node.arguments.find(arg => arg.argumentCategory === ArgumentCategory.List) !== undefined; + + // Now consume any named parameters. + while (argIndex < node.arguments.length) { + if (node.arguments[argIndex].argumentCategory === ArgumentCategory.Dictionary) { + foundDictionaryArg = true; + } else { + // Protect against the case where a non-named argument appears after + // a named argument. This will have already been reported as a parse + // error, but we need to protect against it here. + const paramName = node.arguments[argIndex].name; + if (paramName) { + const paramNameValue = paramName.nameToken.value; + const paramEntry = paramMap.get(paramNameValue); + if (paramEntry) { + if (paramEntry.argsReceived > 0) { + this._addError( + `Parameter '${ paramNameValue }' is already assigned`, paramName); + } else { + paramMap.get(paramName.nameToken.value)!.argsReceived++; + + let paramInfo = typeParams.find(param => param.name === paramNameValue); + assert(paramInfo !== undefined); + this._validateArgType(paramInfo!.type, node.arguments[argIndex].valueExpression); + this._updateExpressionTypeForNode(paramName, paramInfo!.type); + } + } else if (!hasVarArgDictParam) { + this._addError( + `No parameter named '${ paramName.nameToken.value }'`, paramName); + } + } + } + + argIndex++; + } + + // Determine whether there are any parameters that require arguments + // but have not yet received them. If we received a dictionary argument + // (i.e. an arg starting with a "**") or a list argument (i.e. an arg + // starting with a "*"), we will assume that all parameters are matched. + if (!foundDictionaryArg && !foundListArg) { + let unassignedParams = paramMap.getKeys().filter(name => { + const entry = paramMap.get(name)!; + return entry.argsReceived < entry.argsNeeded; + }); + + if (unassignedParams.length > 0) { + this._addError( + `Argument missing for parameter${ unassignedParams.length === 1 ? '' : 's' } ` + + unassignedParams.map(p => `${ p }`).join(', '), node); + } + } + } + } + + private _validateArgType(paramType: Type, argExpression: ExpressionNode) { + let argType = this._getTypeOfExpressionWithTypeConstraints(argExpression); + if (!TypeUtils.canAssignType(paramType, argType)) { + this._addError( + `Argument of type '${ argType.asString() }' cannot be assigned to parameter of type '${ paramType.asString() }'`, + argExpression); + } + } + + // Tries to match the arguments of a call to the constructor for a class. + private _validateConstructorArguments(node: CallExpressionNode, type: ClassType) { + const initMethodType = TypeUtils.lookUpClassMember(type, '__init__'); + if (!initMethodType) { + if (node.arguments.length > 0) { + this._addError( + `Expected 0 arguments to '${ type.getClassName() }' constructor`, node); + } + } else if (initMethodType instanceof FunctionType) { + this._validateFunctionArguments(node, initMethodType, true); + } + } + + private _validateMemberAccess(baseType: Type, memberName: NameNode): boolean { + const memberNameValue = memberName.nameToken.value; + + if (baseType instanceof ObjectType) { + let classMemberInfo = TypeUtils.lookUpClassMember( + baseType.getClassType(), memberNameValue); + if (classMemberInfo) { + if (classMemberInfo.symbol && classMemberInfo.symbol.declarations) { + AnalyzerNodeInfo.setDeclaration(memberName, classMemberInfo.symbol.declarations[0]); + } + return true; + } else { + // See if the class has a "__getattribute__" or "__getattr__" method. + // If so, aribrary members are supported. + let getAttribMember = TypeUtils.lookUpClassMember( + baseType.getClassType(), '__getattribute__'); + if (getAttribMember && getAttribMember.class) { + const isObjectClass = getAttribMember.class.isBuiltIn() && + getAttribMember.class.getClassName() === 'object'; + // The built-in 'object' class, from which every class derives, + // implements the default __getattribute__ method. We want to ignore + // this one. If this method is overridden, we need to assume that + // all members can be accessed. + if (!isObjectClass) { + return true; + } + } + + let getAttrMember = TypeUtils.lookUpClassMember( + baseType.getClassType(), '__getattr__'); + if (getAttrMember) { + return true; + } + + // If the class has decorators, there may be additional fields + // added that we don't know about. + // TODO - figure out a better approach here. + if (!baseType.getClassType().hasDecorators()) { + this._addError( + `'${ memberNameValue }' is not a known member of type '${ baseType.asString() }'`, + memberName); + } + return false; + } + } + + if (baseType instanceof ModuleType) { + let moduleMemberInfo = baseType.getFields().get(memberNameValue); + if (!moduleMemberInfo) { + this._addError( + `'${ memberNameValue }' is not a known member of module`, + memberName); + return false; + } + + if (moduleMemberInfo.declarations) { + AnalyzerNodeInfo.setDeclaration(memberName, moduleMemberInfo.declarations[0]); + } + return true; + } + + if (baseType instanceof ClassType) { + let classMemberInfo = TypeUtils.lookUpClassMember(baseType, memberNameValue, false); + if (!classMemberInfo) { + // If the class has decorators, there may be additional fields + // added that we don't know about. + // TODO - figure out a better approach here. + if (!baseType.hasDecorators()) { + this._addError( + `'${ memberNameValue }' is not a known member of '${ baseType.asString() }'`, + memberName); + } + return false; + } + + if (classMemberInfo.symbol && classMemberInfo.symbol.declarations) { + AnalyzerNodeInfo.setDeclaration(memberName, classMemberInfo.symbol.declarations[0]); + } + return true; + } + + if (baseType instanceof UnionType) { + // TODO - need to add extra logic to determine whether it's safe + // to simplfy the type at this point in the program. + let simplifiedType = baseType.removeOptional(); + if (simplifiedType instanceof UnionType) { + for (let t of simplifiedType.getTypes()) { + if (!this._validateMemberAccess(t, memberName)) { + return false; + } + } + return true; + } + + return this._validateMemberAccess(simplifiedType, memberName); + } + + if (baseType instanceof UnboundType) { + this._addError( + `'${ memberNameValue }' cannot be accessed from unbound variable`, memberName); + return false; + } + + if (baseType instanceof PropertyType) { + // TODO - need to implement this check + return true; + } + + if (baseType instanceof FunctionType) { + // TODO - need to implement this check + return true; + } + + if (baseType instanceof TypeVarType) { + // TODO - need to handle this check + return true; + } + + if (!baseType.isAny()) { + this._addError( + `'${ memberNameValue }' is not a known member of type ${ baseType.asString() }`, memberName); + return false; + } + + return true; + } + + private _useExpressionTypeConstraint(typeConstraints: TypeConstraintResults | undefined, + useIfClause: boolean, callback: () => void) { + + // Push the specified constraints onto the list. + let itemsToPop = 0; + if (typeConstraints) { + let constraintsToUse = useIfClause ? + typeConstraints.ifConstraints : typeConstraints.elseConstraints; + constraintsToUse.forEach(tc => { + this._expressionTypeConstraints.push(tc); + itemsToPop++; + }); + } + + callback(); + + // Clean up after ourself. + for (let i = 0; i < itemsToPop; i++) { + this._expressionTypeConstraints.pop(); + } + } + + private _buildTypeConstraints(node: ExpressionNode) { + return TypeConstraintBuilder.buildTypeConstraints(node, + (node: ExpressionNode) => this._getTypeOfExpressionWithTypeConstraints(node)); + } + + private _applyTypeConstraint(node: ExpressionNode, type: Type): Type { + // Apply constraints associated with the expression we're + // currently walking. + this._expressionTypeConstraints.forEach(constraint => { + type = constraint.applyToType(node, type); + }); + + // Apply constraints from the current scope and its outer scopes. + return this._applyScopeTypeConstraintRecursive(node, type); + } + + private _applyScopeTypeConstraintRecursive(node: ExpressionNode, type: Type, + scope = this._currentScope): Type { + // If we've hit a permanent scope, don't recurse any further. + if (scope.getType() !== ScopeType.Temporary) { + return type; + } + + // Recursively allow the parent scopes to apply their type constraints. + const parentScope = scope.getParent(); + if (parentScope) { + type = this._applyScopeTypeConstraintRecursive(node, type, parentScope); + } + + // Apply the constraints within the current scope. + scope.getTypeConstraints().forEach(constraint => { + type = constraint.applyToType(node, type); + }); + + return type; + } + + private _enterTemporaryScope(callback: () => void, isConditional?: boolean, + isNotExecuted?: boolean) { + let prevScope = this._currentScope; + let newScope = new Scope(ScopeType.Temporary, prevScope); + if (isConditional) { + newScope.setConditional(); + } + if (this._currentScope.isNotExecuted() || isNotExecuted) { + newScope.setIsNotExecuted(); + } + this._currentScope = newScope; + + callback(); + + this._currentScope = prevScope; + return newScope; + } + + private _enterScope(node: ParseNode, callback: () => void): Scope { + let prevScope = this._currentScope; + let newScope = AnalyzerNodeInfo.getScope(node); + assert(newScope !== undefined); + this._currentScope = newScope!; + + // Enter a new temporary scope so we don't pollute the + // namespace of the permanent scope. For example, if code + // within a function assigns a value to a globally-bound + // variable, we want to track the type of that variable + // within this scope and then combine it back to the + // global scope at the end, not add it to the function's + // permanent scope. + const tempScope = this._enterTemporaryScope(() => { + callback(); + }); + this._mergeToCurrentScope(tempScope); + + this._currentScope = prevScope; + + return newScope!; + } + + private _suppressDiagnostics(callback: () => void) { + // Temporarily suppress diagnostics. + let prevSuppressDiagnostics = this._isDiagnosticsSuppressed; + this._isDiagnosticsSuppressed = true; + + callback(); + + this._isDiagnosticsSuppressed = prevSuppressDiagnostics; + } + + private _addError(message: string, textRange: TextRange) { + // Don't emit error if the scope is guaranteed not to be executed. + if (!this._currentScope.isNotExecuted() && !this._isDiagnosticsSuppressed) { + this._fileInfo.diagnosticSink.addErrorWithTextRange(message, textRange); + } + } + + private _getConditionalDiagnosticSink(): TextRangeDiagnosticSink { + // If the current scope isn't executed, create a dummy sink + // for any errors that are reported. + if (this._currentScope.isNotExecuted() && !this._isDiagnosticsSuppressed) { + return new TextRangeDiagnosticSink(this._fileInfo.lines); + } + + return this._fileInfo.diagnosticSink; + } + + private _setAnalysisChanged() { + this._didAnalysisChange = true; + } +} diff --git a/server/src/analyzer/typeAnnotation.ts b/server/src/analyzer/typeAnnotation.ts new file mode 100644 index 000000000..0151177f4 --- /dev/null +++ b/server/src/analyzer/typeAnnotation.ts @@ -0,0 +1,759 @@ +/* +* typeAnnotation.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Class that handles interpretation of type annotations, +* converting the parsed annotation into an internal type +* that can be used for type analysis. +*/ + +import { TextRangeDiagnosticSink } from '../common/diagnosticSink'; +import StringMap from '../common/stringMap'; +import { ArgumentCategory, CallExpressionNode, ConstantNode, DictionaryNode, + EllipsisNode, ExpressionNode, FunctionNode, IndexExpressionNode, ListNode, + MemberAccessExpressionNode, NameNode, NumberNode, ParameterCategory, + SetNode, StringNode, TupleExpressionNode } from '../parser/parseNodes'; +import { KeywordToken, KeywordType, QuoteTypeFlags, TokenType } from '../parser/tokenizerTypes'; +import { AnalyzerNodeInfo } from './analyzerNodeInfo'; +import { DefaultTypeSourceId } from './inferredType'; +import { ParseTreeUtils } from './parseTreeUtils'; +import { Scope, ScopeType } from './scope'; +import { Symbol } from './symbol'; +import { AnyType, ClassType, ClassTypeFlags, EllipsisType, + FunctionParameter, FunctionType, FunctionTypeFlags, ModuleType, NoneType, ObjectType, + OverloadedFunctionType, PropertyType, TupleType, Type, TypeVarType, UnionType, UnknownType } from './types'; +import { TypeUtils } from './typeUtils'; + +export class TypeAnnotation { + static getTypeFromName(node: NameNode, currentScope: Scope, diagSink: TextRangeDiagnosticSink, + classNamesImplyObjects = true, transformBuiltInTypes = true): Type | undefined { + let symbolInScope = currentScope.lookUpSymbolRecursive(node.nameToken.value); + if (!symbolInScope) { + return undefined; + } + + let type = symbolInScope.symbol.currentType; + if (type instanceof ClassType && type.isBuiltIn() && transformBuiltInTypes) { + const className = type.getClassName(); + switch (className) { + case 'Callable': { + // A 'Callable' with no parameters is a generic function. + type = this.getCallableType(undefined, currentScope, diagSink); + break; + } + + case 'ChainMap': + case 'DefaultDict': + case 'Deque': + case 'Dict': + case 'FrozenSet': + case 'List': + case 'Set': + case 'Tuple': + case 'Type': { + type = this.getBuiltInType(currentScope, className.toLowerCase()); + break; + } + + case 'Union': { + diagSink.addErrorWithTextRange( + `Expected type parameters after ${ className }`, node); + break; + } + + case 'ClassVar': + case 'Counter': + case 'Final': + case 'Generic': + case 'Literal': + case 'Optional': { + diagSink.addErrorWithTextRange( + `Expected one type parameter after ${ className }`, node); + break; + } + } + } + + if (type instanceof ClassType) { + if (classNamesImplyObjects) { + type = new ObjectType(type); + } + } + return type; + } + + static getType(node: ExpressionNode, currentScope: Scope, diagSink: TextRangeDiagnosticSink, + classNamesImplyObjects = true, transformBuiltInTypes = true): Type { + let type: Type | undefined; + + if (node instanceof NameNode) { + type = this.getTypeFromName(node, currentScope, + diagSink, false, transformBuiltInTypes); + } else if (node instanceof EllipsisNode) { + type = EllipsisType.create(); + } else if (node instanceof ConstantNode) { + if (node.token.type === TokenType.Keyword) { + if (node.token.keywordType === KeywordType.None) { + type = NoneType.create(); + } else if (node.token.keywordType === KeywordType.True || + node.token.keywordType === KeywordType.False || + node.token.keywordType === KeywordType.Debug) { + type = this.getBuiltInType(currentScope, 'bool'); + } + } + } else if (node instanceof MemberAccessExpressionNode) { + let baseType = TypeAnnotation.getType(node.leftExpression, currentScope, + diagSink, true, false); + let memberName = node.memberName.nameToken.value; + + if (baseType.isAny()) { + type = baseType; + } else if (baseType instanceof ModuleType) { + let fieldInfo = baseType.getFields().get(memberName); + if (fieldInfo) { + type = fieldInfo.currentType; + } else { + diagSink.addErrorWithTextRange( + `'${ memberName }' is not a known member of module`, node.memberName); + type = UnknownType.create(); + } + } else if (baseType instanceof ClassType) { + let fieldInfo = TypeUtils.lookUpClassMember(baseType, memberName); + if (fieldInfo) { + type = TypeUtils.getEffectiveTypeOfMember(fieldInfo); + } else { + diagSink.addErrorWithTextRange( + `'${ memberName }' is not a known member of '${ baseType.asString() }'`, + node.memberName); + type = UnknownType.create(); + } + } else if (baseType instanceof ObjectType) { + let fieldInfo = TypeUtils.lookUpClassMember(baseType.getClassType(), memberName); + if (fieldInfo) { + type = TypeUtils.getEffectiveTypeOfMember(fieldInfo); + } else { + diagSink.addErrorWithTextRange( + `'${ memberName }' is not a known member of '${ baseType.asString() }'`, + node.memberName); + type = UnknownType.create(); + } + } + } else if (node instanceof IndexExpressionNode) { + let baseType = TypeAnnotation.getType(node.baseExpression, currentScope, + diagSink, false, false); + + if (baseType.isAny()) { + type = baseType; + } else if (baseType instanceof ClassType) { + if (baseType instanceof ClassType && baseType.isSpecialBuiltIn()) { + const className = baseType.getClassName(); + switch (className) { + case 'Callable': { + type = this.getCallableType(node.indexExpression, currentScope, diagSink); + break; + } + + case 'Optional': { + type = this.getOptionalType(node.indexExpression, currentScope, diagSink); + break; + } + + case 'Type': { + type = this.getTypeType(node.indexExpression, currentScope, diagSink); + classNamesImplyObjects = false; + break; + } + + case 'ClassVar': + case 'Deque': + case 'Generic': + case 'List': + case 'FrozenSet': + case 'Set': { + type = this.getOneParameterType(className, node.indexExpression, + currentScope, diagSink); + break; + } + + case 'ChainMap': + case 'Dict': + case 'DefaultDict': { + type = this.getTwoParameterType(className, node.indexExpression, + currentScope, diagSink); + break; + } + + case 'Protocol': + case 'Tuple': { + type = this.getArbitraryParameterType(className, node.indexExpression, + currentScope, diagSink); + break; + } + + case 'Union': { + type = this.getUnionType(node.indexExpression, currentScope, diagSink); + break; + } + + default: { + // TODO - need to handle more + type = UnknownType.create(); + diagSink.addErrorWithTextRange( + `'Unsupported type expression: indexed ${ baseType.asString() }`, + node.baseExpression); + break; + } + } + } + + if (!type) { + // TODO - need to implement + type = UnknownType.create(); + // diagSink.addErrorWithTextRange( + // `'Unsupported type expression: indexed ${ baseType.asString() }`, + // node.baseExpression); + } + } else if (baseType instanceof FunctionType) { + // TODO - need to implement generic function support + type = this.getCallableType(undefined, currentScope, diagSink); + } else { + diagSink.addErrorWithTextRange( + `'Unsupported type expression: indexed other (${ baseType.asString() })`, + node.baseExpression); + } + } else if (node instanceof TupleExpressionNode) { + let tupleType = new TupleType(this.getBuiltInType(currentScope, 'tuple') as ClassType); + node.expressions.forEach(expr => { + tupleType.addEntryType(TypeAnnotation.getType(expr, + currentScope, diagSink, classNamesImplyObjects)); + }); + type = tupleType; + } else if (node instanceof StringNode) { + if (node.tokens[0].quoteTypeFlags & QuoteTypeFlags.Byte) { + type = this.getBuiltInType(currentScope, 'byte'); + } else { + type = this.getBuiltInType(currentScope, 'str'); + } + } else if (node instanceof NumberNode) { + if (node.token.isInteger) { + type = this.getBuiltInType(currentScope, 'int'); + } else { + type = this.getBuiltInType(currentScope, 'float'); + } + } else if (node instanceof CallExpressionNode) { + let baseType = TypeAnnotation.getType(node.leftExpression, currentScope, diagSink, false); + if (baseType instanceof ClassType && baseType.isBuiltIn()) { + const className = baseType.getClassName(); + + if (className === 'TypeVar') { + type = this.getTypeVarType(node, currentScope, diagSink); + } else if (className === 'NamedTuple') { + type = this.getNamedTupleType(node, true, currentScope, diagSink); + classNamesImplyObjects = false; + } else { + type = UnknownType.create(); + diagSink.addErrorWithTextRange(`'${ className }' is not callable`, node); + } + } else if (baseType instanceof FunctionType) { + // The stdlib collections.pyi stub file defines namedtuple as a function + // rather than a class, so we need to check for it here. + if (node.leftExpression instanceof NameNode && node.leftExpression.nameToken.value === 'namedtuple') { + type = this.getNamedTupleType(node, false, currentScope, diagSink); + classNamesImplyObjects = false; + } else { + type = baseType.getEffectiveReturnType(); + } + } else if (baseType.isAny()) { + type = UnknownType.create(); + } + + if (type === undefined) { + type = baseType; + diagSink.addErrorWithTextRange( + `'Unsupported type expression: call`, node); + } + } else if (node instanceof ListNode) { + // TODO - need to implement + type = UnknownType.create(); + // diagSink.addErrorWithTextRange( + // `'Unsupported type expression: list`, node); + } else if (node instanceof DictionaryNode) { + // TODO - need to implement + type = UnknownType.create(); + diagSink.addErrorWithTextRange( + `'Unsupported type expression: dictionary`, node); + } else if (node instanceof SetNode) { + // TODO - need to implement + type = UnknownType.create(); + diagSink.addErrorWithTextRange( + `'Unsupported type expression: set`, node); + } + + if (type) { + if (type instanceof ClassType && classNamesImplyObjects) { + type = new ObjectType(type); + } + return type; + } + + diagSink.addErrorWithTextRange( + `Unknown type '${ ParseTreeUtils.printExpression(node) }'`, node); + return UnknownType.create(); + } + + // Unpacks the index expression for an Optional type annotation. + static getOptionalType(indexExpression: ExpressionNode, currentScope: Scope, + diagSink: TextRangeDiagnosticSink): Type { + + let type = this.getType(indexExpression, currentScope, diagSink); + return TypeUtils.combineTypes(type, NoneType.create()); + } + + // Unpacks the index expression for a Type type annotation. + static getTypeType(indexExpression: ExpressionNode, currentScope: Scope, + diagSink: TextRangeDiagnosticSink): Type { + + let type = this.getType(indexExpression, currentScope, diagSink); + if (type instanceof ObjectType) { + return type.getClassType(); + } else if (type instanceof TypeVarType) { + // TODO - remove once we support type var processing + } else if (!type.isAny()) { + diagSink.addErrorWithTextRange('Expected type parameter after Type', + indexExpression); + } + + return UnknownType.create(); + } + + // Unpacks the index expression for a Union type annotation. + static getUnionType(indexExpression: ExpressionNode, currentScope: Scope, + diagSink: TextRangeDiagnosticSink): UnionType { + let unionType = new UnionType(); + + if (indexExpression instanceof TupleExpressionNode) { + indexExpression.expressions.forEach(expr => { + let type = this.getType(expr, currentScope, diagSink); + if (type instanceof UnionType) { + type.getTypes().forEach(t => { + unionType.addType(t); + }); + } else { + unionType.addType(type); + } + }); + } else { + unionType.addType(this.getType(indexExpression, currentScope, diagSink)); + } + + return unionType; + } + + // Unpacks the index expression for a Callable type annotation. It should + // have zero to two parameters. The first parameter, if present, should be + // either an ellipsis or a list of parameter types. The second parameter, if + // present, should specify the return type. + static getCallableType(node: ExpressionNode | undefined, + currentScope: Scope, diagSink: TextRangeDiagnosticSink): FunctionType { + let functionType = new FunctionType(FunctionTypeFlags.None); + functionType.setDeclaredReturnType(AnyType.create()); + let paramList: Type[] | undefined; + + if (node) { + if (node instanceof TupleExpressionNode) { + if (node.expressions.length === 0) { + diagSink.addErrorWithTextRange( + `Expected parameter type list or '...'`, node); + } + + paramList = this._getCallableParameterTypeList( + node.expressions[0], currentScope, diagSink); + + if (node.expressions.length > 1) { + functionType.setDeclaredReturnType(this.getType( + node.expressions[1], currentScope, diagSink)); + } + + if (node.expressions.length > 2) { + diagSink.addErrorWithTextRange( + `Expected at most two parameters`, node.expressions[2]); + } + } else { + paramList = this._getCallableParameterTypeList( + node, currentScope, diagSink); + } + } + + if (paramList !== undefined) { + paramList.forEach((paramType, index) => { + functionType.addParameter({ + category: ParameterCategory.Simple, + name: `p${ index.toString() }`, + type: paramType + }); + }); + } else { + TypeUtils.addDefaultFunctionParameters(functionType); + } + + return functionType; + } + + private static _getCallableParameterTypeList(node: ExpressionNode, currentScope: Scope, + diagSink: TextRangeDiagnosticSink): Type[] | undefined { + let typeList: Type[] = []; + + if (node instanceof EllipsisNode) { + return undefined; + } else if (node instanceof ListNode) { + node.entries.forEach(entry => { + typeList.push(this.getType(entry, currentScope, diagSink)); + }); + } else { + diagSink.addErrorWithTextRange( + `Expected parameter type list or '...'`, node); + } + + return typeList; + } + + static getOneParameterType(className: string, indexExpression: ExpressionNode, + currentScope: Scope, diagSink: TextRangeDiagnosticSink): Type { + // let typeParam = this.getType(indexExpression, currentScope, diagSink, false); + + return this.getBuiltInType(currentScope, className.toLowerCase()); + } + + static getTwoParameterType(className: string, indexExpression: ExpressionNode, + currentScope: Scope, diagSink: TextRangeDiagnosticSink): Type { + + if (indexExpression instanceof TupleExpressionNode && indexExpression.expressions.length === 2) { + // let keyType = this.getType(indexExpression.expressions[0], currentScope, diagSink, false); + // let valueType = this.getType(indexExpression.expressions[1], currentScope, diagSink, false); + } else { + diagSink.addErrorWithTextRange(`Expected two type parameters after ${ className }`, + indexExpression); + } + + return this.getBuiltInType(currentScope, className.toLowerCase()); + } + + static getArbitraryParameterType(className: string, indexExpression: ExpressionNode, + currentScope: Scope, diagSink: TextRangeDiagnosticSink): Type { + + if (indexExpression instanceof TupleExpressionNode) { + indexExpression.expressions.forEach(expr => { + // let typeParamType = this.getType(expr, currentScope, diagSink, false); + }); + } else { + // let typeParamType = this.getType(indexExpression, currentScope, diagSink, false); + } + + return this.getBuiltInType(currentScope, className.toLowerCase()); + } + + static getTypeVarType(node: CallExpressionNode, currentScope: Scope, + diagSink: TextRangeDiagnosticSink): TypeVarType | undefined { + let typeVarName = ''; + if (node.arguments.length === 0) { + diagSink.addErrorWithTextRange('Expected name of type var', node); + return undefined; + } + + let firstArg = node.arguments[0]; + if (firstArg.valueExpression instanceof StringNode) { + typeVarName = firstArg.valueExpression.getValue(); + } else { + diagSink.addErrorWithTextRange('Expected name of type var as first parameter', + firstArg.valueExpression); + } + + let typeVar = new TypeVarType(typeVarName); + + // Parse the remaining parameters. + for (let i = 1; i < node.arguments.length; i++) { + const paramNameNode = node.arguments[i].name; + const paramName = paramNameNode ? paramNameNode.nameToken.value : undefined; + let paramNameMap = new StringMap(); + + if (paramName) { + if (paramNameMap.get(paramName)) { + diagSink.addErrorWithTextRange( + `Duplicate parameter name '${ paramName }' not allowed`, + node.arguments[i]); + } + + if (paramName === 'bound') { + typeVar.setBoundType(this.getType( + node.arguments[i].valueExpression, + currentScope, diagSink)); + } else if (paramName === 'covariant') { + if (this.getBooleanValue(node.arguments[i].valueExpression, diagSink)) { + if (typeVar.isContravariant()) { + diagSink.addErrorWithTextRange( + `A TypeVar cannot be both covariant and contravariant`, + node.arguments[i]); + } else { + typeVar.setIsCovariant(); + } + } + } else if (paramName === 'contravariant') { + if (this.getBooleanValue(node.arguments[i].valueExpression, diagSink)) { + if (typeVar.isContravariant()) { + diagSink.addErrorWithTextRange( + `A TypeVar cannot be both covariant and contravariant`, + node.arguments[i]); + } else { + typeVar.setIsContravariant(); + } + } + } else { + diagSink.addErrorWithTextRange( + `'${ paramName }' is unknown parameter to TypeVar`, + node.arguments[i]); + } + + paramNameMap.set(paramName, paramName); + } else { + typeVar.addConstraint(this.getType( + node.arguments[i].valueExpression, + currentScope, diagSink)); + } + } + + return typeVar; + } + + // Creates a new custom tuple factory class with named values. + // Supports both typed and untyped variants. + static getNamedTupleType(node: CallExpressionNode, includesTypes: boolean, + currentScope: Scope, diagSink: TextRangeDiagnosticSink): ClassType { + let className = 'namedtuple'; + if (node.arguments.length === 0) { + diagSink.addErrorWithTextRange('Expected named tuple class name as firat parameter', + node.leftExpression); + } else { + const nameArg = node.arguments[0]; + if (nameArg.argumentCategory !== ArgumentCategory.Simple) { + diagSink.addErrorWithTextRange('Expected named tuple class name as firat parameter', + node.arguments[0].valueExpression); + } else if (nameArg.valueExpression instanceof StringNode) { + className = nameArg.valueExpression.getValue(); + } + } + + let classType = new ClassType(className, ClassTypeFlags.None); + const classFields = classType.getClassFields(); + classFields.set('__class__', new Symbol(classType, DefaultTypeSourceId)); + const instanceFields = classType.getInstanceFields(); + + let tupleType = new TupleType(this.getBuiltInType(currentScope, 'tuple') as ClassType); + let constructorType = new FunctionType(FunctionTypeFlags.ClassMethod); + constructorType.setDeclaredReturnType(tupleType); + constructorType.addParameter({ + category: ParameterCategory.Simple, + name: 'cls', + type: classType + }); + + let initType = new FunctionType(FunctionTypeFlags.InstanceMethod); + const selfParameter: FunctionParameter = { + category: ParameterCategory.Simple, + name: 'self', + type: new ObjectType(classType) + }; + initType.setDeclaredReturnType(NoneType.create()); + initType.addParameter(selfParameter); + + if (node.arguments.length < 2) { + diagSink.addErrorWithTextRange('Expected named tuple entry list as second parameter', + node.leftExpression); + } else { + const entriesArg = node.arguments[1]; + if (entriesArg.argumentCategory !== ArgumentCategory.Simple || + !(entriesArg.valueExpression instanceof ListNode)) { + diagSink.addErrorWithTextRange('Expected named tuple entry list as second parameter', + entriesArg.valueExpression); + } else { + const entryList = entriesArg.valueExpression; + let entryMap: { [name: string]: string } = {}; + + entryList.entries.forEach((entry, index) => { + let entryType: Type | undefined; + let entryNameNode: ExpressionNode | undefined; + let entryName = ''; + + if (includesTypes) { + // Handle the variant that includes name/type tuples. + if (entry instanceof TupleExpressionNode && entry.expressions.length === 2) { + entryNameNode = entry.expressions[0]; + entryType = this.getType(entry.expressions[1], currentScope, + diagSink); + } else { + diagSink.addErrorWithTextRange( + 'Expected two-entry tuple specifying entry name and type', entry); + } + } else { + entryNameNode = entry; + entryType = UnknownType.create(); + } + + if (entryNameNode instanceof StringNode) { + entryName = entryNameNode.getValue(); + if (!entryName) { + diagSink.addErrorWithTextRange( + 'Names within a named tuple cannot be empty', entryNameNode); + } + } else { + diagSink.addErrorWithTextRange( + 'Expected string literal for entry name', entryNameNode || entry); + } + + if (!entryName) { + entryName = `_${ index.toString() }`; + } + + if (entryMap[entryName]) { + diagSink.addErrorWithTextRange( + 'Names within a named tuple must be unique', entryNameNode || entry); + } + + // Record names in a map to detect duplicates. + entryMap[entryName] = entryName; + + if (!entryType) { + entryType = UnknownType.create(); + } + + tupleType.addEntryType(entryType); + const paramInfo: FunctionParameter = { + category: ParameterCategory.Simple, + name: entryName, + type: entryType + }; + + constructorType.addParameter(paramInfo); + initType.addParameter(paramInfo); + + instanceFields.set(entryName, new Symbol(entryType, DefaultTypeSourceId)); + }); + } + } + + classFields.set('__new__', new Symbol(constructorType, DefaultTypeSourceId)); + classFields.set('__init__', new Symbol(initType, DefaultTypeSourceId)); + + let keysItemType = new FunctionType(FunctionTypeFlags.None); + keysItemType.setDeclaredReturnType(this.getBuiltInObject(currentScope, 'list')); + classFields.set('keys', new Symbol(keysItemType, DefaultTypeSourceId)); + classFields.set('items', new Symbol(keysItemType, DefaultTypeSourceId)); + + let lenType = new FunctionType(FunctionTypeFlags.InstanceMethod); + lenType.setDeclaredReturnType(this.getBuiltInObject(currentScope, 'int')); + lenType.addParameter(selfParameter); + classFields.set('__len__', new Symbol(lenType, DefaultTypeSourceId)); + + return classType; + } + + static getBooleanValue(node: ExpressionNode, diagSink: TextRangeDiagnosticSink): boolean { + if (node instanceof ConstantNode) { + if (node.token instanceof KeywordToken) { + if (node.token.keywordType === KeywordType.False) { + return false; + } else if (node.token.keywordType === KeywordType.True) { + return true; + } + } + } + + diagSink.addErrorWithTextRange('Expected True or False', node); + return false; + } + + static getBuiltInType(currentScope: Scope, name: string): Type { + // Starting at the current scope, find the built-in scope, which should + // be the top-most parent. + let builtInScope = currentScope; + while (builtInScope.getType() !== ScopeType.BuiltIn) { + builtInScope = builtInScope.getParent()!; + } + + let nameType = builtInScope.lookUpSymbol(name); + if (nameType) { + return nameType.currentType; + } + + return UnknownType.create(); + } + + static getBuiltInObject(currentScope: Scope, className: string): Type { + let nameType = this.getBuiltInType(currentScope, className); + if (nameType instanceof ClassType) { + return new ObjectType(nameType); + } + + return nameType; + } + + // Determines if the function node is a property accessor (getter, setter, deleter). + static getPropertyType(node: FunctionNode, type: FunctionType, currentScope: Scope): PropertyType | undefined { + if (ParseTreeUtils.functionHasDecorator(node, 'property')) { + return new PropertyType(type); + } + + const setterOrDeleterDecorator = node.decorators.find(decorator => { + return decorator.callName instanceof MemberAccessExpressionNode && + decorator.callName.leftExpression instanceof NameNode && + (decorator.callName.memberName.nameToken.value === 'setter' || + decorator.callName.memberName.nameToken.value === 'deleter') && + decorator.arguments.length === 0; + }); + + if (setterOrDeleterDecorator) { + let memberAccessNode = setterOrDeleterDecorator.callName as MemberAccessExpressionNode; + const propertyName = (memberAccessNode.leftExpression as NameNode).nameToken.value; + const isSetter = memberAccessNode.memberName.nameToken.value === 'setter'; + + let curValue = currentScope.lookUpSymbol(propertyName); + + if (curValue && curValue.currentType instanceof PropertyType) { + // TODO - check for duplicates. + // TODO - check for type consistency. + if (isSetter) { + curValue.currentType.setSetter(type); + } else { + curValue.currentType.setDeleter(type); + } + return curValue.currentType; + } + } + + return undefined; + } + + static getOverloadedFunctionType(node: FunctionNode, type: FunctionType, + currentScope: Scope): [OverloadedFunctionType | undefined, boolean] { + + let warnIfDuplicate = true; + let decoratedType: OverloadedFunctionType | undefined; + let typeSourceId = AnalyzerNodeInfo.getTypeSourceId(node); + + // TODO - make sure this overload decorator is the built-in one. + if (ParseTreeUtils.functionHasDecorator(node, 'overload')) { + let existingSymbol = currentScope.lookUpSymbol(node.name.nameToken.value); + if (existingSymbol && existingSymbol.currentType instanceof OverloadedFunctionType) { + existingSymbol.currentType.addOverload(typeSourceId, type); + decoratedType = existingSymbol.currentType; + warnIfDuplicate = false; + } else { + let newOverloadType = new OverloadedFunctionType(); + newOverloadType.addOverload(typeSourceId, type); + decoratedType = newOverloadType; + } + } + + return [decoratedType, warnIfDuplicate]; + } +} diff --git a/server/src/analyzer/typeConstraint.ts b/server/src/analyzer/typeConstraint.ts new file mode 100644 index 000000000..9e1e1e6f2 --- /dev/null +++ b/server/src/analyzer/typeConstraint.ts @@ -0,0 +1,319 @@ +/* +* typeConstraint.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Classes that record an invariant within a conditional scope +* that affect types. For example, the expression "foo" implies +* implies that foo is not None, so "if foo:" implies that the +* the value of "foo" is not None within that scope. +*/ + +import { BinaryExpressionNode, CallExpressionNode, ExpressionNode, + MemberAccessExpressionNode, NameNode, UnaryExpressionNode } from '../parser/parseNodes'; +import { OperatorType } from '../parser/tokenizerTypes'; +import { ClassType, NoneType, ObjectType, TupleType, Type, UnionType } from './types'; +import { TypeUtils } from './typeUtils'; + +export abstract class TypeConstraint { + private _isPositiveTest: boolean; + + constructor(isPositiveTest: boolean) { + this._isPositiveTest = isPositiveTest; + } + + isPositiveTest() { + return this._isPositiveTest; + } + + negate() { + this._isPositiveTest = !this._isPositiveTest; + } + + // Determines whether the expression is one that the type constraint + // module knows how to handle. In general, we need to restrict this + // to expressions whose types cannot change throughout a block of code. + // For now, we support only simple names and member access chains + // that include only simple names (e.g. "A.B.C.D"). + static isSupportedExpression(expression: ExpressionNode) { + if (expression instanceof NameNode) { + return true; + } else if (expression instanceof MemberAccessExpressionNode) { + if (!this.isSupportedExpression(expression.leftExpression)) { + return false; + } + + return true; + } + + return false; + } + + static doesExpressionMatch(expression1: ExpressionNode, expression2: ExpressionNode): boolean { + if (expression1 instanceof NameNode) { + if (expression2 instanceof NameNode) { + return expression1.nameToken.value === expression2.nameToken.value; + } + } else if (expression1 instanceof MemberAccessExpressionNode) { + if (expression2 instanceof MemberAccessExpressionNode) { + return this.doesExpressionMatch(expression1.leftExpression, expression2.leftExpression) && + this.doesExpressionMatch(expression1.memberName, expression2.memberName); + } + } + + return false; + } + + abstract applyToType(node: ExpressionNode, type: Type): Type; +} + +// Represents a simple check for truthiness. It eliminates the +// possibility of "None" for a type. +export class TruthyTypeConstraint extends TypeConstraint { + private _expression: ExpressionNode; + + constructor(node: ExpressionNode, isPositiveTest = true) { + super(isPositiveTest); + this._expression = node; + } + + applyToType(node: ExpressionNode, type: Type): Type { + if (TypeConstraint.doesExpressionMatch(node, this._expression)) { + if (type.isAny()) { + return type; + } + + if (this.isPositiveTest()) { + if (type instanceof UnionType) { + return type.removeOptional(); + } else if (type instanceof NoneType) { + // TODO - we may want to return a "never" type in + // this case to indicate that the condition will + // always evalutate to false. + return NoneType.create(); + } + } else { + if (type instanceof UnionType) { + let remainingTypes = type.getTypes().filter(t => !(t instanceof NoneType)); + if (remainingTypes.length === 0) { + // TODO - we may want to return a "never" type in + // this case to indicate that the condition will + // always evalutate to false. + return NoneType.create(); + } else { + return TypeUtils.combineTypesArray(remainingTypes); + } + } + } + } + + // Return the original type. + return type; + } +} + +// Represents an "instanceof" check, potentially constraining a +// union type. +export class InstanceOfTypeConstraint extends TypeConstraint { + private _expression: ExpressionNode; + private _classTypeList: ClassType[]; + + constructor(node: ExpressionNode, typeList: ClassType[], isPositiveTest = true) { + super(isPositiveTest); + this._expression = node; + this._classTypeList = typeList; + } + + applyToType(node: ExpressionNode, type: Type): Type { + let doInstanceCheck = (objType: ObjectType) => { + const matchingInstance = this._classTypeList.find( + t => TypeUtils.isInstanceOf(objType, t)); + if (this.isPositiveTest()) { + // For a positive test, see if the type is an instance of at + // least one of the class types. + return matchingInstance !== undefined; + } else { + // For a negative test, see if the type is not an instance of + // all class types. + return matchingInstance === undefined; + } + }; + + if (TypeConstraint.doesExpressionMatch(node, this._expression)) { + if (type instanceof UnionType) { + let remainingTypes = type.getTypes().filter(t => { + if (t.isAny()) { + // We need to assume that "Any" is always an instance and not an instance, + // so it matches regardless of whether the test is positive or negative. + return true; + } + + if (t instanceof ObjectType) { + return doInstanceCheck(t); + } + + // All other types are never instances of a class. + return !this.isPositiveTest(); + }); + + if (remainingTypes.length === 0) { + // TODO - we may want to return a "never" type in + // this case to indicate that the condition will + // always evalutate to false. + return NoneType.create(); + } + + return TypeUtils.combineTypesArray(remainingTypes); + } else if (type instanceof ObjectType) { + if (type.isAny()) { + // We need to assume that "Any" is always an instance and not an instance, + // so it matches regardless of whether the test is positive or negative. + return type; + } + + if (doInstanceCheck(type)) { + return type; + } else { + // TODO - we may want to return a "never" type in + // this case to indicate that the condition will + // always evalutate to false. + return NoneType.create(); + } + } + } + + // Return the original type. + return type; + } +} + +export interface TypeConstraintResults { + ifConstraints: TypeConstraint[]; + elseConstraints: TypeConstraint[]; +} + +export class TypeConstraintBuilder { + // Given a test expression (one that's used in an if statement to test a + // conditional), return all of the type constraints that apply both + // within the "if" clause and the "else" clause. + static buildTypeConstraints(testExpression: ExpressionNode, + typeEvaluator: (node: ExpressionNode) => Type): + TypeConstraintResults | undefined { + + if (testExpression instanceof BinaryExpressionNode) { + let results: TypeConstraintResults = { + ifConstraints: [], + elseConstraints: [] + }; + + if (testExpression.operator === OperatorType.And) { + let leftConstraints = this.buildTypeConstraints( + testExpression.leftExpression, typeEvaluator); + let rightConstraints = this.buildTypeConstraints( + testExpression.rightExpression, typeEvaluator); + + // For an AND operator, all of the "if" constraints must be true, + // but we can't make any assumptions about the "else" constraints + // because we can't determine which false evaluation caused the + // AND to become false. + if (leftConstraints) { + results.ifConstraints = leftConstraints.ifConstraints; + } + if (rightConstraints) { + results.ifConstraints = results.ifConstraints.concat(rightConstraints.ifConstraints); + } + if (results.ifConstraints.length === 0) { + return undefined; + } + return results; + } else if (testExpression.operator === OperatorType.Or) { + let leftConstraints = this.buildTypeConstraints( + testExpression.leftExpression, typeEvaluator); + let rightConstraints = this.buildTypeConstraints( + testExpression.rightExpression, typeEvaluator); + + // For an OR operator, all of the negated "else" constraints must be true, + // but we can't make any assumptions about the "if" constraints + // because we can't determine which evaluation caused the + // OR to become true. + if (leftConstraints) { + results.elseConstraints.forEach(c => { + c.negate(); + }); + results.elseConstraints = results.elseConstraints; + } + if (rightConstraints) { + rightConstraints.elseConstraints.forEach(c => { + c.negate(); + }); + results.elseConstraints = results.elseConstraints.concat(rightConstraints.elseConstraints); + } + if (results.elseConstraints.length === 0) { + return undefined; + } + return results; + } + } else if (testExpression instanceof UnaryExpressionNode) { + if (testExpression.operator === OperatorType.Not) { + let constraints = this.buildTypeConstraints( + testExpression.expression, typeEvaluator); + + if (constraints) { + // A not operator simply flips the else and if constraints. + return { + ifConstraints: constraints.elseConstraints, + elseConstraints: constraints.ifConstraints + }; + } + } + } else if (testExpression instanceof NameNode || + testExpression instanceof MemberAccessExpressionNode) { + if (TypeConstraint.isSupportedExpression(testExpression)) { + const trueConstraint = new TruthyTypeConstraint(testExpression, true); + const falseConstraint = new TruthyTypeConstraint(testExpression, false); + return { + ifConstraints: [trueConstraint], + elseConstraints: [falseConstraint] + }; + } + } else if (testExpression instanceof CallExpressionNode) { + if (testExpression.leftExpression instanceof NameNode && + testExpression.leftExpression.nameToken.value === 'isinstance' && + testExpression.arguments.length === 2) { + + // Make sure the first parameter is a supported expression type + // and the second parameter is a valid class type or a tuple + // of valid class types. + const arg0Expr = testExpression.arguments[0].valueExpression; + const arg1Expr = testExpression.arguments[1].valueExpression; + + if (TypeConstraint.isSupportedExpression(arg0Expr)) { + const classType = typeEvaluator(arg1Expr); + + if (classType instanceof ClassType) { + const trueConstraint = new InstanceOfTypeConstraint(arg0Expr, [classType], true); + const falseConstraint = new InstanceOfTypeConstraint(arg0Expr, [classType], false); + return { + ifConstraints: [trueConstraint], + elseConstraints: [falseConstraint] + }; + } else if (classType instanceof TupleType) { + let tupleBaseTypes = classType.getEntryTypes(); + if (tupleBaseTypes.length > 0 && + tupleBaseTypes.find(t => !(t instanceof ClassType)) === undefined) { + const classTypeList = tupleBaseTypes.map(t => t as ClassType); + const trueConstraint = new InstanceOfTypeConstraint(arg0Expr, classTypeList, true); + const falseConstraint = new InstanceOfTypeConstraint(arg0Expr, classTypeList, false); + return { + ifConstraints: [trueConstraint], + elseConstraints: [falseConstraint] + }; + } + } + } + } + } + + return undefined; + } +} diff --git a/server/src/analyzer/typeUtils.ts b/server/src/analyzer/typeUtils.ts new file mode 100644 index 000000000..e1e2bc469 --- /dev/null +++ b/server/src/analyzer/typeUtils.ts @@ -0,0 +1,344 @@ +/* +* typeUtils.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Collection of static methods that operate on Type objects. +*/ + +import * as assert from 'assert'; + +import { ParameterCategory } from '../parser/parseNodes'; +import { Symbol } from './symbol'; +import { ClassType, FunctionType, ObjectType, OverloadedFunctionType, + TupleType, Type, TypeCategory, TypeVarType, UnboundType, + UnionType, + UnknownType } from './types'; + +export interface ClassMember { + symbol?: Symbol; + isInstanceMember: boolean; + class?: ClassType; +} + +export class TypeUtils { + // Combines two types into a single type. If the types are + // the same, only one is returned. If they differ, they + // are combined into a UnionType. + static combineTypes(type1: Type, type2: Type): Type { + if (type1.isSame(type2)) { + return type1; + } + + let unionType = new UnionType(); + + if (type1 instanceof UnionType) { + unionType.addTypes(type1.getTypes()); + } else { + unionType.addTypes([type1]); + } + + if (type2 instanceof UnionType) { + unionType.addTypes(type2.getTypes()); + } else { + unionType.addTypes([type2]); + } + + return unionType; + } + + static combineTypesArray(types: Type[]): Type { + assert(types.length > 0); + + let resultingType = types[0]; + types.forEach((t, index) => { + if (index > 0) { + resultingType = this.combineTypes(resultingType, t); + } + }); + + return resultingType; + } + + static isInstanceOf(objectType: ObjectType, classType: ClassType): boolean { + return objectType.getClassType().isDerivedFrom(classType); + } + + static canAssignType(destType: Type, srcType: Type): boolean { + if (srcType instanceof UnionType) { + // For union sources, all of the types need to be assignable to the dest. + return srcType.getTypes().find(t => !this.canAssignType(destType, t)) === undefined; + } + + if (destType instanceof UnionType) { + // For union destinations, we just need to match one of the types. + return destType.getTypes().find(t => this.canAssignType(t, srcType)) !== undefined; + } + + if (destType.isAny() || srcType.isAny()) { + return true; + } + + if (destType.category === TypeCategory.Unbound || + srcType.category === TypeCategory.Unbound) { + return false; + } + + if (destType.category === TypeCategory.None && srcType.category === TypeCategory.None) { + return true; + } + + if (srcType instanceof TypeVarType) { + // TODO - remove this once we properly resolve generic types + return true; + } + + if (destType instanceof TypeVarType) { + // TODO - remove this once we properly resolve generic types + return true; + } + + if (destType instanceof ObjectType) { + const destClassType = destType.getClassType(); + + // Construct a generic tuple object using the built-in tuple + // class so we can perform a comparison. + if (srcType instanceof TupleType) { + srcType = new ObjectType(srcType.getBaseClass()); + } + + if (srcType instanceof ObjectType) { + return this.canAssignClassType(destClassType, srcType.getClassType()); + } + } + + if (srcType instanceof ClassType) { + // Is the dest a generic "type" object? + if (destType instanceof ObjectType) { + const destClassType = destType.getClassType(); + if (destClassType.isBuiltIn()) { + const destClassName = destClassType.getClassName(); + if (destClassName === 'type') { + return true; + } + } + } + + if (destType instanceof ClassType) { + return this.canAssignClassType(destType, srcType); + } + } + + if (destType instanceof FunctionType) { + let srcFunction: FunctionType | undefined; + + if (srcType instanceof OverloadedFunctionType) { + // TODO - need to find first overloaded function + // that matches the parameters. + const overloads = srcType.getOverloads(); + if (overloads.length > 0) { + srcFunction = overloads[0].type; + } + } else if (srcType instanceof FunctionType) { + srcFunction = srcType; + } else if (srcType instanceof ObjectType) { + const callMember = this.lookUpObjectMember(srcType, '__call__'); + if (callMember) { + const callType = TypeUtils.getEffectiveTypeOfMember(callMember); + if (callType instanceof FunctionType) { + srcFunction = callType; + } + } + } else if (srcType instanceof ClassType) { + // TODO - need to create function corresponding to constructor for class + } + + if (srcFunction) { + // TODO - validate parameters + return true; + } + } + + if (destType instanceof TupleType && srcType instanceof TupleType) { + const destEntries = destType.getEntryTypes(); + const srcEntries = srcType.getEntryTypes(); + + if (destEntries.length !== srcEntries.length) { + return false; + } + + if (srcEntries.find((srcEntry, index) => !this.canAssignType(destEntries[index], srcEntry))) { + return false; + } + + return true; + } + + return false; + } + + static canAssignClassType(destType: ClassType, srcType: ClassType): boolean { + if (destType.isProtocol()) { + const destClassFields = destType.getClassFields(); + + let missingNames: string[] = []; + let wrongTypes: string[] = []; + + destClassFields.forEach((symbol, name) => { + const classMemberInfo = TypeUtils.lookUpClassMember(srcType, name, false); + if (!classMemberInfo) { + missingNames.push(name); + } else { + const srcMemberType = TypeUtils.getEffectiveTypeOfMember(classMemberInfo); + if (symbol.declarations && symbol.declarations[0].declaredType) { + let destMemberType = symbol.declarations[0].declaredType; + if (!TypeUtils.canAssignType(srcMemberType, destMemberType)) { + wrongTypes.push(name); + } + } + } + }); + + if (missingNames.length > 0 || wrongTypes.length > 0) { + return false; + } + + return true; + } + + if (srcType.isDerivedFrom(destType)) { + return true; + } + + if (srcType.isBuiltIn()) { + if (srcType.getClassName() === 'int') { + if (this.lookUpClassMember(destType, '__int__')) { + return true; + } + } + + if (srcType.getClassName() === 'float') { + if (this.lookUpClassMember(destType, '__float__')) { + return true; + } + } + } + + return false; + } + + // Looks up a member in a class using the multiple-inheritance rules + // defined by Python. For more detials, see this note on method resolution + // order: https://www.python.org/download/releases/2.3/mro/. + static lookUpClassMember(classType: Type, memberName: string, includeInstanceFields = true): ClassMember | undefined { + if (classType instanceof ClassType) { + // TODO - for now, use naive depth-first search. + + // Look in the instance fields first if requested. + if (includeInstanceFields) { + const instanceFields = classType.getInstanceFields(); + const instanceFieldEntry = instanceFields.get(memberName); + if (instanceFieldEntry) { + let symbol = instanceFieldEntry; + + return { + symbol, + isInstanceMember: true, + class: classType + }; + } + } + + // Next look in the class fields. + const classFields = classType.getClassFields(); + const classFieldEntry = classFields.get(memberName); + if (classFieldEntry) { + let symbol = classFieldEntry; + + return { + symbol, + isInstanceMember: false, + class: classType + }; + } + + for (let baseClass of classType.getBaseClasses()) { + let methodType = this.lookUpClassMember(baseClass.type, memberName); + if (methodType) { + return methodType; + } + } + } else if (classType.isAny()) { + return { + isInstanceMember: false + }; + } + + return undefined; + } + + static getEffectiveTypeOfMember(member: ClassMember): Type { + if (!member.symbol) { + return UnknownType.create(); + } + + if (member.symbol.declarations) { + if (member.symbol.declarations[0].declaredType) { + return member.symbol.declarations[0].declaredType; + } + } + + if (member.symbol.inferredType) { + // TODO - for now, always simplify the type. + if (member.symbol.inferredType instanceof UnionType) { + return member.symbol.inferredType.removeOptional(); + } + return member.symbol.inferredType.getType(); + } + + return UnboundType.create(); + } + + static lookUpObjectMember(objectType: Type, memberName: string): ClassMember | undefined { + if (objectType instanceof ObjectType) { + return this.lookUpClassMember(objectType.getClassType(), memberName); + } + + return undefined; + } + + static addDefaultFunctionParameters(functionType: FunctionType) { + functionType.addParameter({ + category: ParameterCategory.VarArgList, + name: 'args', + type: UnknownType.create() + }); + functionType.addParameter({ + category: ParameterCategory.VarArgDictionary, + name: 'kwargs', + type: UnknownType.create() + }); + } + + static getMetaclass(type: ClassType): ClassType | UnknownType | undefined { + for (let base of type.getBaseClasses()) { + if (base.isMetaclass) { + if (base.type instanceof ClassType) { + return base.type; + } else { + return UnknownType.create(); + } + } + + if (base.type instanceof ClassType) { + // TODO - add protection for infinite recursion + let metaclass = this.getMetaclass(base.type); + if (metaclass) { + return metaclass; + } + } + } + + return undefined; + } +} diff --git a/server/src/analyzer/types.ts b/server/src/analyzer/types.ts new file mode 100644 index 000000000..02c7e4f0f --- /dev/null +++ b/server/src/analyzer/types.ts @@ -0,0 +1,780 @@ +/* +* types.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Representation of types used during type analysis within Python. +*/ + +import * as assert from 'assert'; +import { ParameterCategory, ParseNode } from '../parser/parseNodes'; +import { InferredType, TypeSourceId } from './inferredType'; +import { SymbolTable } from './symbol'; + +export enum TypeCategory { + // Name is not bound to a value of any type. + Unbound, + + // Type exists but is not currenlty known by the + // type analyzer (e.g. there is no available typings file). + // Unknown types are treated the same as "Any" at analysis time. + Unknown, + + // Type can be anything. + Any, + + // Special "None" type defined in Python. + None, + + // Special "Ellipsis" type defined in Python. + Ellipsis, + + // Immutable sequence of typed values. + Tuple, + + // Callable type with typed intput parameters and return parameter. + Function, + + // Functions defined with @overload decorator in stub files that + // have multiple function declarations for a common implementation. + OverloadedFunction, + + // Value that has associated getter/setter/deleter function. + Property, + + // Class definition, including associated instance methods, + // class methods, static methods, properties, and variables. + Class, + + // Class instance. + Object, + + // Module instance. + Module, + + // Composite type (e.g. Number OR String OR None). + Union, + + // Type variable (defined with TypeVar) + TypeVar +} + +const AsStringMaxRecursionCount = 4; + +export abstract class Type { + abstract category: TypeCategory; + + protected constructor() { + } + + isUnbound(): boolean { + return false; + } + + isAny(): boolean { + return false; + } + + isPossiblyUnbound(): boolean { + return false; + } + + isSame(type2: Type): boolean { + return this.category === type2.category; + } + + asString(): string { + return this.asStringInternal(AsStringMaxRecursionCount); + } + + abstract asStringInternal(recursionCount: number): string; +} + +export class UnboundType extends Type { + category = TypeCategory.Unbound; + + private static _instance = new UnboundType(); + static create() { + // Use a single instance to reduce memory allocation. + return this._instance; + } + + protected constructor() { + super(); + } + + isUnbound(): boolean { + return true; + } + + isAny(): boolean { + return false; + } + + isPossiblyUnbound(): boolean { + return true; + } + + asStringInternal(recursionCount = AsStringMaxRecursionCount): string { + return 'Unbound'; + } +} + +export class UnknownType extends Type { + category = TypeCategory.Unknown; + + private static _instance = new UnknownType(); + static create() { + // Use a single instance to reduce memory allocation. + return this._instance; + } + + isAny(): boolean { + return true; + } + + asStringInternal(recursionCount = AsStringMaxRecursionCount): string { + return 'Unknown'; + } +} + +export class ModuleType extends Type { + category = TypeCategory.Module; + private _fields: SymbolTable; + + // A partial module is one that is not fully initialized + // but contains only the symbols that have been imported + // in a multi-part import (e.g. import a.b.c). + private _isPartialModule = false; + + constructor(symbolTable: SymbolTable) { + super(); + + this._fields = symbolTable; + } + + getFields() { + return this._fields; + } + + setIsPartialModule() { + this._isPartialModule = true; + } + + isPartialModule() { + return this._isPartialModule; + } + + asStringInternal(recursionCount = AsStringMaxRecursionCount): string { + return 'Module'; + } +} + +export enum ClassTypeFlags { + None = 0x00, + + // The class has one or more decorators. + HasDecorators = 0x01, + + // Class is defined in the "builtins" or "typings" file. + BuiltInClass = 0x02, + + // CLass requires special-case handling because it + // exhibits non-standard behavior or is not defined + // formally as a class. Examples include 'Optional' + // and 'Union'. + SpecialBuiltIn = 0x04 +} + +// export class TypeReference extends Type { +// // A generic type instantiation will have one or more type +// // arguments and an associated target class type. +// private _typeArguments: Type[] = []; +// private _targetType?: ClassType; +// } + +export interface BaseClass { + isMetaclass: boolean; + type: Type; +} + +export class ClassType extends Type { + category = TypeCategory.Class; + + private _classFlags: ClassTypeFlags; + private _className: string; + private _baseClasses: BaseClass[] = []; + private _classFields = new SymbolTable(); + private _instanceFields = new SymbolTable(); + + // A generic class will have one or more type variables. + // private _typeVariables: TypeVarType[] = []; + + constructor(name: string, flags: ClassTypeFlags) { + super(); + this._className = name; + this._classFlags = flags; + } + + isSpecialBuiltIn() { + return !!(this._classFlags & ClassTypeFlags.SpecialBuiltIn); + } + + isBuiltIn() { + return !!(this._classFlags & ClassTypeFlags.BuiltInClass); + } + + isProtocol() { + // Does the class directly 'derive' from "Protocol"? + return this._baseClasses.find(bc => { + if (bc.type instanceof ClassType) { + if (bc.type.isBuiltIn() && bc.type.getClassName() === 'Protocol') { + return true; + } + } + return false; + }) !== undefined; + } + + getClassName() { + return this._className; + } + + hasDecorators() { + return !!(this._classFlags & ClassTypeFlags.HasDecorators); + } + + getBaseClasses(): BaseClass[] { + return this._baseClasses; + } + + addBaseClass(type: Type, isMetaclass: boolean) { + this._baseClasses.push({ isMetaclass, type }); + } + + updateBaseClassType(index: number, type: Type) { + const didChange = !type.isSame(this._baseClasses[index].type); + this._baseClasses[index].type = type; + return didChange; + } + + getClassFields(): SymbolTable { + return this._classFields; + } + + setClassFields(nameMap: SymbolTable) { + this._classFields = nameMap; + } + + getInstanceFields(): SymbolTable { + return this._instanceFields; + } + + setInstanceFields(nameMap: SymbolTable) { + this._instanceFields = nameMap; + } + + isSame(type2: Type): boolean { + return super.isSame(type2) && + this._className === (type2 as ClassType)._className; + } + + asStringInternal(recursionCount = AsStringMaxRecursionCount): string { + return 'class ' + this._className; + } + + // Determines whether this is a subclass (derived class) + // of the specified class. + isDerivedFrom(type2: ClassType): boolean { + if (type2 === this) { + return true; + } + + // Handle built-in types like 'dict' and 'list', which are all + // subclasses of object even though they are not explicitly declared + // that way. + if (this.isBuiltIn() && type2._className === 'object' && type2.isBuiltIn()) { + return true; + } + + for (let baseClass of this.getBaseClasses()) { + if (baseClass.type instanceof ClassType) { + if (baseClass.type.isDerivedFrom(type2)) { + return true; + } + } else if (baseClass.type.isAny()) { + return true; + } + } + + return false; + } +} + +export class ObjectType extends Type { + category = TypeCategory.Object; + + private _classType: ClassType; + + constructor(classType: ClassType) { + super(); + + assert(classType instanceof ClassType); + this._classType = classType; + } + + getClassType() { + return this._classType; + } + + isSame(type2: Type): boolean { + return super.isSame(type2) && + this._classType.isSame((type2 as ObjectType)._classType); + } + + asStringInternal(recursionCount = AsStringMaxRecursionCount): string { + return this._classType.getClassName(); + } +} + +export interface FunctionParameter { + category: ParameterCategory; + name?: string; + hasDefault?: boolean; + type: Type; + node?: ParseNode; +} + +export enum FunctionTypeFlags { + None = 0, + InstanceMethod = 1, + ClassMethod = 2, + StaticMethod = 4, + HasCustomDecorators = 8 +} + +export class FunctionType extends Type { + category = TypeCategory.Function; + + private _parameters: FunctionParameter[] = []; + private _declaredReturnType?: Type; + private _inferredReturnType = new InferredType(); + private _flags: FunctionTypeFlags; + + constructor(flags: FunctionTypeFlags) { + super(); + this._flags = flags; + } + + isInstanceMethod(): boolean { + return (this._flags & FunctionTypeFlags.InstanceMethod) !== 0; + } + + isClassMethod(): boolean { + return (this._flags & FunctionTypeFlags.ClassMethod) !== 0; + } + + getParameters() { + return this._parameters; + } + + setParameters(params: FunctionParameter[]) { + this._parameters = params; + } + + addParameter(param: FunctionParameter) { + this._parameters.push(param); + } + + getDeclaredReturnType() { + return this._declaredReturnType; + } + + setDeclaredReturnType(type?: Type): boolean { + const typeChanged = !this._declaredReturnType || !type || + !this._declaredReturnType.isSame(type); + this._declaredReturnType = type; + + return typeChanged; + } + + getInferredReturnType() { + return this._inferredReturnType; + } + + getEffectiveReturnType() { + if (this._declaredReturnType) { + return this._declaredReturnType; + } + + return this._inferredReturnType.getType(); + } + + hasCustomDecorators(): boolean { + return (this._flags & FunctionTypeFlags.HasCustomDecorators) !== undefined; + } + + clearHasCustomDecoratorsFlag() { + this._flags &= ~FunctionTypeFlags.HasCustomDecorators; + } + + asStringInternal(recursionCount = AsStringMaxRecursionCount): string { + let paramTypeString = this._parameters.map(param => { + let paramString = ''; + if (param.category === ParameterCategory.VarArgList) { + paramString += '*'; + } else if (param.category === ParameterCategory.VarArgDictionary) { + paramString += '**'; + } + + if (param.name) { + paramString += param.name; + } + + if (param.category === ParameterCategory.Simple) { + const paramTypeString = recursionCount > 0 ? + param.type.asStringInternal(recursionCount - 1) : ''; + paramString += ': ' + paramTypeString; + } + return paramString; + }).join(', '); + + let returnTypeString = 'Any'; + const returnType = this.getEffectiveReturnType(); + returnTypeString = recursionCount > 0 ? + returnType.asStringInternal(recursionCount - 1) : ''; + + return `(${ paramTypeString }) -> ${ returnTypeString }`; + } +} + +export interface OverloadedFunctionEntry { + type: FunctionType; + typeSourceId: TypeSourceId; +} + +export class OverloadedFunctionType extends Type { + category = TypeCategory.OverloadedFunction; + + private _overloads: OverloadedFunctionEntry[] = []; + + constructor() { + super(); + } + + getOverloads() { + return this._overloads; + } + + addOverload(typeSourceId: TypeSourceId, type: FunctionType) { + // Was this entry already added? If so, replace the type. + const index = this._overloads.findIndex(entry => entry.typeSourceId === typeSourceId); + if (index >= 0) { + this._overloads[index].type = type; + } else { + this._overloads.push({ typeSourceId, type}); + } + } + + asStringInternal(recursionCount = AsStringMaxRecursionCount): string { + const overloads = this._overloads.map(overload => + overload.type.asStringInternal(recursionCount)); + return `Overload[${ overloads.join(', ') }]`; + } +} + +export class PropertyType extends Type { + category = TypeCategory.Property; + + private _getter: FunctionType; + private _setter?: FunctionType; + private _deleter?: FunctionType; + + constructor(getter: FunctionType) { + super(); + this._getter = getter; + } + + hasSetter() { + return this._setter !== undefined; + } + + setSetter(setter: FunctionType) { + this._setter = setter; + } + + hasDeleter() { + return this._deleter !== undefined; + } + + setDeleter(deleter: FunctionType) { + this._deleter = deleter; + } + + getEffectiveReturnType() { + return this._getter.getEffectiveReturnType(); + } + + asStringInternal(recursionCount = AsStringMaxRecursionCount): string { + const returnType = this._getter.getEffectiveReturnType(); + let returnTypeString = recursionCount > 0 ? + returnType.asStringInternal(recursionCount - 1) : ''; + return returnTypeString; + } +} + +export class EllipsisType extends Type { + category = TypeCategory.Ellipsis; + + private static _instance = new EllipsisType(); + static create() { + // Use a single instance to reduce memory allocation. + return this._instance; + } + + isAny(): boolean { + return true; + } + + asStringInternal(recursionCount = AsStringMaxRecursionCount): string { + return '...'; + } +} + +export class NoneType extends Type { + category = TypeCategory.None; + + private static _instance = new NoneType(); + static create() { + // Use a single instance to reduce memory allocation. + return this._instance; + } + + asStringInternal(recursionCount = AsStringMaxRecursionCount): string { + return 'None'; + } +} + +export class AnyType extends Type { + category = TypeCategory.Any; + + private static _instance = new AnyType(); + static create() { + // Use a single instance to reduce memory allocation. + return this._instance; + } + + isAny(): boolean { + return true; + } + + asStringInternal(): string { + return 'Any'; + } +} + +export class UnionType extends Type { + category = TypeCategory.Union; + + private _types: Type[] = []; + + constructor() { + super(); + } + + getTypes() { + return this._types; + } + + isAny(): boolean { + return this._types.find(t => !t.isAny()) === undefined; + } + + isPossiblyUnbound(): boolean { + return this._types.find(t => t.isPossiblyUnbound()) !== undefined; + } + + addType(type1: Type) { + assert(type1.category !== TypeCategory.Union); + + this._types.push(type1); + } + + addTypes(types: Type[]) { + // Add any types that are unique to the union. + for (let newType of types) { + assert(newType.category !== TypeCategory.Union); + if (!this._types.find(t => t.isSame(newType))) { + this._types.push(newType); + } + } + } + + // Eliminates any "None" elements from the union. + removeOptional(): Type { + let simplifiedTypes = this._types.filter(t => t.category !== TypeCategory.None); + if (simplifiedTypes.length === 1) { + return simplifiedTypes[0]; + } + let newUnion = new UnionType(); + newUnion.addTypes(simplifiedTypes); + return newUnion; + } + + // Eliminates any "Unbound" elements from the union. + removeUnbound(): Type { + let simplifiedTypes = this._types.filter(t => t.category !== TypeCategory.Unbound); + if (simplifiedTypes.length === 1) { + return simplifiedTypes[0]; + } + let newUnion = new UnionType(); + newUnion.addTypes(simplifiedTypes); + return newUnion; + } + + isSame(type2: Type): boolean { + if (!(type2 instanceof UnionType)) { + return false; + } + + if (this._types.length !== type2._types.length) { + return false; + } + + // The types do not have a particular order, so we need to + // do the comparison in an order-indepdendent manner. + return this._types.find(t => !type2.containsType(t)) === undefined; + } + + containsType(type: Type): boolean { + return this._types.find(t => t.isSame(type)) !== undefined; + } + + asStringInternal(recursionCount = AsStringMaxRecursionCount): string { + if (this._types.find(t => t.category === TypeCategory.None) !== undefined) { + const optionalType = recursionCount > 0 ? + this.removeOptional().asStringInternal(recursionCount - 1) : ''; + return 'Optional[' + optionalType + ']'; + } + + const unionTypeString = recursionCount > 0 ? + this._types.map(t => t.asStringInternal(recursionCount - 1)).join(', ') : ''; + + return 'Union[' + unionTypeString + ']'; + } +} + +export class TupleType extends Type { + category = TypeCategory.Tuple; + + private _tupleBaseClass: ClassType; + private _entryTypes: Type[] = []; + + constructor(baseClass: ClassType) { + super(); + this._tupleBaseClass = baseClass; + } + + getBaseClass() { + return this._tupleBaseClass; + } + + getEntryTypes() { + return this._entryTypes; + } + + addEntryType(type: Type) { + this._entryTypes.push(type); + } + + isSame(type2: Type): boolean { + if (!super.isSame(type2)) { + return false; + } + + const type2Tuple = type2 as TupleType; + if (this._entryTypes.length !== type2Tuple._entryTypes.length) { + return false; + } + + return this._entryTypes.find((t, index) => + !type2Tuple._entryTypes[index].isSame(t)) === undefined; + } + + asStringInternal(recursionCount = AsStringMaxRecursionCount): string { + let tupleTypeString = recursionCount > 0 ? + this._entryTypes.map(t => t.asStringInternal(recursionCount - 1)).join(', ') : ''; + return 'Tuple[' + tupleTypeString + ']'; + } +} + +export class TypeVarType extends Type { + category = TypeCategory.TypeVar; + + private _name: string; + private _constraints: Type[] = []; + private _boundType?: Type; + private _isCovariant = false; + private _isContravariant = false; + + constructor(name: string) { + super(); + this._name = name; + } + + getConstraints() { + return this._constraints; + } + + addConstraint(type: Type) { + this._constraints.push(type); + } + + getBoundType() { + return this._boundType; + } + + setBoundType(type?: Type) { + this._boundType = type; + } + + isCovariant() { + return this._isCovariant; + } + + setIsCovariant() { + this._isCovariant = true; + } + + isContravariant() { + return this._isContravariant; + } + + setIsContravariant() { + this._isContravariant = true; + } + + isSame(type2: Type): boolean { + if (!super.isSame(type2) || this._constraints.length !== (type2 as TypeVarType)._constraints.length) { + return false; + } + + for (let i = 0; i < this._constraints.length; i++) { + if (!this._constraints[i].isSame((type2 as TypeVarType)._constraints[i])) { + return false; + } + } + + return true; + } + + asStringInternal(recursionCount = AsStringMaxRecursionCount): string { + let params: string[] = [this._name]; + if (recursionCount > 0) { + for (let constraint of this._constraints) { + params.push(constraint.asStringInternal(recursionCount - 1)); + } + } + return 'TypeVar[' + params.join(', ') + ']'; + } +} diff --git a/server/src/common/cancelToken.ts b/server/src/common/cancelToken.ts new file mode 100644 index 000000000..7fa5066d1 --- /dev/null +++ b/server/src/common/cancelToken.ts @@ -0,0 +1,29 @@ +/* +* cancelToken.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* A simple class that allows a caller to cancel an async operation. +* The async operation needs to cooperatively check for cancelation. +*/ + +export class CancelError extends Error { +} + +export class CancelToken { + private _isCanceled = false; + + cancel(): void { + this._isCanceled = true; + } + + isCanceled(): boolean { + return this._isCanceled; + } + + throwIfCanceled(): void { + if (this._isCanceled) { + throw new CancelError(); + } + } +} diff --git a/server/src/common/commandLineOptions.ts b/server/src/common/commandLineOptions.ts new file mode 100644 index 000000000..fe93fd2d3 --- /dev/null +++ b/server/src/common/commandLineOptions.ts @@ -0,0 +1,40 @@ +/* +* commandLineOptions.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Class that holds the command-line options (those that can be +* passed into the main entry point of the command-line version +* of the analyzer). +*/ + +// Some options can be specified by command line. +export class CommandLineOptions { + constructor(executionRoot: string) { + this.executionRoot = executionRoot; + } + + // A list of file specs to include in the anlaysis. Can contain + // directories, in which case all "*.py" files within those directories + // are included. + fileSpecs: string[] = []; + + // Watch for changes? + watch?: boolean; + + // Path of config file. This option cannot be combined with + // file specs. + configFilePath?: string; + + // Virtual environments directory. + venvPath?: string; + + // Path of python environment. + pythonPath?: string; + + // Path of typeshed stubs. + typeshedPath?: string; + + // Absolute execution root (current working directory). + executionRoot: string; +} diff --git a/server/src/common/configOptions.ts b/server/src/common/configOptions.ts new file mode 100644 index 000000000..7de52f6de --- /dev/null +++ b/server/src/common/configOptions.ts @@ -0,0 +1,316 @@ +/* +* configOptions.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Class that holds the configuration options for the analyzer. +*/ + +import { ConsoleInterface } from './console'; +import { combinePaths, ensureTrailingDirectorySeparator, getDirectoryPath, + normalizePath } from './pathUtils'; +import { LatestStablePythonVersion, PythonVersion, versionFromString } from './pythonVersion'; + +export class ExecutionEnvironment { + // Default to "." which indicates every file in the project. + constructor(root = '.', defaultPythonVersion?: PythonVersion, defaultPythonPlatform?: string) { + this.root = root; + this.pythonVersion = defaultPythonVersion || LatestStablePythonVersion; + this.pythonPlatform = defaultPythonPlatform; + } + + // Root directory for execution - absolute or relative to the + // project root. + root: string; + + // Always default to the latest stable version of the language. + pythonVersion: PythonVersion; + + // Default to no platform. + pythonPlatform?: string; + + // Default to no extra paths. + extraPaths: string[] = []; + + // Name of virtual environment to use. + venv?: string; +} + +export type DiagnosticLevel = 'none' | 'warn' | 'error'; + +// Internal configuration options. These are derived from a combination +// of the command line and from a JSON-based config file. +export class ConfigOptions { + constructor(projectRoot: string) { + this.projectRoot = projectRoot; + } + + // Absolute directory of project. All relative paths in the config + // are based on this path. + projectRoot: string; + + // Path to use for typeshed definitions. + typeshedPath?: string; + + // Path to custom typings (stub) modules. + typingsPath?: string; + + // A list of file specs to include in the analysis. Can contain + // directories, in which case all "*.py" files within those directories + // are included. + include: string[] = []; + + // A list of file specs to exclude from the analysis (overriding include + // if necessary). Can contain directories, in which case all "*.py" files + // within those directories are included. + exclude: string[] = []; + + // Report diagnostics in typeshed files? + reportTypeshedErrors: DiagnosticLevel = 'none'; + + // Report missing imports? + reportMissingImports: DiagnosticLevel = 'error'; + + // Parameters that specify the execution environment for + // the files being analyzed. + executionEnvironments: ExecutionEnvironment[] = []; + + // Path to python interpreter environment -- used to resolve third-party + // modules when there is no "venv" option in the config file. + pythonPath?: string; + + // Path to a directory containing one or more virtual environment + // directories. This is used in conjunction with the "venv" name in + // the config file to identify the python environment used for resolving + // third-party modules. + venvPath?: string; + + // Default venv environment. Can be overridden by executionEnvironment. + defaultVenv?: string; + + // Default pythonVersion. Can be overridden by executionEnvironment. + defaultPythonVersion?: PythonVersion; + + // Default pythonPlatform. Can be overridden by executionEnvironment. + defaultPythonPlatform?: string; + + // Finds the best execution environment for a given file path. The + // specified file path should be absolute. + // If no matching execution environment can be found, a default + // execution environment is used. + findExecEnvironment(filePath: string): ExecutionEnvironment { + let execEnv = this.executionEnvironments.find(env => { + let envRoot = ensureTrailingDirectorySeparator( + normalizePath(combinePaths(this.projectRoot, env.root))); + return filePath.startsWith(envRoot); + }); + + if (!execEnv) { + execEnv = new ExecutionEnvironment(normalizePath(getDirectoryPath(filePath)), + this.defaultPythonVersion, this.defaultPythonPlatform); + } + + return execEnv; + } + + // Initialize the structure from a JSON object. + initializeFromJson(configObj: any, console: ConsoleInterface) { + // Read the "include" entry. + this.include = []; + if (configObj.include !== undefined) { + if (!Array.isArray(configObj.include)) { + console.log(`Config "include" entry must must contain an array.`); + } else { + let filesList = configObj.include as string[]; + filesList.forEach((fileSpec, index) => { + if (typeof fileSpec !== 'string') { + console.log(`Index ${ index } of "include" array should be a string.`); + } else { + this.include.push(fileSpec); + } + }); + } + } + + // Read the "exclude" entry. + this.exclude = []; + if (configObj.exclude !== undefined) { + if (!Array.isArray(configObj.exclude)) { + console.log(`Config "exclude" entry must contain an array.`); + } else { + let filesList = configObj.exclude as string[]; + filesList.forEach((fileSpec, index) => { + if (typeof fileSpec !== 'string') { + console.log(`Index ${ index } of "exclude" array should be a string.`); + } else { + this.exclude.push(fileSpec); + } + }); + } + } + + // Read the "reportTypeshedErrors" entry. + this.reportTypeshedErrors = this._convertDiagnosticLevel( + configObj.reportTypeshedErrors, 'reportTypeshedErrors', 'none'); + + // Read the "reportMissingImports" entry. + this.reportMissingImports = this._convertDiagnosticLevel( + configObj.reportMissingImports, 'reportMissingImports', 'none'); + + // Read the default "venv". + this.defaultVenv = undefined; + if (configObj.venv !== undefined) { + if (typeof configObj.venv !== 'string') { + console.log(`Config "venv" field must contain a string.`); + } else { + this.defaultVenv = configObj.venv; + } + } + + // Read the default "pythonVersion". + this.defaultPythonVersion = undefined; + if (configObj.pythonVersion !== undefined) { + if (typeof configObj.pythonVersion === 'string') { + let version = versionFromString(configObj.pythonVersion); + if (version) { + this.defaultPythonVersion = version; + } else { + console.log(`Config "pythonVersion" field contains unsupported version.`); + } + } else { + console.log(`Config "pythonVersion" field must contain a string.`); + } + } + + // Read the default "pythonPlatform". + this.defaultPythonPlatform = undefined; + if (configObj.pythonPlatform !== undefined) { + if (typeof configObj.pythonPlatform !== 'string') { + console.log(`Config "pythonPlatform" field must contain a string.`); + } else { + this.defaultPythonPlatform = configObj.pythonPlatform; + } + } + + // Read the "typeshedPath". + this.typeshedPath = undefined; + if (configObj.typeshedPath !== undefined) { + if (typeof configObj.typeshedPath !== 'string') { + console.log(`Config "typeshedPath" field must contain a string.`); + } else { + this.typeshedPath = configObj.typeshedPath; + } + } + + // Read the "typingsPath". + this.typingsPath = undefined; + if (configObj.typingsPath !== undefined) { + if (typeof configObj.typingsPath !== 'string') { + console.log(`Config "typingsPath" field must contain a string.`); + } else { + this.typingsPath = normalizePath(combinePaths(this.projectRoot, configObj.typingsPath)); + } + } + + // Read the "executionEnvironments" array. This should be done at the end + // after we've established default values. + this.executionEnvironments = []; + if (configObj.executionEnvironments !== undefined) { + if (!Array.isArray(configObj.executionEnvironments)) { + console.log(`Config "executionEnvironments" field must contain an array.`); + } else { + let execEnvironments = configObj.executionEnvironments as ExecutionEnvironment[]; + execEnvironments.forEach((env, index) => { + let execEnv = this._initExecutionEnvironmentFromJson(env, index, console); + if (execEnv) { + this.executionEnvironments.push(execEnv); + } + }); + } + } + } + + private _convertDiagnosticLevel(value: any, fieldName: string, + defaultValue: DiagnosticLevel): DiagnosticLevel { + if (typeof value === 'boolean') { + return value ? 'error' : 'none'; + } else if (typeof value === 'string') { + if (value === 'error' || value === 'warn' || value === 'none') { + return value; + } + } + + console.log(`Config "${ fieldName }" entry must be true, false, "error", "warn" or "none".`); + return defaultValue; + } + + private _initExecutionEnvironmentFromJson(envObj: any, index: number, + console: ConsoleInterface): ExecutionEnvironment | undefined { + try { + let newExecEnv = new ExecutionEnvironment('.', this.defaultPythonVersion, + this.defaultPythonPlatform); + + // Validate the root. + if (envObj.root && typeof envObj.root === 'string') { + newExecEnv.root = normalizePath(combinePaths(this.projectRoot, envObj.root)); + } else { + console.log(`Config executionEnvironments index ${ index }: missing root value.`); + } + + // Validate the extraPaths. + if (envObj.extraPaths) { + if (!Array.isArray(envObj.extraPaths)) { + console.log(`Config executionEnvironments index ${ index }: extraPaths field must contain an array.`); + } else { + let pathList = envObj.extraPaths as string[]; + pathList.forEach((path, pathIndex) => { + if (typeof path !== 'string') { + console.log(`Config executionEnvironments index ${ index }:` + + ` extraPaths field ${ pathIndex } must be a string.`); + } else { + newExecEnv.extraPaths.push(normalizePath(combinePaths(this.projectRoot, path))); + } + }); + } + } + + // Validate the pythonVersion. + if (envObj.pythonVersion) { + if (typeof envObj.pythonVersion === 'string') { + let version = versionFromString(envObj.pythonVersion); + if (version) { + newExecEnv.pythonVersion = version; + } else { + console.log(`Config executionEnvironments index ${ index } contains unsupported pythonVersion.`); + } + } else { + console.log(`Config executionEnvironments index ${ index } pythonVersion must be a string.`); + } + } + + // Validate the pythonPlatform. + if (envObj.pythonPlatform) { + if (typeof envObj.root === 'string') { + newExecEnv.pythonPlatform = envObj.pythonPlatform; + } else { + console.log(`Config executionEnvironments index ${ index } pythonPlatform must be a string.`); + } + } + + // Validate the venv. + if (envObj.venv) { + if (typeof envObj.venv === 'string') { + newExecEnv.venv = envObj.venv; + } else { + console.log(`Config executionEnvironments index ${ index } venv must be a string.`); + } + } + + return newExecEnv; + } catch { + console.log(`Config executionEnvironments index ${ index } is not accessible.`); + } + + return undefined; + } +} diff --git a/server/src/common/console.ts b/server/src/common/console.ts new file mode 100644 index 000000000..105e4f068 --- /dev/null +++ b/server/src/common/console.ts @@ -0,0 +1,39 @@ +/* +* console.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Provides an abstraction for console logging and error-reporting +* methods. +*/ + +export interface ConsoleInterface { + log: (message: string) => void; + error: (message: string) => void; +} + +// Avoids outputting errors to the console but counts +// the number of logs and errors, which can be useful +// for unit tests. +export class NullConsole implements ConsoleInterface { + logCount = 0; + errorCount = 0; + + log(message: string) { + this.logCount++; + } + + error(message: string) { + this.errorCount++; + } +} + +export class StandardConsole implements ConsoleInterface { + log(message: string) { + console.log(message); + } + + error(message: string) { + console.error(message); + } +} diff --git a/server/src/common/diagnostic.ts b/server/src/common/diagnostic.ts new file mode 100644 index 000000000..72d95218d --- /dev/null +++ b/server/src/common/diagnostic.ts @@ -0,0 +1,37 @@ +/* +* diagnostics.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Class that represents errors and warnings. +*/ + +export enum DiagnosticCategory { + Error, + Warning, + Informational +} + +export interface DiagnosticTextPosition { + // Both line and column are zero-based + line: number; + column: number; +} + +export interface DiagnosticTextRange { + start: DiagnosticTextPosition; + end: DiagnosticTextPosition; +} + +// Represents a range within a particular document. +export interface DocumentTextRange { + path: string; + range: DiagnosticTextRange; +} + +// Represents a single error or warning. +export class Diagnostic { + constructor(readonly category: DiagnosticCategory, readonly message: string, + readonly range?: DiagnosticTextRange) { + } +} diff --git a/server/src/common/diagnosticSink.ts b/server/src/common/diagnosticSink.ts new file mode 100644 index 000000000..fcd8352ec --- /dev/null +++ b/server/src/common/diagnosticSink.ts @@ -0,0 +1,66 @@ +/* +* diagnostics.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Class that represents errors and warnings. +*/ + +import { Diagnostic, DiagnosticCategory, DiagnosticTextRange } from './diagnostic'; +import { convertOffsetsToRange } from './positionUtils'; +import { TextRange } from './textRange'; +import { TextRangeCollection } from './textRangeCollection'; + +// Represents a collection of diagnostics within a file. +export interface FileDiagnostics { + filePath: string; + diagnostics: Diagnostic[]; +} + +// Creates and tracks a list of diagnostics. +export class DiagnosticSink { + diagnostics: Diagnostic[] = []; + + constructor(diagnostics?: Diagnostic[]) { + this.diagnostics = diagnostics || []; + } + + discard() { + this.diagnostics = []; + } + + addError(message: string, range?: DiagnosticTextRange) { + this.addDiagnostic(new Diagnostic(DiagnosticCategory.Error, message, range)); + } + + addWarning(message: string, range?: DiagnosticTextRange) { + this.addDiagnostic(new Diagnostic(DiagnosticCategory.Warning, message, range)); + } + + addDiagnostic(diag: Diagnostic) { + this.diagnostics.push(diag); + } + + addDiagnostics(diagsToAdd: Diagnostic[]) { + this.diagnostics.push(...diagsToAdd); + } +} + +// Specialized version of DiagnosticSink that works with TextRange objects +// and converts text ranges to line and column numbers. +export class TextRangeDiagnosticSink extends DiagnosticSink { + private _lines: TextRangeCollection; + + constructor(lines: TextRangeCollection, diagnostics?: Diagnostic[]) { + super(diagnostics); + this._lines = lines; + } + + addErrorWithTextRange(message: string, range: TextRange) { + this.addError(message, convertOffsetsToRange(range.start, range.end, this._lines)); + } + + addWarningWithTextRange(message: string, range: TextRange) { + this.addWarning(message, convertOffsetsToRange(range.start, range.end, this._lines)); + } +} diff --git a/server/src/common/pathUtils.ts b/server/src/common/pathUtils.ts new file mode 100644 index 000000000..fe52e77a6 --- /dev/null +++ b/server/src/common/pathUtils.ts @@ -0,0 +1,173 @@ +/* +* pathUtils.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Pathname utility functions. +*/ + +import * as fs from 'fs'; +import * as path from 'path'; +import Char from 'typescript-char'; + +export function forEachAncestorDirectory(directory: string, callback: (directory: string) => string | undefined): string | undefined { + while (true) { + const result = callback(directory); + if (result !== undefined) { + return result; + } + + const parentPath = getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + + directory = parentPath; + } +} + +export function getDirectoryPath(pathString: string): string { + return pathString.substr(0, Math.max(getRootLength(pathString), pathString.lastIndexOf(path.sep))); +} + +export function getRootLength(pathString: string): number { + if (pathString.charAt(0) === path.sep) { + if (pathString.charAt(1) !== path.sep) { return 1; } + let p1 = pathString.indexOf(path.sep, 2); + if (p1 < 0) { return 2; } + let p2 = pathString.indexOf(path.sep, p1 + 1); + if (p2 < 0) { return p1 + 1; } + return p2 + 1; + } + if (pathString.charAt(1) === ':') { + if (pathString.charAt(2) === path.sep) { return 3; } + } + return 0; +} + +export function normalizeSlashes(pathString: string): string { + const backslashRegExp = /\\/g; + return pathString.replace(backslashRegExp, path.sep); +} + +export function combinePaths(pathString: string, ...paths: (string | undefined)[]): string { + if (pathString) { + pathString = normalizeSlashes(pathString); + } + + for (let relativePath of paths) { + if (!relativePath) { + continue; + } + + relativePath = normalizeSlashes(relativePath); + + if (!pathString || getRootLength(relativePath) !== 0) { + pathString = relativePath; + } else { + pathString = ensureTrailingDirectorySeparator(pathString) + relativePath; + } + } + + return pathString; +} + +export function ensureTrailingDirectorySeparator(pathString: string): string { + if (!hasTrailingDirectorySeparator(pathString)) { + return pathString + path.sep; + } + + return pathString; +} + +export function hasTrailingDirectorySeparator(pathString: string) { + if (pathString.length === 0) { + return false; + } + + const ch = pathString.charCodeAt(pathString.length - 1); + return ch === Char.Slash || ch === Char.Backslash; +} + +export function stripTrailingDirectorySeparator(pathString: string) { + if (!hasTrailingDirectorySeparator(pathString)) { + return pathString; + } + return pathString.substr(0, pathString.length - 1); +} + +export function getFileExtension(fileName: string) { + return path.extname(fileName); +} + +export function getFileName(pathString: string) { + return path.basename(pathString); +} + +export function stripFileExtension(fileName: string) { + let ext = path.extname(fileName); + return fileName.substr(0, fileName.length - ext.length); +} + +export function normalizePath(pathString: string): string { + return path.normalize(pathString); +} + +export interface FileSystemEntries { + files: string[]; + directories: string[]; +} + +export function isDirectory(path: string): boolean { + let stat: any; + try { + stat = fs.statSync(path); + } catch (e) { + return false; + } + + return stat.isDirectory(); +} + +export function isFile(path: string): boolean { + let stat: any; + try { + stat = fs.statSync(path); + } catch (e) { + return false; + } + + return stat.isFile(); +} + +export function getFileSystemEntries(path: string): FileSystemEntries { + try { + const entries = fs.readdirSync(path || '.').sort(); + const files: string[] = []; + const directories: string[] = []; + for (const entry of entries) { + // This is necessary because on some file system node fails to exclude + // "." and "..". See https://github.com/nodejs/node/issues/4002 + if (entry === '.' || entry === '..') { + continue; + } + const name = combinePaths(path, entry); + + let stat: any; + try { + stat = fs.statSync(name); + } catch (e) { + continue; + } + + if (stat.isFile()) { + files.push(entry); + } else if (stat.isDirectory()) { + directories.push(entry); + } + } + return { files, directories }; + } catch (e) { + return { files: [], directories: [] }; + } +} diff --git a/server/src/common/positionUtils.ts b/server/src/common/positionUtils.ts new file mode 100644 index 000000000..5de684993 --- /dev/null +++ b/server/src/common/positionUtils.ts @@ -0,0 +1,57 @@ +/* +* positionUtils.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Utility routines for converting between file offsets and +* line/column positions. +*/ + +import * as assert from 'assert'; + +import { DiagnosticTextPosition, DiagnosticTextRange } from './diagnostic'; +import { TextRange } from './textRange'; +import { TextRangeCollection } from './textRangeCollection'; + +// Translates a file offset into a line/column pair. +export function convertOffsetToPosition(offset: number, lines: TextRangeCollection): DiagnosticTextPosition { + // Handle the case where the file is empty. + if (lines.end === 0) { + return { + line: 0, + column: 0 + }; + } + + // Handle the case where we're pointing to the last line of the file. + if (offset >= lines.end) { + offset = lines.end - 1; + } + + let itemIndex = lines.getItemContaining(offset); + assert(itemIndex >= 0 && itemIndex <= lines.length); + let lineRange = lines.getItemAt(itemIndex); + assert(lineRange !== undefined); + return { + line: itemIndex, + column: offset - lineRange.start + }; +} + +// Translates a start/end file offset into a pair of line/column positions. +export function convertOffsetsToRange(startOffset: number, endOffset: number, + lines: TextRangeCollection): DiagnosticTextRange { + let start = convertOffsetToPosition(startOffset, lines); + let end = convertOffsetToPosition(endOffset, lines); + return { start, end }; +} + +// Translates a position (line and col) into a file offset. +export function convertPositionToOffset(position: DiagnosticTextPosition, + lines: TextRangeCollection): number | undefined { + if (position.line >= lines.count) { + return undefined; + } + + return lines.getItemAt(position.line).start + position.column; +} diff --git a/server/src/common/promiseUtils.ts b/server/src/common/promiseUtils.ts new file mode 100644 index 000000000..59fac17ee --- /dev/null +++ b/server/src/common/promiseUtils.ts @@ -0,0 +1,48 @@ +/* +* promiseUtils.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Utility types that make promises easier to use. +*/ + +import * as assert from 'assert'; + +export class PromiseSource { + private _resolve?: (result: T) => void; + private _reject?: (error?: any) => void; + private _promise: Promise; + + constructor() { + this._promise = new Promise((resolve, reject) => { + this._resolve = resolve; + this._reject = reject; + }); + } + + getPromise() { + return this._promise; + } + + resolve(result: T) { + assert(this._resolve, 'Promise was already resolved or rejected'); + + if (this._resolve) { + let resolve = this._resolve; + this._resolve = undefined; + this._reject = undefined; + resolve(result); + } + } + + reject(error?: any) { + assert(this._reject, 'Promise was already resolved or rejected'); + + if (this._reject) { + let reject = this._reject; + this._resolve = undefined; + this._reject = undefined; + reject(error); + } + } +} diff --git a/server/src/common/pythonVersion.ts b/server/src/common/pythonVersion.ts new file mode 100644 index 000000000..b43554c48 --- /dev/null +++ b/server/src/common/pythonVersion.ts @@ -0,0 +1,69 @@ +/* +* pythonLanguageVersion.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Types and functions that relate to the Python language version +* and features within them. +*/ + +export enum PythonVersion { + // The order of this enumeration is significant. We assume + // that we can use comparison operators to check for older + // or newer versions. + V24 = 0x0204, + V25 = 0x0205, + V26 = 0x0206, + V27 = 0x0207, + V30 = 0x0300, + V31 = 0x0301, + V32 = 0x0302, + V33 = 0x0303, + V34 = 0x0304, + V35 = 0x0305, + V36 = 0x0306, + V37 = 0x0307, + V38 = 0x0308 +} + +export const LatestStablePythonVersion = PythonVersion.V37; +export const LatestPythonVersion = PythonVersion.V38; + +export function versionToString(version: PythonVersion): string { + const majorVersion = (version >> 8) & 0xFF; + const minorVersion = version & 0xFF; + return `${ majorVersion }.${ minorVersion }`; +} + +export function versionFromString(verString: string): PythonVersion | undefined { + const split = verString.split('.'); + if (split.length !== 2) { + return undefined; + } + + const majorVersion = parseInt(split[0], 10); + const minorVersion = parseInt(split[1], 10); + + if (isNaN(majorVersion) || isNaN(minorVersion)) { + return undefined; + } + + if (majorVersion > 255 || minorVersion > 255) { + return undefined; + } + + let value = majorVersion * 256 + minorVersion; + if (PythonVersion[value] === undefined) { + return undefined; + } + + return value; +} + +export function is2x(version: PythonVersion): boolean { + return (version >> 8) === 2; +} + +export function is3x(version: PythonVersion): boolean { + return (version >> 8) === 3; +} diff --git a/server/src/common/stringMap.ts b/server/src/common/stringMap.ts new file mode 100644 index 000000000..f9d27442e --- /dev/null +++ b/server/src/common/stringMap.ts @@ -0,0 +1,65 @@ +/* +* stringMap.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Provides a map between an arbitrary set of strings and some +* other type. This wraps the normal JS map and handles reserved +* keys like "prototype" and "constructor", which cannot be +* entered into a normal JS map. +*/ + +const _keyPrefix = '$'; + +export default class StringMap { + private _map: { [key: string]: T } = {}; + + // Adds a new entry, replacing an existing entry. + // Returns false if it was already present. + set(key: string, value: T): boolean { + const encodedKey = this.encodeKey(key); + const wasPresent = this._map[encodedKey] !== undefined; + + this._map[encodedKey] = value; + return !wasPresent; + } + + // Adds a new entry if the key isn't already defined. + // Returns false if it was already present. + setIfUnique(key: string, value: T): boolean { + const encodedKey = this.encodeKey(key); + if (this._map[encodedKey] !== undefined) { + return false; + } + + this._map[encodedKey] = value; + return true; + } + + get(key: string): T | undefined { + return this._map[this.encodeKey(key)]; + } + + delete(key: string) { + delete this._map[this.encodeKey(key)]; + } + + encodeKey(key: string): string { + // Prepend a $ to avoid reserved keys like "constructor". + return _keyPrefix + key; + } + + decodeKey(key: string): string { + return key.substr(_keyPrefix.length); + } + + getKeys(): string[] { + return Object.keys(this._map).map(k => this.decodeKey(k)); + } + + forEach(callback: (item: T, key: string) => void) { + Object.keys(this._map).forEach(key => { + callback(this._map[key], this.decodeKey(key)); + }); + } +} diff --git a/server/src/common/textRange.ts b/server/src/common/textRange.ts new file mode 100644 index 000000000..768c672e4 --- /dev/null +++ b/server/src/common/textRange.ts @@ -0,0 +1,50 @@ +/* +* textRange.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Specifies the range of text within a larger string. +*/ + +export class TextRange { + start: number; + length: number; + + constructor(start: number, length: number) { + if (start < 0) { + throw new Error('start must be non-negative'); + } + if (length < 0) { + throw new Error('length must be non-negative'); + } + this.start = start; + this.length = length; + } + + get end(): number { + return this.start + this.length; + } + + contains(position: number): boolean { + return position >= this.start && position < this.end; + } + + extend(range: TextRange | TextRange[] | undefined) { + if (range) { + if (Array.isArray(range)) { + range.forEach(r => { + this.extend(r); + }); + } else { + if (range.start < this.start) { + this.length += this.start - range.start; + this.start = range.start; + } + + if (range.end > this.end) { + this.length += range.end - this.end; + } + } + } + } +} diff --git a/server/src/common/textRangeCollection.ts b/server/src/common/textRangeCollection.ts new file mode 100644 index 000000000..36dcc6450 --- /dev/null +++ b/server/src/common/textRangeCollection.ts @@ -0,0 +1,113 @@ +/* +* textRangeCollection.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Based on code from vscode-python repository: +* https://github.com/Microsoft/vscode-python +* +* Class that maintains an ordered list of text ranges and allows +* for indexing and fast lookups within this list. +*/ + +import { TextRange } from './textRange'; + +export class TextRangeCollection { + private items: T[]; + + constructor(items: T[]) { + this.items = items; + } + + get start(): number { + return this.items.length > 0 ? this.items[0].start : 0; + } + + get end(): number { + return this.items.length > 0 ? this.items[this.items.length - 1].end : 0; + } + + get length(): number { + return this.end - this.start; + } + + get count(): number { + return this.items.length; + } + + contains(position: number) { + return position >= this.start && position < this.end; + } + + getItemAt(index: number): T { + if (index < 0 || index >= this.items.length) { + throw new Error('index is out of range'); + } + return this.items[index]; + } + + getItemAtPosition(position: number): number { + if (this.count === 0) { + return -1; + } + if (position < this.start) { + return -1; + } + if (position >= this.end) { + return -1; + } + + let min = 0; + let max = this.count - 1; + + while (min <= max) { + const mid = Math.floor(min + (max - min) / 2); + const item = this.items[mid]; + + if (item.start === position) { + return mid; + } + + if (position < item.start) { + max = mid - 1; + } else { + min = mid + 1; + } + } + return -1; + } + + getItemContaining(position: number): number { + if (this.count === 0) { + return -1; + } + if (position < this.start) { + return -1; + } + if (position > this.end) { + return -1; + } + + let min = 0; + let max = this.count - 1; + + while (min <= max) { + const mid = Math.floor(min + (max - min) / 2); + const item = this.items[mid]; + + if (item.contains(position)) { + return mid; + } + if (mid < this.count - 1 && item.end <= position && position < this.items[mid + 1].start) { + return -1; + } + + if (position < item.start) { + max = mid - 1; + } else { + min = mid + 1; + } + } + return -1; + } +} diff --git a/server/src/common/timing.ts b/server/src/common/timing.ts new file mode 100644 index 000000000..e871279eb --- /dev/null +++ b/server/src/common/timing.ts @@ -0,0 +1,67 @@ +/* +* timing.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* A simple duration class that can be used to record and report +* durations at the millisecond level of resolution. +*/ + +import { ConsoleInterface } from './console'; + +export class Duration { + private _startTime: number; + + constructor() { + this._startTime = Date.now(); + } + + restart() { + this._startTime = Date.now(); + } + + getDurationInMilliseconds() { + let curTime = Date.now(); + return curTime - this._startTime; + } + + getDurationInSeconds() { + return this.getDurationInMilliseconds() / 1000; + } +} + +export class TimingStat { + totalTime = 0; + + timeOperation(callback: () => void) { + let duration = new Duration(); + callback(); + this.totalTime += duration.getDurationInMilliseconds(); + } + + printTime(): string { + return (this.totalTime / 1000).toString() + 'sec'; + } +} + +export class TimingStats { + findFilesTime = new TimingStat(); + readFileTime = new TimingStat(); + tokenizeFileTime = new TimingStat(); + parseFileTime = new TimingStat(); + postParseWalkerTime = new TimingStat(); + semanticAnalyzerTime = new TimingStat(); + typeAnalyzerTime = new TimingStat(); + + print(console: ConsoleInterface) { + console.log('Find Source Files: ' + this.findFilesTime.printTime()); + console.log('Read Source Files: ' + this.readFileTime.printTime()); + console.log('Tokenize: ' + this.tokenizeFileTime.printTime()); + console.log('Parse: ' + this.parseFileTime.printTime()); + console.log('Post-parse Walker: ' + this.postParseWalkerTime.printTime()); + console.log('Semantic Analyzer: ' + this.semanticAnalyzerTime.printTime()); + console.log('Type Analyzer: ' + this.typeAnalyzerTime.printTime()); + } +} + +export let timingStats = new TimingStats(); diff --git a/server/src/parser/characterStream.ts b/server/src/parser/characterStream.ts new file mode 100644 index 000000000..19e0af104 --- /dev/null +++ b/server/src/parser/characterStream.ts @@ -0,0 +1,134 @@ +/* +* characterStream.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Based on code from vscode-python repository: +* https://github.com/Microsoft/vscode-python +* +* Class that represents a stream of characters. +*/ + +import Char from 'typescript-char'; +import { isLineBreak, isWhiteSpace } from './characters'; + +export class CharacterStream { + private _text: string; + private _position: number; + private _currentChar: number; + private _isEndOfStream: boolean; + + constructor(text: string) { + this._text = text; + this._position = 0; + this._currentChar = text.length > 0 ? text.charCodeAt(0) : 0; + this._isEndOfStream = text.length === 0; + } + + getText(): string { + return this._text; + } + + get position(): number { + return this._position; + } + + set position(value: number) { + this._position = value; + this._checkBounds(); + } + + get currentChar(): number { + return this._currentChar; + } + + get nextChar(): number { + return this.position + 1 < this._text.length ? this._text.charCodeAt(this.position + 1) : 0; + } + + get prevChar(): number { + return this.position - 1 >= 0 ? this._text.charCodeAt(this.position - 1) : 0; + } + + isEndOfStream(): boolean { + return this._isEndOfStream; + } + + lookAhead(offset: number): number { + const pos = this._position + offset; + return pos < 0 || pos >= this._text.length ? 0 : this._text.charCodeAt(pos); + } + + advance(offset: number) { + this.position += offset; + } + + moveNext(): boolean { + if (this._position < this._text.length - 1) { + // Most common case, no need to check bounds extensively + this._position += 1; + this._currentChar = this._text.charCodeAt(this._position); + return true; + } + this.advance(1); + return !this.isEndOfStream(); + } + + isAtWhiteSpace(): boolean { + return isWhiteSpace(this.currentChar); + } + + isAtLineBreak(): boolean { + return isLineBreak(this.currentChar); + } + + skipLineBreak(): void { + if (this._currentChar === Char.CarriageReturn) { + this.moveNext(); + if (this.currentChar === Char.LineFeed) { + this.moveNext(); + } + } else if (this._currentChar === Char.LineFeed) { + this.moveNext(); + } + } + + skipWhitespace(): void { + while (!this.isEndOfStream() && this.isAtWhiteSpace()) { + this.moveNext(); + } + } + + skipToEol(): void { + while (!this.isEndOfStream() && !this.isAtLineBreak()) { + this.moveNext(); + } + } + + skipToWhitespace(): void { + while (!this.isEndOfStream() && !this.isAtWhiteSpace()) { + this.moveNext(); + } + } + + charCodeAt(index: number): number { + return this._text.charCodeAt(index); + } + + get length(): number { + return this._text.length; + } + + private _checkBounds(): void { + if (this._position < 0) { + this._position = 0; + } + + this._isEndOfStream = this._position >= this._text.length; + if (this._isEndOfStream) { + this._position = this._text.length; + } + + this._currentChar = this._isEndOfStream ? 0 : this._text.charCodeAt(this._position); + } +} diff --git a/server/src/parser/characters.ts b/server/src/parser/characters.ts new file mode 100644 index 000000000..b3c84e7ac --- /dev/null +++ b/server/src/parser/characters.ts @@ -0,0 +1,147 @@ +/* +* characters.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Based on code from vscode-python repository: +* https://github.com/Microsoft/vscode-python +* +* Utility routines used by tokenizer. +*/ + +import Char from 'typescript-char'; + +import * as unicode from './unicode'; + +enum CharCategory { + // Character cannot appear in identifier + NotIdentifierChar = 0, + + // Character can appear at beginning or within identifier + StartIdentifierChar = 1, + + // Character can appear only within identifier, not at beginning + IdentifierChar = 2 +} + +// Table of first 256 character codes (the most common cases). +const _identifierCharFastTableSize = 256; +let _identifierCharFastTable: CharCategory[] = new Array(_identifierCharFastTableSize); + +// Map of remaining characters that can appear within identifier. +let _identifierCharMap: { [code: number]: CharCategory } = {}; + +// We do lazy initialization of this map because it's rarely used. +let _identifierCharMapInitialized = false; + +export function isIdentifierStartChar(ch: number) { + if (ch < _identifierCharFastTableSize) { + return _identifierCharFastTable[ch] === CharCategory.StartIdentifierChar; + } + + // Lazy initialize the char map. We'll rarely get here. + if (!_identifierCharMapInitialized) { + _buildIdentifierLookupTable(false); + _identifierCharMapInitialized = true; + } + + return _identifierCharMap[ch] === CharCategory.StartIdentifierChar; +} + +export function isIdentifierChar(ch: number) { + if (ch < _identifierCharFastTableSize) { + return _identifierCharFastTable[ch] === CharCategory.StartIdentifierChar || + _identifierCharFastTable[ch] === CharCategory.IdentifierChar; + } + + return _identifierCharMap[ch] === CharCategory.StartIdentifierChar || + _identifierCharMap[ch] === CharCategory.IdentifierChar; +} + +export function isWhiteSpace(ch: number): boolean { + return ch === Char.Space || ch === Char.Tab || ch === Char.FormFeed; +} + +export function isLineBreak(ch: number): boolean { + return ch === Char.CarriageReturn || ch === Char.LineFeed; +} + +export function isNumber(ch: number): boolean { + return ch >= Char._0 && ch <= Char._9 || ch === Char.Underscore; +} + +export function isDecimal(ch: number): boolean { + return ch >= Char._0 && ch <= Char._9 || ch === Char.Underscore; +} + +export function isHex(ch: number): boolean { + return isDecimal(ch) || (ch >= Char.a && ch <= Char.f) || (ch >= Char.A && ch <= Char.F) || ch === Char.Underscore; +} + +export function isOctal(ch: number): boolean { + return ch >= Char._0 && ch <= Char._7 || ch === Char.Underscore; +} + +export function isBinary(ch: number): boolean { + return ch === Char._0 || ch === Char._1 || ch === Char.Underscore; +} + +// Underscore is explicitly allowed to start an identifier. +// Characters with the Other_ID_Start property. +const _specialStartIdentifierChars: unicode.UnicodeRangeTable = [Char.Underscore, + 0x1885, 0x1886, 0x2118, 0x212E, 0x309B, 0x309C]; + +const _startIdentifierCharRanges = [_specialStartIdentifierChars, unicode.unicodeLu, + unicode.unicodeLl, unicode.unicodeLt, unicode.unicodeLo, unicode.unicodeLm, unicode.unicodeNl]; + +// Characters with the Other_ID_Start property. +const _specialIdentifierChars: unicode.UnicodeRangeTable = [0x00B7, 0x0387, 0x1369, + 0x136A, 0x136B, 0x136C, 0x136D, 0x136E, 0x136F, 0x1370, 0x1371, 0x19DA]; + +const _identifierCharRanges = [_specialIdentifierChars, unicode.unicodeMn, unicode.unicodeMc, + unicode.unicodeNd, unicode.unicodePc]; + +function _buildIdentifierLookupTableFromUnicodeRangeTable(table: unicode.UnicodeRangeTable, + category: CharCategory, fastTableOnly: boolean) { + for (let entryIndex = 0; entryIndex < table.length; entryIndex++) { + let entry = table[entryIndex]; + let rangeStart: number; + let rangeEnd: number; + + if (Array.isArray(entry)) { + rangeStart = entry[0]; + rangeEnd = entry[1]; + } else { + rangeStart = rangeEnd = entry; + } + + for (let i = rangeStart; i <= rangeEnd; i++) { + if (i < _identifierCharFastTableSize) { + _identifierCharFastTable[i] = category; + } else { + _identifierCharMap[i] = category; + } + } + + if (fastTableOnly && rangeStart >= _identifierCharFastTableSize) { + break; + } + } +} + +// Build a lookup table for to speed up tokenization of identifiers. +function _buildIdentifierLookupTable(fastTableOnly: boolean) { + _identifierCharFastTable.fill(CharCategory.NotIdentifierChar); + + _identifierCharRanges.forEach(table => { + _buildIdentifierLookupTableFromUnicodeRangeTable( + table, CharCategory.IdentifierChar, fastTableOnly); + }); + + _startIdentifierCharRanges.forEach(table => { + _buildIdentifierLookupTableFromUnicodeRangeTable( + table, CharCategory.StartIdentifierChar, fastTableOnly); + }); +} + +_buildIdentifierLookupTable(true); diff --git a/server/src/parser/nameBindings.ts b/server/src/parser/nameBindings.ts new file mode 100644 index 000000000..102067fce --- /dev/null +++ b/server/src/parser/nameBindings.ts @@ -0,0 +1,111 @@ +/* +* nameBindings.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Tracks the names that are declared within a Python scope (module, class, +* function or lambda). Note that only the the names are tracked here, not +* the values to which they are bound at runtime. By default, names declared +* within a scope (via a parameter, assignment, class, or function) have local +* binding. This default can be overriden through the use of a "global" +* or "nonlocal" statement, as long as that statement comes before an implied +* local binding within the block. It is an error condition for a name to have +* inconsistent bindings, and this module is used to detect that condition. +*/ + +import StringMap from '../common/stringMap'; + +export enum NameBindingType { + // Class or function + Local, + + // With "nonlocal" keyword + Nonlocal, + + // Module level or with "global" keyword + Global, + + // Marked both global and nonlocal + Inconsistent +} + +export class NameBindings { + private _bindingType: NameBindingType; + private _names = new StringMap(); + private _hasWildcardImport = false; + + constructor(bindingType: NameBindingType) { + this._bindingType = bindingType; + } + + getBindingType() { + return this._bindingType; + } + + lookUpName(name: string): NameBindingType | undefined { + const entry = this._names.get(name); + if (entry) { + return entry; + } + + if (this._hasWildcardImport) { + return NameBindingType.Local; + } + + return undefined; + } + + getGlobalNames(): string[] { + return this._getNamesOfBindingType(NameBindingType.Global); + } + + getLocalNames(): string[] { + return this._getNamesOfBindingType(NameBindingType.Local); + } + + // Adds a name and associated binding type. Returns false if the + // name already exists but is a different type than it was previously. + addName(name: string, bindingType: NameBindingType): boolean { + const entry = this._names.get(name); + if (entry === bindingType) { + return true; + } + + if (entry === undefined) { + this._names.set(name, bindingType); + return true; + } + + // If the name was already marked as inconsistent, return true + // so we don't report errors multiple times. + if (entry === NameBindingType.Inconsistent) { + return true; + } + + // Mark the type as inconsistent so we don't use it in subsequent + // analysis and we can generate a diagnostic. + this._names.set(name, NameBindingType.Inconsistent); + return false; + } + + // Adds a wildcard (from a "from X import *" statement). + addWildcard() { + this._hasWildcardImport = true; + } + + // Returns all of the names with a specified binding type. + private _getNamesOfBindingType(type: NameBindingType): string[] { + let nameList: string[] = []; + + this._names.forEach((entry, name) => { + // Include names with inconsistent binding types as well to + // eliminate extraneous errors during analysis. + if (entry === type || entry === NameBindingType.Inconsistent) { + nameList.push(name); + } + }); + + return nameList; + } + +} diff --git a/server/src/parser/parseNodes.ts b/server/src/parser/parseNodes.ts new file mode 100644 index 000000000..15be1fb8d --- /dev/null +++ b/server/src/parser/parseNodes.ts @@ -0,0 +1,1093 @@ +/* +* parseNodes.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Definition of parse nodes that make up the Python asbtract +* syntax tree (AST). +*/ + +import { TextRange } from '../common/textRange'; +import { IdentifierToken, KeywordToken, NumberToken, + OperatorType, StringToken, Token } from './tokenizerTypes'; + +export type ParseNodeOrArray = undefined | ParseNode | ParseNode[]; +export type RecursiveParseNodeArray = ParseNodeOrArray | ParseNodeOrArray[]; + +export enum ParseNodeType { + None, + Error, + + Argument, + Assert, + Assignment, + AugmentedAssignment, + Await, + BinaryOperation, + Break, + Call, + Class, + Conditional, + Constant, + Continue, + Decorator, + Del, + Dictionary, + DictionaryExpandEntry, + DictionaryKeyEntry, + Ellipsis, + If, + Import, + ImportAs, + ImportFrom, + ImportFromAs, + Index, + Except, + For, + Function, + Global, + Lambda, + List, + ListComprehension, + ListComprehensionFor, + ListComprehensionIf, + MemberAccess, + Module, + ModuleName, + Name, + Nonlocal, + Number, + Parameter, + Pass, + Raise, + Return, + Set, + Slice, + Star, + StatementList, + String, + Suite, + Tuple, + Try, + TypeAnnotation, + UnaryOperation, + While, + With, + WithItem, + Yield, + YieldFrom +} + +export abstract class ParseNode extends TextRange { + readonly nodeType: ParseNodeType = ParseNodeType.None; + + // The parent field is filled in by the PostParseWalker, + // which isn't technically part of the parser. + parent?: ParseNode; + + constructor(initialRange: TextRange) { + super(initialRange.start, initialRange.length); + } + + abstract getChildren(): RecursiveParseNodeArray; + + getChildrenFlattened(): ParseNode[] { + return this._unflatten(this.getChildren()); + } + + private _unflatten(nodes: RecursiveParseNodeArray): ParseNode[] { + if (Array.isArray(nodes)) { + let nodeArray: ParseNode[] = []; + nodes.forEach(node => { + if (node) { + nodeArray = nodeArray.concat(this._unflatten(node)); + } + }); + return nodeArray; + } + + if (nodes) { + return [nodes]; + } + + return []; + } +} + +export class ModuleNode extends ParseNode { + readonly nodeType = ParseNodeType.Module; + statements: StatementNode[] = []; + + getChildren(): RecursiveParseNodeArray { + return this.statements; + } +} + +export class SuiteNode extends ParseNode { + readonly nodeType = ParseNodeType.Suite; + statements: StatementNode[] = []; + + getChildren(): RecursiveParseNodeArray { + return this.statements; + } +} + +export class IfNode extends ParseNode { + readonly nodeType = ParseNodeType.If; + testExpression: ExpressionNode; + ifSuite: SuiteNode; + elseSuite?: SuiteNode | IfNode; + + constructor(ifOrElifToken: Token, testExpression: ExpressionNode, + ifSuite: SuiteNode) { + super(ifOrElifToken); + this.testExpression = testExpression; + this.ifSuite = ifSuite; + this.extend(this.testExpression); + this.extend(this.ifSuite); + } + + getChildren(): RecursiveParseNodeArray { + return [this.testExpression, this.ifSuite, this.elseSuite]; + } +} + +export class WhileNode extends ParseNode { + readonly nodeType = ParseNodeType.While; + whileExpression?: ExpressionNode; + whileSuite?: SuiteNode; + elseSuite?: SuiteNode; + + getChildren(): RecursiveParseNodeArray { + return [this.whileExpression, this.whileSuite, this.elseSuite]; + } +} + +export class ForNode extends ParseNode { + readonly nodeType = ParseNodeType.For; + isAsync?: boolean; + targetExpression: ExpressionNode; + sequenceExpression: ExpressionNode; + forSuite: SuiteNode; + elseSuite?: SuiteNode; + + constructor(forToken: Token, targetExpression: ExpressionNode, + sequenceExpression: ExpressionNode, forSuite: SuiteNode) { + super(forToken); + this.targetExpression = targetExpression; + this.sequenceExpression = sequenceExpression; + this.forSuite = forSuite; + this.extend(forSuite); + } + + getChildren(): RecursiveParseNodeArray { + return [this.targetExpression, this.sequenceExpression, this.forSuite, this.elseSuite]; + } +} + +export type ListComprehensionIterNode = ListComprehensionForNode | ListComprehensionIfNode; + +export class ListComprehensionForNode extends ParseNode { + readonly nodeType = ParseNodeType.ListComprehensionFor; + isAsync?: boolean; + targetExpression: ExpressionNode; + sequenceExpression: ExpressionNode; + + constructor(startToken: Token, targetExpression: ExpressionNode, sequenceExpression: ExpressionNode) { + super(startToken); + this.targetExpression = targetExpression; + this.sequenceExpression = sequenceExpression; + this.extend(targetExpression); + this.extend(sequenceExpression); + } + + getChildren(): RecursiveParseNodeArray { + return [this.targetExpression, this.sequenceExpression]; + } +} + +export class ListComprehensionIfNode extends ParseNode { + readonly nodeType = ParseNodeType.ListComprehensionIf; + testExpression: ExpressionNode; + + constructor(ifToken: Token, testExpression: ExpressionNode) { + super(ifToken); + this.testExpression = testExpression; + this.extend(testExpression); + } + + getChildren(): RecursiveParseNodeArray { + return this.testExpression; + } +} + +export class TryNode extends ParseNode { + readonly nodeType = ParseNodeType.Try; + trySuite: SuiteNode; + exceptClauses: ExceptNode[] = []; + elseSuite?: SuiteNode; + finallySuite?: SuiteNode; + + constructor(tryToken: Token, trySuite: SuiteNode) { + super(tryToken); + this.trySuite = trySuite; + } + + getChildren(): RecursiveParseNodeArray { + return [this.trySuite, this.exceptClauses, this.elseSuite, this.finallySuite]; + } +} + +export class ExceptNode extends ParseNode { + readonly nodeType = ParseNodeType.Except; + typeExpression?: ExpressionNode; + name?: NameNode; + exceptSuite: SuiteNode; + + constructor(exceptToken: Token, exceptSuite: SuiteNode) { + super(exceptToken); + this.exceptSuite = exceptSuite; + this.extend(exceptSuite); + } + + getChildren(): RecursiveParseNodeArray { + return [this.typeExpression, this.name, this.exceptSuite]; + } +} + +export interface TypeAnnotationExpression { + // Type annotations can be specified as string literal values. + // In such a case, the rawExpression will contain the string + // literal and the expression will contain the parsed annotation. + // If the rawExpression is not a string literal, the two fields + // will be the same. + rawExpression: ExpressionNode; + expression: ExpressionNode; +} + +export class FunctionNode extends ParseNode { + readonly nodeType = ParseNodeType.Function; + decorators: DecoratorNode[] = []; + isAsync?: boolean; + name: NameNode; + parameters: ParameterNode[] = []; + returnTypeAnnotation?: TypeAnnotationExpression; + suite: SuiteNode; + + constructor(defToken: Token, name: NameNode, suite: SuiteNode) { + super(defToken); + this.name = name; + this.suite = suite; + this.extend(suite); + } + + getChildren(): RecursiveParseNodeArray { + return [this.decorators, this.name, this.parameters, + this.returnTypeAnnotation ? this.returnTypeAnnotation.expression : undefined, + this.suite]; + } +} + +export enum ParameterCategory { + Simple, + VarArgList, + VarArgDictionary +} + +export class ParameterNode extends ParseNode { + readonly nodeType = ParseNodeType.Parameter; + category: ParameterCategory; + name?: NameNode; + typeAnnotation?: TypeAnnotationExpression; + defaultValue?: ExpressionNode; + + constructor(startToken: Token, paramCategory: ParameterCategory) { + super(startToken); + this.category = paramCategory; + } + + getChildren(): RecursiveParseNodeArray { + return [this.name, + this.typeAnnotation ? this.typeAnnotation.expression : undefined, + this.defaultValue]; + } +} + +export class ClassNode extends ParseNode { + readonly nodeType = ParseNodeType.Class; + decorators: DecoratorNode[] = []; + name: NameNode; + arguments: ArgumentNode[] = []; + suite: SuiteNode; + + constructor(classToken: Token, name: NameNode, suite: SuiteNode) { + super(classToken); + this.name = name; + this.suite = suite; + this.extend(suite); + } + + getChildren(): RecursiveParseNodeArray { + return [this.decorators, this.name, this.arguments, this.suite]; + } +} + +export class WithNode extends ParseNode { + readonly nodeType = ParseNodeType.With; + isAsync?: boolean; + withItems: WithItemNode[] = []; + suite: SuiteNode; + + constructor(withToken: Token, suite: SuiteNode) { + super(withToken); + this.suite = suite; + this.extend(suite); + } + + getChildren(): RecursiveParseNodeArray { + return [this.withItems, this.suite]; + } +} + +export class WithItemNode extends ParseNode { + readonly nodeType = ParseNodeType.WithItem; + expression: ExpressionNode; + target?: ExpressionNode; + + constructor(expression: ExpressionNode) { + super(expression); + this.expression = expression; + } + + getChildren(): RecursiveParseNodeArray { + return [this.expression, this.target]; + } +} + +export class DecoratorNode extends ParseNode { + readonly nodeType = ParseNodeType.Decorator; + callName: ExpressionNode; + arguments: ArgumentNode[] = []; + + constructor(atToken: Token, callName: ExpressionNode) { + super(atToken); + this.callName = callName; + this.extend(callName); + } + + getChildren(): RecursiveParseNodeArray { + return [this.callName, this.arguments]; + } +} + +export class StatementListNode extends ParseNode { + readonly nodeType = ParseNodeType.StatementList; + statements: ParseNode[] = []; + + getChildren(): RecursiveParseNodeArray { + return this.statements; + } +} + +export type StatementNode = IfNode | WhileNode | ForNode | TryNode | + FunctionNode | ClassNode | WithNode | StatementListNode; + +export type SmallStatementNode = ExpressionNode | DelNode | PassNode | + ImportNode | GlobalNode | NonlocalNode | AssertNode; + +export abstract class ExpressionNode extends ParseNode { + abstract getAssignmentError(): string | undefined; +} + +export class ErrorExpressionNode extends ExpressionNode { + readonly nodeType = ParseNodeType.Error; + + getAssignmentError(): string | undefined { + return undefined; + } + + getChildren(): RecursiveParseNodeArray { + return undefined; + } +} + +export class UnaryExpressionNode extends ExpressionNode { + readonly nodeType = ParseNodeType.UnaryOperation; + expression: ExpressionNode; + operator: OperatorType; + + constructor(expression: ExpressionNode, operator: OperatorType) { + super(expression); + this.expression = expression; + this.operator = operator; + this.extend(expression); + } + + getAssignmentError(): string | undefined { + return 'Cannot assign value to expression'; + } + + getChildren(): RecursiveParseNodeArray { + return this.expression; + } +} + +export class BinaryExpressionNode extends ExpressionNode { + readonly nodeType = ParseNodeType.BinaryOperation; + leftExpression: ExpressionNode; + operator: OperatorType; + rightExpression: ExpressionNode; + + constructor(leftExpression: ExpressionNode, rightExpression: ExpressionNode, + operator: OperatorType) { + super(leftExpression); + this.leftExpression = leftExpression; + this.rightExpression = rightExpression; + this.operator = operator; + this.extend(rightExpression); + } + + getAssignmentError(): string | undefined { + return 'Cannot assign value to expression'; + } + + getChildren(): RecursiveParseNodeArray { + return [this.leftExpression, this.rightExpression]; + } +} + +export class AssignmentNode extends ExpressionNode { + readonly nodeType = ParseNodeType.Assignment; + leftExpression: ExpressionNode; + rightExpression: ExpressionNode; + + constructor(leftExpression: ExpressionNode, rightExpression: ExpressionNode) { + super(leftExpression); + this.leftExpression = leftExpression; + this.rightExpression = rightExpression; + this.extend(rightExpression); + } + + getAssignmentError(): string | undefined { + return this.rightExpression.getAssignmentError(); + } + + getChildren(): RecursiveParseNodeArray { + return [this.leftExpression, this.rightExpression]; + } +} + +export class TypeAnnotationExpressionNode extends ExpressionNode { + readonly nodeType = ParseNodeType.TypeAnnotation; + valueExpression: ExpressionNode; + typeAnnotation: TypeAnnotationExpression; + + constructor(valueExpression: ExpressionNode, typeAnnotation: TypeAnnotationExpression) { + super(valueExpression); + this.valueExpression = valueExpression; + this.typeAnnotation = typeAnnotation; + this.extend(typeAnnotation.rawExpression); + } + + getAssignmentError(): string | undefined { + return this.valueExpression.getAssignmentError(); + } + + getChildren(): RecursiveParseNodeArray { + return [this.valueExpression, this.typeAnnotation.expression]; + } +} + +export class AugmentedAssignemtnExpressionNode extends ExpressionNode { + readonly nodeType = ParseNodeType.AugmentedAssignment; + leftExpression: ExpressionNode; + operator: OperatorType; + rightExpression: ExpressionNode; + + constructor(leftExpression: ExpressionNode, rightExpression: ExpressionNode, operator: OperatorType) { + super(leftExpression); + this.leftExpression = leftExpression; + this.rightExpression = rightExpression; + this.operator = operator; + this.extend(rightExpression); + } + + getAssignmentError(): string | undefined { + return this.rightExpression.getAssignmentError(); + } + + getChildren(): RecursiveParseNodeArray { + return [this.leftExpression, this.rightExpression]; + } +} + +export class AwaitExpressionNode extends ExpressionNode { + readonly nodeType = ParseNodeType.Await; + expression: ExpressionNode; + + constructor(awaitToken: Token, expression: ExpressionNode) { + super(awaitToken); + this.expression = expression; + this.extend(expression); + } + + getAssignmentError(): string | undefined { + return 'Cannot assign to await expression'; + } + + getChildren(): RecursiveParseNodeArray { + return this.expression; + } +} + +export class ConditionalExpressionNode extends ExpressionNode { + readonly nodeType = ParseNodeType.Conditional; + leftExpression: ExpressionNode; + ifExpression: ExpressionNode; + elseExpression: ExpressionNode; + + constructor(leftExpression: ExpressionNode, ifExpression: ExpressionNode, elseExpression: ExpressionNode) { + super(leftExpression); + this.leftExpression = leftExpression; + this.ifExpression = ifExpression; + this.elseExpression = elseExpression; + this.extend(elseExpression); + } + + getAssignmentError(): string | undefined { + return 'Cannot assign value to conditional expression'; + } + + getChildren(): RecursiveParseNodeArray { + return [this.leftExpression, this.ifExpression, this.elseExpression]; + } +} + +export class StarExpressionNode extends ExpressionNode { + readonly nodeType = ParseNodeType.Star; + expression: ExpressionNode; + + constructor(starToken: Token, expression: ExpressionNode) { + super(starToken); + this.expression = expression; + this.extend(expression); + } + + getAssignmentError(): string | undefined { + return this.expression.getAssignmentError(); + } + + getChildren(): RecursiveParseNodeArray { + return this.expression; + } +} + +export class TupleExpressionNode extends ExpressionNode { + readonly nodeType = ParseNodeType.Tuple; + expressions: ExpressionNode[] = []; + + getAssignmentError(): string | undefined { + for (let expr of this.expressions) { + let msg = expr.getAssignmentError(); + if (msg) { + return msg; + } + } + return undefined; + } + + getChildren(): RecursiveParseNodeArray { + return this.expressions; + } +} + +export class CallExpressionNode extends ExpressionNode { + readonly nodeType = ParseNodeType.Call; + leftExpression: ExpressionNode; + arguments: ArgumentNode[] = []; + + constructor(leftExpression: ExpressionNode) { + super(leftExpression); + this.leftExpression = leftExpression; + } + + getAssignmentError(): string | undefined { + return 'Cannot assign value to function call'; + } + + getChildren(): RecursiveParseNodeArray { + return [this.leftExpression, this.arguments]; + } +} + +export class ListComprehensionNode extends ExpressionNode { + readonly nodeType = ParseNodeType.ListComprehension; + baseExpression: T; + comprehensions: ListComprehensionIterNode[] = []; + + constructor(baseExpression: T) { + super(baseExpression); + this.baseExpression = baseExpression; + } + + getAssignmentError(): string | undefined { + return 'Cannot assign value to list comprehension statement'; + } + + getChildren(): RecursiveParseNodeArray { + return [this.baseExpression, this.comprehensions]; + } +} + +export class IndexExpressionNode extends ExpressionNode { + readonly nodeType = ParseNodeType.Index; + baseExpression: ExpressionNode; + indexExpression: ExpressionNode; + + constructor(baseExpression: ExpressionNode, indexExpression: ExpressionNode) { + super(baseExpression); + this.baseExpression = baseExpression; + this.indexExpression = indexExpression; + } + + getAssignmentError(): string | undefined { + return undefined; + } + + getChildren(): RecursiveParseNodeArray { + return [this.baseExpression, this.indexExpression]; + } +} + +export class SliceExpressionNode extends ExpressionNode { + readonly nodeType = ParseNodeType.Slice; + startValue?: ExpressionNode; + endValue?: ExpressionNode; + stepValue?: ExpressionNode; + + getAssignmentError(): string | undefined { + return undefined; + } + + getChildren(): RecursiveParseNodeArray { + return [this.startValue, this.endValue, this.stepValue]; + } +} + +export class YieldExpressionNode extends ExpressionNode { + readonly nodeType = ParseNodeType.Yield; + expression: ExpressionNode; + + constructor(yieldToken: Token, expression: ExpressionNode) { + super(yieldToken); + this.expression = expression; + this.extend(expression); + } + + getAssignmentError(): string | undefined { + return 'Cannot assign to yield statement'; + } + + getChildren(): RecursiveParseNodeArray { + return this.expression; + } +} + +export class YieldFromExpressionNode extends ExpressionNode { + readonly nodeType = ParseNodeType.YieldFrom; + expression: ExpressionNode; + + constructor(yieldToken: Token, expression: ExpressionNode) { + super(yieldToken); + this.expression = expression; + this.extend(expression); + } + + getAssignmentError(): string | undefined { + return 'Cannot assign to yield statement'; + } + + getChildren(): RecursiveParseNodeArray { + return this.expression; + } +} + +export class MemberAccessExpressionNode extends ExpressionNode { + readonly nodeType = ParseNodeType.MemberAccess; + leftExpression: ExpressionNode; + memberName: NameNode; + + constructor(leftExpression: ExpressionNode, memberName: NameNode) { + super(leftExpression); + this.leftExpression = leftExpression; + this.memberName = memberName; + this.extend(memberName); + } + + getAssignmentError(): string | undefined { + return undefined; + } + + getChildren(): RecursiveParseNodeArray { + return [this.leftExpression, this.memberName]; + } +} + +export class LambdaNode extends ExpressionNode { + readonly nodeType = ParseNodeType.Lambda; + parameters: ParameterNode[] = []; + expression: ExpressionNode; + + constructor(lambdaToken: Token, expression: ExpressionNode) { + super(lambdaToken); + this.expression = expression; + this.extend(expression); + } + + getAssignmentError(): string | undefined { + return 'Cannot assign to lambda expression'; + } + + getChildren(): RecursiveParseNodeArray { + return [this.parameters, this.expression]; + } +} + +export class NameNode extends ExpressionNode { + readonly nodeType = ParseNodeType.Name; + nameToken: IdentifierToken; + + constructor(nameToken: IdentifierToken) { + super(nameToken); + this.nameToken = nameToken; + } + + getAssignmentError(): string | undefined { + return undefined; + } + + getChildren(): RecursiveParseNodeArray { + return undefined; + } +} + +export class ConstantNode extends ExpressionNode { + readonly nodeType = ParseNodeType.Constant; + token: KeywordToken; + + constructor(token: KeywordToken) { + super(token); + this.token = token; + } + + getAssignmentError(): string | undefined { + return 'Cannot assign to constant'; + } + + getChildren(): RecursiveParseNodeArray { + return undefined; + } +} + +export class EllipsisNode extends ExpressionNode { + readonly nodeType = ParseNodeType.Ellipsis; + + getAssignmentError(): string | undefined { + return 'Cannot assign to ellipsis'; + } + + getChildren(): RecursiveParseNodeArray { + return undefined; + } +} + +export class NumberNode extends ExpressionNode { + readonly nodeType = ParseNodeType.Number; + token: NumberToken; + + constructor(token: NumberToken) { + super(token); + this.token = token; + } + + getAssignmentError(): string | undefined { + return 'Cannot assign to numeric literal'; + } + + getChildren(): RecursiveParseNodeArray { + return undefined; + } +} + +export class StringNode extends ExpressionNode { + readonly nodeType = ParseNodeType.String; + tokens: StringToken[]; + + constructor(tokens: StringToken[]) { + super(tokens[0]); + this.tokens = tokens; + } + + getAssignmentError(): string | undefined { + return 'Cannot assign to string literal'; + } + + getChildren(): RecursiveParseNodeArray { + return undefined; + } + + getValue(): string { + return this.tokens.map(t => t.value).join(''); + } +} + +export class DictionaryNode extends ExpressionNode { + readonly nodeType = ParseNodeType.Dictionary; + entries: DictionaryEntryNode[] = []; + + getAssignmentError(): string | undefined { + return undefined; + } + + getChildren(): RecursiveParseNodeArray { + return this.entries; + } +} + +export class DictionaryKeyEntryNode extends ParseNode { + readonly nodeType = ParseNodeType.DictionaryKeyEntry; + keyExpression: ExpressionNode; + valueExpression: ExpressionNode; + + constructor(keyExpression: ExpressionNode, valueExpression: ExpressionNode) { + super(keyExpression); + this.keyExpression = keyExpression; + this.valueExpression = valueExpression; + this.extend(valueExpression); + } + + getChildren(): RecursiveParseNodeArray { + return [this.keyExpression, this.valueExpression]; + } +} + +export class DictionaryExpandEntryNode extends ExpressionNode { + readonly nodeType = ParseNodeType.DictionaryExpandEntry; + expandExpression: ExpressionNode; + + constructor(expandExpression: ExpressionNode) { + super(expandExpression); + this.expandExpression = expandExpression; + } + + getAssignmentError(): string | undefined { + return 'Cannot assign to dictionary expand clause'; + } + + getChildren(): RecursiveParseNodeArray { + return this.expandExpression; + } +} + +export type DictionaryEntryNode = DictionaryKeyEntryNode | DictionaryExpandEntryNode | ListComprehensionNode; + +export class SetNode extends ExpressionNode { + readonly nodeType = ParseNodeType.Set; + entries: ExpressionNode[] = []; + + getAssignmentError(): string | undefined { + return undefined; + } + + getChildren(): RecursiveParseNodeArray { + return this.entries; + } +} + +export class ListNode extends ExpressionNode { + readonly nodeType = ParseNodeType.List; + entries: ExpressionNode[] = []; + + getAssignmentError(): string | undefined { + return undefined; + } + + getChildren(): RecursiveParseNodeArray { + return this.entries; + } +} + +export enum ArgumentCategory { + Simple, + List, + Dictionary +} + +export class ArgumentNode extends ParseNode { + readonly nodeType = ParseNodeType.Argument; + argumentCategory: ArgumentCategory; + name?: NameNode; + valueExpression: ExpressionNode; + + constructor(startToken: Token, valueExpression: ExpressionNode, argCategory: ArgumentCategory) { + super(startToken); + this.valueExpression = valueExpression; + this.argumentCategory = argCategory; + this.extend(valueExpression); + } + + getChildren(): RecursiveParseNodeArray { + return this.valueExpression; + } +} + +export class DelNode extends ParseNode { + readonly nodeType = ParseNodeType.Del; + expressions: ExpressionNode[] = []; + + constructor(delToken: Token) { + super(delToken); + } + + getChildren(): RecursiveParseNodeArray { + return this.expressions; + } +} + +export class PassNode extends ParseNode { + readonly nodeType = ParseNodeType.Pass; + + getChildren(): RecursiveParseNodeArray { + return undefined; + } +} + +export class ImportNode extends ParseNode { + readonly nodeType = ParseNodeType.Import; + list: ImportAsNode[] = []; + + getChildren(): RecursiveParseNodeArray { + return this.list; + } +} + +export class ModuleNameNode extends ParseNode { + readonly nodeType = ParseNodeType.ModuleName; + leadingDots = 0; + nameParts: NameNode[] = []; + + getChildren(): RecursiveParseNodeArray { + return undefined; + } +} + +export class ImportAsNode extends ParseNode { + readonly nodeType = ParseNodeType.ImportAs; + module: ModuleNameNode; + alias?: NameNode; + + constructor(module: ModuleNameNode) { + super(module); + this.module = module; + } + + getChildren(): RecursiveParseNodeArray { + return [this.module, this.alias]; + } +} + +export class ImportFromNode extends ParseNode { + readonly nodeType = ParseNodeType.ImportFrom; + module: ModuleNameNode; + + constructor(fromToken: Token, module: ModuleNameNode) { + super(fromToken); + this.module = module; + this.extend(module); + } + + // An empty list implies "import *". + imports: ImportFromAsNode[] = []; + + getChildren(): RecursiveParseNodeArray { + return [this.module, this.imports]; + } +} + +export class ImportFromAsNode extends ParseNode { + readonly nodeType = ParseNodeType.ImportFromAs; + name: NameNode; + alias?: NameNode; + + constructor(name: NameNode) { + super(name); + this.name = name; + } + + getChildren(): RecursiveParseNodeArray { + return [this.name, this.alias]; + } +} + +export class GlobalNode extends ParseNode { + readonly nodeType = ParseNodeType.Global; + nameList: NameNode[] = []; + + getChildren(): RecursiveParseNodeArray { + return this.nameList; + } +} + +export class NonlocalNode extends ParseNode { + readonly nodeType = ParseNodeType.Nonlocal; + nameList: NameNode[] = []; + + getChildren(): RecursiveParseNodeArray { + return this.nameList; + } +} + +export class AssertNode extends ParseNode { + readonly nodeType = ParseNodeType.Assert; + expressions: ExpressionNode[] = []; + + getChildren(): RecursiveParseNodeArray { + return this.expressions; + } +} + +export class BreakNode extends ParseNode { + readonly nodeType = ParseNodeType.Break; + + getChildren(): RecursiveParseNodeArray { + return undefined; + } +} + +export class ContinueNode extends ParseNode { + readonly nodeType = ParseNodeType.Continue; + + getChildren(): RecursiveParseNodeArray { + return undefined; + } +} + +export class ReturnNode extends ParseNode { + readonly nodeType = ParseNodeType.Return; + returnExpression?: ExpressionNode; + + getChildren(): RecursiveParseNodeArray { + return this.returnExpression; + } +} + +export class RaiseNode extends ParseNode { + readonly nodeType = ParseNodeType.Raise; + typeExpression?: ExpressionNode; + valueExpression?: ExpressionNode; + tracebackExpression?: ExpressionNode; + + getChildren(): RecursiveParseNodeArray { + return [this.typeExpression, this.valueExpression, this.tracebackExpression]; + } +} diff --git a/server/src/parser/parser.ts b/server/src/parser/parser.ts new file mode 100644 index 000000000..9aea0a292 --- /dev/null +++ b/server/src/parser/parser.ts @@ -0,0 +1,2392 @@ +/* +* parser.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Based on code from python-language-server repository: +* https://github.com/Microsoft/python-language-server +* +* Parser for the Python language. Converts a stream of tokens +* into an abstract syntax tree (AST). +*/ + +import * as assert from 'assert'; + +import { CancelToken } from '../common/cancelToken'; +import { Diagnostic } from '../common/diagnostic'; +import { DiagnosticSink } from '../common/diagnosticSink'; +import { convertOffsetsToRange } from '../common/positionUtils'; +import { LatestStablePythonVersion, PythonVersion } from '../common/pythonVersion'; +import StringMap from '../common/stringMap'; +import { TextRange } from '../common/textRange'; +import { TextRangeCollection } from '../common/textRangeCollection'; +import { timingStats } from '../common/timing'; +import { ArgumentCategory, ArgumentNode, AssertNode, + AssignmentNode, AugmentedAssignemtnExpressionNode, AwaitExpressionNode, + BinaryExpressionNode, BreakNode, CallExpressionNode, ClassNode, + ConditionalExpressionNode, ConstantNode, ContinueNode, DecoratorNode, + DelNode, DictionaryEntryNode, DictionaryExpandEntryNode, + DictionaryKeyEntryNode, DictionaryNode, EllipsisNode, ErrorExpressionNode, + ExceptNode, ExpressionNode, ForNode, FunctionNode, GlobalNode, IfNode, + ImportAsNode, ImportFromAsNode, ImportFromNode, ImportNode, + IndexExpressionNode, LambdaNode, ListComprehensionForNode, + ListComprehensionIfNode, ListComprehensionIterNode, ListComprehensionNode, + ListNode, MemberAccessExpressionNode, ModuleNameNode, ModuleNode, NameNode, NonlocalNode, + NumberNode, ParameterCategory, ParameterNode, ParseNode, PassNode, + RaiseNode, ReturnNode, SetNode, SliceExpressionNode, StarExpressionNode, + StatementListNode, StatementNode, StringNode, SuiteNode, TryNode, + TupleExpressionNode, TypeAnnotationExpression, TypeAnnotationExpressionNode, UnaryExpressionNode, + WhileNode, WithItemNode, WithNode, YieldExpressionNode, YieldFromExpressionNode } from './parseNodes'; +import { Tokenizer, TokenizerOutput } from './tokenizer'; +import { DedentToken, IdentifierToken, KeywordToken, KeywordType, + NumberToken, OperatorToken, OperatorType, QuoteTypeFlags, StringToken, Token, TokenType } from './tokenizerTypes'; + +interface ExpressionListResult { + list: ExpressionNode[]; + trailingComma: boolean; + parseError?: ErrorExpressionNode; +} + +export class ParseOptions { + constructor() { + this.isStubFile = false; + this.pythonVersion = LatestStablePythonVersion; + } + + isStubFile: boolean; + pythonVersion: PythonVersion; +} + +export interface ParseResults { + parseTree: ModuleNode; + tokens: TextRangeCollection; + lines: TextRangeCollection; +} + +export interface ParseExpressionTextResults { + parseTree?: ExpressionNode; + diagnostics: Diagnostic[]; +} + +export class Parser { + private _fileContents?: string; + private _tokenizerOutput?: TokenizerOutput; + private _tokenIndex = 0; + private _parseOptions: ParseOptions = new ParseOptions(); + private _cancelToken?: CancelToken; + private _diagSink: DiagnosticSink = new DiagnosticSink(); + private _isInLoop = false; + private _isInFinally = false; + + parseSourceFile(fileContents: string, parseOptions: ParseOptions, + diagSink: DiagnosticSink, cancelToken?: CancelToken): ParseResults { + timingStats.tokenizeFileTime.timeOperation(() => { + this._startNewParse(fileContents, 0, fileContents.length, + parseOptions, diagSink, cancelToken); + }); + + let moduleNode = new ModuleNode(new TextRange(0, fileContents.length)); + + timingStats.parseFileTime.timeOperation(() => { + while (!this._atEof()) { + if (!this._consumeTokenIfType(TokenType.NewLine)) { + // Handle a common error case and try to recover. + let nextToken = this._peekToken(); + if (nextToken.type === TokenType.Indent) { + this._getNextToken(); + nextToken = this._peekToken(); + this._addError('Unexpected indentation', nextToken); + } + + let statement = this._parseStatement(); + if (!statement) { + // Perform basic error recovery to get to the next line. + this._consumeTokensUntilType(TokenType.NewLine); + } else { + moduleNode.statements.push(statement); + } + + this._checkCancel(); + } + } + }); + + return { + parseTree: moduleNode, + tokens: this._tokenizerOutput!.tokens, + lines: this._tokenizerOutput!.lines + }; + } + + parseTextExpression(fileContents: string, textOffset: number, textLength: number, + parseOptions: ParseOptions): ParseExpressionTextResults { + let diagSink = new DiagnosticSink(); + this._startNewParse(fileContents, textOffset, textLength, parseOptions, diagSink); + + let parseTree = this._parseTestExpression(); + + return { + parseTree, + diagnostics: diagSink.diagnostics + }; + } + + private _startNewParse(fileContents: string, textOffset: number, textLength: number, + parseOptions: ParseOptions, diagSink: DiagnosticSink, cancelToken?: CancelToken) { + this._fileContents = fileContents; + this._parseOptions = parseOptions; + this._cancelToken = cancelToken; + this._diagSink = diagSink; + + this._checkCancel(); + + // Tokenize the file contents. + let tokenizer = new Tokenizer(); + this._tokenizerOutput = tokenizer.tokenize(fileContents, textOffset, textLength); + this._tokenIndex = 0; + + this._checkCancel(); + } + + // stmt: simple_stmt | compound_stmt + // compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt + // | funcdef | classdef | decorated | async_stmt + private _parseStatement(): StatementNode | undefined { + // Handle the errant condition of a dedent token here to provide + // better recovery. + if (this._consumeTokenIfType(TokenType.Dedent)) { + this._addError('Unindent not expected', this._peekToken()); + } + + switch (this._peekKeywordType()) { + case KeywordType.If: + return this._parseIfStatement(); + + case KeywordType.While: + return this._parseWhileStatement(); + + case KeywordType.For: + return this._parseForStatement(); + + case KeywordType.Try: + return this._parseTryStatement(); + + case KeywordType.With: + return this._parseWithStatement(); + + case KeywordType.Def: + return this._parseFunctionDef(); + + case KeywordType.Class: + return this._parseClassDef(); + + case KeywordType.Async: + return this._parseAsyncStatement(); + } + + if (this._peekOperatorType() === OperatorType.MatrixMultiply) { + return this._parseDecorated(); + } + + return this._parseSimpleStatement(); + } + + // async_stmt: 'async' (funcdef | with_stmt | for_stmt) + private _parseAsyncStatement(): StatementNode | undefined { + let asyncToken = this._getKeywordToken(KeywordType.Async); + + switch (this._peekKeywordType()) { + case KeywordType.Def: + return this._parseFunctionDef(asyncToken); + + case KeywordType.With: + return this._parseWithStatement(asyncToken); + + case KeywordType.For: + return this._parseForStatement(asyncToken); + } + + this._addError('Expected "def", "with" or "for" to follow "async".', + asyncToken); + + return undefined; + } + + // if_stmt: 'if' test_suite ('elif' test_suite)* ['else' suite] + // test_suite: test suite + // test: or_test ['if' or_test 'else' test] | lambdef + private _parseIfStatement(keywordType: KeywordType.If | KeywordType.Elif = KeywordType.If): IfNode { + let ifOrElifToken = this._getKeywordToken(keywordType); + + let test = this._parseTestExpression(); + let suite = this._parseSuite(); + let ifNode = new IfNode(ifOrElifToken, test, suite); + + if (this._consumeTokenIfKeyword(KeywordType.Else)) { + ifNode.elseSuite = this._parseSuite(); + ifNode.extend(ifNode.elseSuite); + } else if (this._peekKeywordType() === KeywordType.Elif) { + // Recursively handle an "elif" statement. + ifNode.elseSuite = this._parseIfStatement(KeywordType.Elif); + ifNode.extend(ifNode.elseSuite); + } + + return ifNode; + } + + private _parseLoopSuite(): SuiteNode { + const wasInLoop = this._isInLoop; + const wasInFinally = this._isInFinally; + this._isInLoop = true; + this._isInFinally = false; + + let suite = this._parseSuite(); + + this._isInLoop = wasInLoop; + this._isInFinally = wasInFinally; + + return suite; + } + + // suite: ':' (simple_stmt | NEWLINE INDENT stmt+ DEDENT) + private _parseSuite(): SuiteNode { + let nextToken = this._peekToken(); + let suite = new SuiteNode(nextToken); + + if (!this._consumeTokenIfType(TokenType.Colon)) { + this._addError('Expected ":"', nextToken); + return suite; + } + + if (this._consumeTokenIfType(TokenType.NewLine)) { + if (!this._consumeTokenIfType(TokenType.Indent)) { + this._addError('Expected indented block', this._peekToken()); + } + + while (true) { + // Handle a common error here and see if we can recover. + let nextToken = this._peekToken(); + if (nextToken.type === TokenType.Indent) { + this._getNextToken(); + nextToken = this._peekToken(); + this._addError('Unexpected indentation', nextToken); + } + + let statement = this._parseStatement(); + if (!statement) { + // Perform basic error recovery to get to the next line. + this._consumeTokensUntilType(TokenType.NewLine); + } else { + suite.statements.push(statement); + } + + let dedentToken = this._peekToken() as DedentToken; + if (this._consumeTokenIfType(TokenType.Dedent)) { + if (!dedentToken.matchesIndent) { + this._addError('Unindent amount does not match previous indent', dedentToken); + } + break; + } + + if (this._peekTokenType() === TokenType.EndOfStream) { + break; + } + } + } else { + suite.statements.push(this._parseSimpleStatement()); + } + + if (suite.statements.length > 0) { + suite.extend(suite.statements); + } + + return suite; + } + + // for_stmt: [async] 'for' exprlist 'in' testlist suite ['else' suite] + private _parseForStatement(asyncToken?: KeywordToken): ForNode { + let forToken = this._getKeywordToken(KeywordType.For); + + let exprListResult = this._parseExpressionList(true); + let targetExpr = this._makeExpressionOrTuple(exprListResult); + let seqExpr: ExpressionNode; + let forSuite: SuiteNode; + let elseSuite: SuiteNode | undefined; + + if (!this._consumeTokenIfKeyword(KeywordType.In)) { + seqExpr = this._handleExpressionParseError('Expected "in"'); + forSuite = new SuiteNode(this._peekToken()); + } else { + seqExpr = this._parseTestListAsExpression('Expected expression after "in"'); + forSuite = this._parseLoopSuite(); + + if (this._consumeTokenIfKeyword(KeywordType.Else)) { + elseSuite = this._parseSuite(); + } + } + + let forNode = new ForNode(forToken, targetExpr, seqExpr, forSuite); + forNode.elseSuite = elseSuite; + forNode.extend(elseSuite); + + if (asyncToken) { + forNode.isAsync = true; + forNode.extend(asyncToken); + } + + return forNode; + } + + // comp_iter: comp_for | comp_if + private _tryParseListComprehension(target: T): ListComprehensionNode | undefined { + let compFor = this._tryParseCompForStatement(); + + if (!compFor) { + return undefined; + } + + let compList: ListComprehensionIterNode[] = [compFor]; + while (true) { + let compIter = this._tryParseCompForStatement() || this._tryParseCompIfStatement(); + if (!compIter) { + break; + } + compList.push(compIter); + } + + let listCompNode = new ListComprehensionNode(target); + listCompNode.comprehensions = compList; + listCompNode.extend(compList); + return listCompNode; + } + + // comp_for: ['async'] 'for' exprlist 'in' or_test [comp_iter] + private _tryParseCompForStatement(): ListComprehensionForNode | undefined { + let startTokenKeywordType = this._peekKeywordType(); + + if (startTokenKeywordType === KeywordType.Async) { + let nextToken = this._peekToken(1) as KeywordToken; + if (nextToken.type !== TokenType.Keyword || nextToken.keywordType !== KeywordType.For) { + return undefined; + } + } else if (startTokenKeywordType !== KeywordType.For) { + return undefined; + } + + let asyncToken: KeywordToken | undefined; + if (this._peekKeywordType() === KeywordType.Async) { + asyncToken = this._getKeywordToken(KeywordType.Async); + } + + let forToken = this._getKeywordToken(KeywordType.For); + + let exprListResult = this._parseExpressionList(true); + let targetExpr = this._makeExpressionOrTuple(exprListResult); + let seqExpr: ExpressionNode; + + if (!this._consumeTokenIfKeyword(KeywordType.In)) { + seqExpr = this._handleExpressionParseError('Expected "in"'); + } else { + seqExpr = this._parseOrTest(); + } + + let compForNode = new ListComprehensionForNode(asyncToken || forToken, + targetExpr, seqExpr); + + if (asyncToken) { + compForNode.isAsync = true; + } + + return compForNode; + } + + // comp_if: 'if' test_nocond [comp_iter] + // comp_iter: comp_for | comp_if + private _tryParseCompIfStatement(): ListComprehensionIfNode | undefined { + if (this._peekKeywordType() !== KeywordType.If) { + return undefined; + } + + let ifToken = this._getKeywordToken(KeywordType.If); + let ifExpr = this._tryParseLambdaExpression() || this._parseOrTest(); + + let compIfNode = new ListComprehensionIfNode(ifToken, ifExpr); + + return compIfNode; + } + + // while_stmt: 'while' test suite ['else' suite] + private _parseWhileStatement(): WhileNode { + let whileToken = this._getKeywordToken(KeywordType.While); + + let whileNode = new WhileNode(whileToken); + + whileNode.whileExpression = this._parseTestExpression(); + whileNode.whileSuite = this._parseLoopSuite(); + + if (this._consumeTokenIfKeyword(KeywordType.Else)) { + whileNode.elseSuite = this._parseSuite(); + } + whileNode.extend(whileNode.elseSuite || whileNode.whileSuite); + + return whileNode; + } + + // try_stmt: ('try' suite + // ((except_clause suite)+ + // ['else' suite] + // ['finally' suite] | + // 'finally' suite)) + // except_clause: 'except' [test ['as' NAME]] + private _parseTryStatement(): TryNode { + let tryToken = this._getKeywordToken(KeywordType.Try); + let trySuite = this._parseSuite(); + let tryNode = new TryNode(tryToken, trySuite); + let sawCatchAllExcept = false; + + while (true) { + let exceptToken = this._peekToken(); + if (!this._consumeTokenIfKeyword(KeywordType.Except)) { + break; + } + + let typeExpr: ExpressionNode | undefined; + let symbolName: IdentifierToken | undefined; + if (this._peekTokenType() !== TokenType.Colon) { + typeExpr = this._parseTestExpression(); + + if (this._consumeTokenIfKeyword(KeywordType.As)) { + symbolName = this._getTokenIfIdentifier(); + if (!symbolName) { + this._addError('Expected symbol name after "as"', this._peekToken()); + } + } + } + + if (!typeExpr) { + if (sawCatchAllExcept) { + this._addError('Only one catch-all except clause is allowed', exceptToken); + } + sawCatchAllExcept = true; + } else { + if (sawCatchAllExcept) { + this._addError('A named except clause cannot appear after catch-all except clause', + typeExpr); + } + } + + let exceptSuite = this._parseSuite(); + let exceptNode = new ExceptNode(exceptToken, exceptSuite); + exceptNode.typeExpression = typeExpr; + if (symbolName) { + exceptNode.name = new NameNode(symbolName); + } + + tryNode.exceptClauses.push(exceptNode); + } + tryNode.extend(tryNode.exceptClauses); + + if (tryNode.exceptClauses.length > 0) { + if (this._consumeTokenIfKeyword(KeywordType.Else)) { + tryNode.elseSuite = this._parseSuite(); + tryNode.extend(tryNode.elseSuite); + } + } + + if (this._consumeTokenIfKeyword(KeywordType.Finally)) { + tryNode.finallySuite = this._parseSuite(); + tryNode.extend(tryNode.finallySuite); + } + + return tryNode; + } + + // funcdef: 'def' NAME parameters ['->' test] ':' suite + // parameters: '(' [typedargslist] ')' + private _parseFunctionDef(asyncToken?: KeywordToken, decorators?: DecoratorNode[]): FunctionNode { + let defToken = this._getKeywordToken(KeywordType.Def); + + let nameToken = this._getTokenIfIdentifier(); + if (!nameToken) { + this._addError('Expected function name after "def"', defToken); + nameToken = new IdentifierToken(0, 0, ''); + } + + if (!this._consumeTokenIfType(TokenType.OpenParenthesis)) { + this._addError('Expected "("', this._peekToken()); + } + + let paramList = this._parseVarArgsList(TokenType.CloseParenthesis, true); + + if (!this._consumeTokenIfType(TokenType.CloseParenthesis)) { + this._addError('Expected ")"', this._peekToken()); + } + + let returnType: ExpressionNode | undefined; + if (this._consumeTokenIfType(TokenType.Arrow)) { + returnType = this._parseTestExpression(); + } + + let suite = this._parseSuite(); + + let functionNode = new FunctionNode(defToken, new NameNode(nameToken), suite); + if (asyncToken) { + functionNode.isAsync = true; + functionNode.extend(asyncToken); + } + functionNode.parameters = paramList; + if (decorators) { + functionNode.decorators = decorators; + if (decorators.length > 0) { + functionNode.extend(decorators[0]); + } + } + if (returnType) { + functionNode.returnTypeAnnotation = this._parseTypeAnnotation(returnType); + functionNode.extend(functionNode.returnTypeAnnotation.rawExpression); + } + + return functionNode; + } + + // typedargslist: ( + // tfpdef ['=' test] (',' tfpdef ['=' test])* + // [ ',' + // [ + // '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]] + // | '**' tfpdef [','] + // ] + // ] + // | '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]] + // | '**' tfpdef [',']) + // tfpdef: NAME [':' test] + // vfpdef: NAME; + private _parseVarArgsList(terminator: TokenType, allowAnnotations: boolean): ParameterNode[] { + let paramMap = new StringMap(); + let paramList: ParameterNode[] = []; + let sawDefaultParam = false; + let reportedNonDefaultParamErr = false; + let sawKwSeparator = false; + let sawVarArgs = false; + let sawKwArgs = false; + + while (true) { + if (this._peekTokenType() === terminator) { + break; + } + + let param = this._parseParameter(allowAnnotations); + if (!param) { + this._consumeTokensUntilType(terminator); + break; + } + + if (param.name) { + let name = param.name.nameToken.value; + if (!paramMap.set(name, name)) { + this._addError(`Duplicate parameter '${ name }'`, param.name); + } + } + + if (param.category === ParameterCategory.Simple) { + if (param.defaultValue) { + sawDefaultParam = true; + } else if (sawDefaultParam && !sawKwSeparator) { + // Report this error only once. + if (!reportedNonDefaultParamErr) { + this._addError(`Non-default argument follows default argument`, param); + reportedNonDefaultParamErr = true; + } + } + } + + paramList.push(param); + + if (param.category === ParameterCategory.VarArgList) { + if (!param.name) { + if (sawKwSeparator) { + this._addError(`Only one '*' separator is allowed`, param); + } + sawKwSeparator = true; + } else { + if (sawVarArgs) { + this._addError(`Only one '*' parameter is allowed`, param); + } + sawVarArgs = true; + } + } + + if (param.category === ParameterCategory.VarArgDictionary) { + if (sawKwArgs) { + this._addError(`Only one '**' parameter is allowed`, param); + } + sawKwArgs = true; + } else if (sawKwArgs) { + this._addError(`Parameter cannot follow '**' parameter`, param); + } + + if (!this._consumeTokenIfType(TokenType.Comma)) { + break; + } + } + + if (paramList.length > 0) { + let lastParam = paramList[paramList.length - 1]; + if (!lastParam.name) { + this._addError('Named argument must follow bar \'*\'', lastParam); + } + } + + return paramList; + } + + private _parseParameter(allowAnnotations: boolean): ParameterNode { + let starCount = 0; + let firstToken = this._peekToken(); + + if (this._consumeTokenIfOperator(OperatorType.Multiply)) { + starCount = 1; + } else if (this._consumeTokenIfOperator(OperatorType.Power)) { + starCount = 2; + } + + let paramName = this._getTokenIfIdentifier(); + if (!paramName) { + if (starCount === 1) { + let paramNode = new ParameterNode(firstToken, ParameterCategory.VarArgList); + return paramNode; + } + this._addError('Expected parameter name', this._peekToken()); + } + + let paramType = ParameterCategory.Simple; + if (starCount === 1) { + paramType = ParameterCategory.VarArgList; + } else if (starCount === 2) { + paramType = ParameterCategory.VarArgDictionary; + } + let paramNode = new ParameterNode(firstToken, paramType); + if (paramName) { + paramNode.name = new NameNode(paramName); + } + paramNode.extend(paramName); + + if (allowAnnotations && this._consumeTokenIfType(TokenType.Colon)) { + paramNode.typeAnnotation = this._parseTypeAnnotation(this._parseTestExpression()); + paramNode.extend(paramNode.typeAnnotation.rawExpression); + } + + if (this._consumeTokenIfOperator(OperatorType.Assign)) { + paramNode.defaultValue = this._parseTestExpression(); + paramNode.extend(paramNode.defaultValue); + + if (starCount > 0) { + this._addError(`Parameter with '*' or '**' cannot have default value`, + paramNode.defaultValue); + } + } + + return paramNode; + } + + // with_stmt: 'with' with_item (',' with_item)* ':' suite + private _parseWithStatement(asyncToken?: KeywordToken): WithNode { + let withToken = this._getKeywordToken(KeywordType.With); + let withItemList: WithItemNode[] = []; + + while (true) { + withItemList.push(this._parseWithItem()); + + if (!this._consumeTokenIfType(TokenType.Comma)) { + break; + } + } + + let withSuite = this._parseSuite(); + let withNode = new WithNode(withToken, withSuite); + if (asyncToken) { + withNode.isAsync = true; + withNode.extend(asyncToken); + } + withNode.withItems = withItemList; + return withNode; + } + + // with_item: test ['as' expr] + private _parseWithItem(): WithItemNode { + let expr = this._parseTestExpression(); + let itemNode = new WithItemNode(expr); + + if (this._consumeTokenIfKeyword(KeywordType.As)) { + itemNode.target = this._parseExpression(false); + itemNode.extend(itemNode.target); + } + + return itemNode; + } + + // decorators: decorator+ + // decorated: decorators (classdef | funcdef | async_funcdef) + private _parseDecorated(): StatementNode | undefined { + let decoratorList: DecoratorNode[] = []; + + while (true) { + if (this._peekOperatorType() === OperatorType.MatrixMultiply) { + decoratorList.push(this._parseDecorator()); + } else { + break; + } + } + + let nextToken = this._peekToken() as KeywordToken; + if (nextToken.type === TokenType.Keyword) { + if (nextToken.keywordType === KeywordType.Async) { + this._getNextToken(); + + if (this._peekKeywordType() !== KeywordType.Def) { + this._addError('Expected function definition after "async"', this._peekToken()); + return undefined; + } + return this._parseFunctionDef(nextToken, decoratorList); + } else if (nextToken.keywordType === KeywordType.Def) { + return this._parseFunctionDef(undefined, decoratorList); + } else if (nextToken.keywordType === KeywordType.Class) { + return this._parseClassDef(decoratorList); + } + } + + this._addError('Expected function or class declaration after decorator', this._peekToken()); + return undefined; + } + + // decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE + private _parseDecorator(): DecoratorNode { + let atOperator = this._getNextToken() as OperatorToken; + assert.equal(atOperator.operatorType, OperatorType.MatrixMultiply); + + let callNameExpr: ExpressionNode | undefined; + while (true) { + let namePart = this._getTokenIfIdentifier(); + if (!namePart) { + this._addError('Expected decorator name', this._peekToken()); + break; + } + + let namePartNode = new NameNode(namePart); + + if (!callNameExpr) { + callNameExpr = namePartNode; + } else { + callNameExpr = new MemberAccessExpressionNode(callNameExpr, namePartNode); + } + + if (!this._consumeTokenIfType(TokenType.Dot)) { + break; + } + } + + if (!callNameExpr) { + callNameExpr = new ErrorExpressionNode(this._peekToken()); + } + + let decoratorNode = new DecoratorNode(atOperator, callNameExpr); + + if (this._consumeTokenIfType(TokenType.OpenParenthesis)) { + decoratorNode.arguments = this._parseArgList(); + + let nextToken = this._peekToken(); + if (!this._consumeTokenIfType(TokenType.CloseParenthesis)) { + this._addError('Expected ")"', this._peekToken()); + } else { + decoratorNode.extend(nextToken); + } + } + + if (!this._consumeTokenIfType(TokenType.NewLine)) { + this._addError('Expected new line at end of decorator', this._peekToken()); + this._consumeTokensUntilType(TokenType.NewLine); + } + + return decoratorNode; + } + + // classdef: 'class' NAME ['(' [arglist] ')'] suite + private _parseClassDef(decorators?: DecoratorNode[]): ClassNode { + let classToken = this._getKeywordToken(KeywordType.Class); + + let nameToken = this._getTokenIfIdentifier(); + if (!nameToken) { + this._addError('Expected class name', this._peekToken()); + nameToken = new IdentifierToken(0, 0, ''); + } + + let argList: ArgumentNode[] = []; + if (this._consumeTokenIfType(TokenType.OpenParenthesis)) { + argList = this._parseArgList(); + + if (!this._consumeTokenIfType(TokenType.CloseParenthesis)) { + this._addError('Expected ")"', this._peekToken()); + } + } + + let suite = this._parseSuite(); + + let classNode = new ClassNode(classToken, new NameNode(nameToken), suite); + classNode.arguments = argList; + if (decorators) { + classNode.decorators = decorators; + if (decorators.length > 0) { + classNode.extend(decorators[0]); + } + } + + return classNode; + } + + private _parsePassStatement(): PassNode { + return new PassNode(this._getKeywordToken(KeywordType.Pass)); + } + + private _parseBreakStatement(): BreakNode { + let breakToken = this._getKeywordToken(KeywordType.Break); + + if (!this._isInLoop) { + this._addError('"break" can be used only within a loop', + breakToken); + } + + return new BreakNode(breakToken); + } + + private _parseContinueStatement(): ContinueNode { + let continueToken = this._getKeywordToken(KeywordType.Continue); + + if (!this._isInLoop) { + this._addError('"continue" can be used only within a loop', + continueToken); + } else if (this._isInFinally) { + this._addError('"continue" cannot be used within a finally clause', + continueToken); + } + + return new ContinueNode(continueToken); + } + + // return_stmt: 'return' [testlist] + private _parseReturnStatement(): ReturnNode { + let returnToken = this._getKeywordToken(KeywordType.Return); + + let returnNode = new ReturnNode(returnToken); + + if (!this._isNextTokenNeverExpression()) { + let returnExpr = this._parseTestListAsExpression('Expected expression after "return"'); + returnNode.returnExpression = returnExpr; + returnNode.extend(returnExpr); + } + + // TODO - report error if version is < V33 and one or more + // parameters are being returned from a generator (i.e. + // the block also contains a yield statement). + + return returnNode; + } + + // import_from: ('from' (('.' | '...')* dotted_name | ('.' | '...')+) + // 'import' ('*' | '(' import_as_names ')' | import_as_names)) + // import_as_names: import_as_name (',' import_as_name)* [','] + // import_as_name: NAME ['as' NAME] + private _parseFromStatement(): ImportFromNode { + let fromToken = this._getKeywordToken(KeywordType.From); + + let modName = this._parseDottedModuleName(true); + let importFromNode = new ImportFromNode(fromToken, modName); + + if (!this._consumeTokenIfKeyword(KeywordType.Import)) { + this._addError('Expected "import"', this._peekToken()); + } else { + // Look for "*" token. + if (!this._consumeTokenIfOperator(OperatorType.Multiply)) { + let inParen = this._consumeTokenIfType(TokenType.OpenParenthesis); + + while (true) { + let importName = this._getTokenIfIdentifier(); + if (importName) { + let importFromAsNode = new ImportFromAsNode(new NameNode(importName)); + + if (this._consumeTokenIfKeyword(KeywordType.As)) { + let aliasName = this._getTokenIfIdentifier(); + if (!aliasName) { + this._addError('Expected alias symbol name', this._peekToken()); + } else { + importFromAsNode.alias = new NameNode(aliasName); + importFromAsNode.extend(aliasName); + } + } + + importFromNode.imports.push(importFromAsNode); + importFromNode.extend(importFromAsNode); + } + + if (!this._consumeTokenIfType(TokenType.Comma)) { + break; + } + } + + if (importFromNode.imports.length === 0) { + this._addError('Expected imported symbol name', this._peekToken()); + } + + if (inParen) { + let nextToken = this._peekToken(); + if (!this._consumeTokenIfType(TokenType.CloseParenthesis)) { + this._addError('Expected ")"', this._peekToken()); + } else { + importFromNode.extend(nextToken); + } + } + } + } + + // TODO - need to process __future__ imports + + return importFromNode; + } + + // import_name: 'import' dotted_as_names + // dotted_as_names: dotted_as_name (',' dotted_as_name)* + // dotted_as_name: dotted_name ['as' NAME] + private _parseImportStatement(): ImportNode { + let importToken = this._getKeywordToken(KeywordType.Import); + + let importNode = new ImportNode(importToken); + + while (true) { + let modName = this._parseDottedModuleName(); + let importAsNode = new ImportAsNode(modName); + + if (this._consumeTokenIfKeyword(KeywordType.As)) { + let aliasToken = this._getTokenIfIdentifier(); + if (aliasToken) { + importAsNode.alias = new NameNode(aliasToken); + importAsNode.extend(importAsNode.alias); + } else { + this._addError('Expected identifier after "as"', this._peekToken()); + } + } + + importNode.list.push(importAsNode); + + if (!this._consumeTokenIfType(TokenType.Comma)) { + break; + } + } + + importNode.extend(importNode.list); + + return importNode; + } + + // ('.' | '...')* dotted_name | ('.' | '...')+ + // dotted_name: NAME ('.' NAME)* + private _parseDottedModuleName(allowJustDots = false): ModuleNameNode { + let moduleNameNode = new ModuleNameNode(this._peekToken()); + + while (true) { + if (this._consumeTokenIfType(TokenType.Ellipsis)) { + moduleNameNode.leadingDots += 3; + } else if (this._consumeTokenIfType(TokenType.Dot)) { + moduleNameNode.leadingDots++; + } else { + break; + } + } + + while (true) { + let identifier = this._getTokenIfIdentifier([KeywordType.Import]); + if (!identifier) { + if (!allowJustDots || moduleNameNode.leadingDots === 0) { + this._addError('Expected module name', this._peekToken()); + } + break; + } + + moduleNameNode.nameParts.push(new NameNode(identifier)); + moduleNameNode.extend(identifier); + + if (!this._consumeTokenIfType(TokenType.Dot)) { + break; + } + } + + return moduleNameNode; + } + + private _parseGlobalStatement(): GlobalNode { + let globalToken = this._getKeywordToken(KeywordType.Global); + + let globalNode = new GlobalNode(globalToken); + globalNode.nameList = this._parseNameList(); + globalNode.extend(globalNode.nameList); + return globalNode; + } + + private _parseNonlocalStatement(): NonlocalNode { + let nonlocalToken = this._getKeywordToken(KeywordType.Nonlocal); + + let nonlocalNode = new NonlocalNode(nonlocalToken); + nonlocalNode.nameList = this._parseNameList(); + nonlocalNode.extend(nonlocalNode.nameList); + return nonlocalNode; + } + + private _parseNameList(): NameNode[] { + let nameList: NameNode[] = []; + + while (true) { + let name = this._getTokenIfIdentifier(); + if (!name) { + this._addError('Expected identifier', this._peekToken()); + break; + } + + nameList.push(new NameNode(name)); + + if (!this._consumeTokenIfType(TokenType.Comma)) { + break; + } + } + + return nameList; + } + + // raise_stmt: 'raise' [test ['from' test]] + // (old) raise_stmt: 'raise' [test [',' test [',' test]]] + private _parseRaiseStatement(): RaiseNode { + let raiseToken = this._getKeywordToken(KeywordType.Raise); + + let raiseNode = new RaiseNode(raiseToken); + if (!this._isNextTokenNeverExpression()) { + raiseNode.typeExpression = this._parseTestExpression(); + raiseNode.extend(raiseNode.typeExpression); + + if (this._consumeTokenIfKeyword(KeywordType.From)) { + raiseNode.valueExpression = this._parseTestExpression(); + raiseNode.extend(raiseNode.valueExpression); + } else { + if (this._consumeTokenIfType(TokenType.Comma)) { + // Handle the Python 2.x variant + raiseNode.valueExpression = this._parseTestExpression(); + raiseNode.extend(raiseNode.valueExpression); + + if (this._consumeTokenIfType(TokenType.Comma)) { + raiseNode.tracebackExpression = this._parseTestExpression(); + raiseNode.extend(raiseNode.tracebackExpression); + } + } + } + } + + return raiseNode; + } + + // assert_stmt: 'assert' test [',' test] + private _parseAssertStatement(): AssertNode { + let assertToken = this._getKeywordToken(KeywordType.Assert); + + let assertNode = new AssertNode(assertToken); + + while (true) { + let expr = this._parseTestExpression(); + assertNode.expressions.push(expr); + + if (!this._consumeTokenIfType(TokenType.Comma)) { + break; + } + } + + assertNode.extend(assertNode.expressions); + return assertNode; + } + + // del_stmt: 'del' exprlist + private _parseDelStatement(): DelNode { + let delToken = this._getKeywordToken(KeywordType.Del); + + let exprListResult = this._parseExpressionList(true); + if (!exprListResult.parseError && exprListResult.list.length === 0) { + this._addError('Expected expression after "del"', this._peekToken()); + } + let delNode = new DelNode(delToken); + delNode.expressions = exprListResult.list; + delNode.extend(delNode.expressions); + return delNode; + } + + // yield_expr: 'yield' [yield_arg] + // yield_arg: 'from' test | testlist + private _parseYieldExpression(): YieldExpressionNode | YieldFromExpressionNode { + let yieldToken = this._getKeywordToken(KeywordType.Yield); + + if (this._consumeTokenIfKeyword(KeywordType.From)) { + return new YieldFromExpressionNode(yieldToken, this._parseTestExpression()); + } + + let exprListResult = this._parseTestExpressionList(); + let exprList = this._makeExpressionOrTuple(exprListResult); + + return new YieldExpressionNode(yieldToken, exprList); + } + + private _tryParseYieldExpression(): YieldExpressionNode | YieldFromExpressionNode | undefined { + if (this._peekKeywordType() !== KeywordType.Yield) { + return undefined; + } + + return this._parseYieldExpression(); + } + + // simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE + private _parseSimpleStatement(): StatementListNode { + let statement = new StatementListNode(this._peekToken()); + + while (true) { + // Swallow invalid tokens to make sure we make forward progress. + if (this._peekTokenType() === TokenType.Invalid) { + const invalidToken = this._getNextToken(); + const text = this._fileContents!.substr(invalidToken.start, invalidToken.length); + this._addError(`Invalid token: "${ text }"`, invalidToken); + this._consumeTokensUntilType(TokenType.NewLine); + break; + } + + let smallStatement = this._parseSmallStatement(); + statement.statements.push(smallStatement); + statement.extend(smallStatement); + + if (smallStatement instanceof ErrorExpressionNode) { + // No need to log an error here. We assume that + // it was already logged by _parseSmallStatement. + break; + } + + // Consume the semicolon if present. + if (!this._consumeTokenIfType(TokenType.Semicolon)) { + break; + } + + let nextTokenType = this._peekTokenType(); + if (nextTokenType === TokenType.NewLine || nextTokenType === TokenType.EndOfStream) { + break; + } + } + + if (!this._consumeTokenIfType(TokenType.NewLine)) { + this._addError('Statements must be separated by newlines or semicolons', + this._peekToken()); + } + + return statement; + } + + // small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt | + // import_stmt | global_stmt | nonlocal_stmt | assert_stmt) + // flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt + // import_stmt: import_name | import_from + private _parseSmallStatement(): ParseNode { + switch (this._peekKeywordType()) { + case KeywordType.Pass: + return this._parsePassStatement(); + + case KeywordType.Break: + return this._parseBreakStatement(); + + case KeywordType.Continue: + return this._parseContinueStatement(); + + case KeywordType.Return: + return this._parseReturnStatement(); + + case KeywordType.From: + return this._parseFromStatement(); + + case KeywordType.Import: + return this._parseImportStatement(); + + case KeywordType.Global: + return this._parseGlobalStatement(); + + case KeywordType.Nonlocal: + return this._parseNonlocalStatement(); + + case KeywordType.Raise: + return this._parseRaiseStatement(); + + case KeywordType.Assert: + return this._parseAssertStatement(); + + case KeywordType.Del: + return this._parseDelStatement(); + + case KeywordType.Yield: + return this._parseYieldExpression(); + } + + return this._parseExpressionStatement(); + } + + private _makeExpressionOrTuple(exprListResult: ExpressionListResult): ExpressionNode { + if (exprListResult.list.length === 1 && !exprListResult.trailingComma) { + return exprListResult.list[0]; + } + + // To accommodate empty tuples ("()"), we will reach back to get + // the opening parenthesis as the opening token. + + let tupleStartRange: TextRange = exprListResult.list.length > 0 ? + exprListResult.list[0] : this._peekToken(-1); + + let tupleNode = new TupleExpressionNode(tupleStartRange); + tupleNode.expressions = exprListResult.list; + tupleNode.extend(exprListResult.list); + + return tupleNode; + } + + private _parseTestListAsExpression(errorString: string): ExpressionNode { + if (this._isNextTokenNeverExpression()) { + return this._handleExpressionParseError(errorString); + } + + let exprListResult = this._parseTestExpressionList(); + if (exprListResult.parseError) { + return exprListResult.parseError; + } + return this._makeExpressionOrTuple(exprListResult); + } + + private _parseTestOrStarListAsExpression(): ExpressionNode { + if (this._isNextTokenNeverExpression()) { + return this._handleExpressionParseError('Expected expression'); + } + + let exprListResult = this._parseTestOrStarExpressionList(); + if (exprListResult.parseError) { + return exprListResult.parseError; + } + return this._makeExpressionOrTuple(exprListResult); + } + + private _parseExpressionList(allowStar: boolean): ExpressionListResult { + return this._parseExpressionListGeneric(() => this._parseExpression(allowStar)); + } + + // testlist: test (',' test)* [','] + private _parseTestExpressionList(): ExpressionListResult { + return this._parseExpressionListGeneric(() => this._parseTestExpression()); + } + + private _parseTestOrStarExpressionList(): ExpressionListResult { + let exprListResult = this._parseExpressionListGeneric(() => this._parseTestOrStarExpression()); + + if (!exprListResult.parseError) { + // Make sure that we don't have more than one star expression in the list. + let sawStar = false; + for (let expr of exprListResult.list) { + if (expr instanceof StarExpressionNode) { + if (sawStar) { + this._addError('Only one starred expression allowed in list', expr); + break; + } + sawStar = true; + } + } + } + + return exprListResult; + } + + // exp_or_star: expr | star_expr + // expr: xor_expr ('|' xor_expr)* + // star_expr: '*' expr + private _parseExpression(allowStar: boolean): ExpressionNode { + let startToken = this._peekToken(); + + if (allowStar && this._consumeTokenIfOperator(OperatorType.Multiply)) { + return new StarExpressionNode(startToken, this._parseExpression(false)); + } + + return this._parseBitwiseOrExpression(); + } + + // test_or_star: test | star_expr + private _parseTestOrStarExpression(): ExpressionNode { + if (this._peekOperatorType() === OperatorType.Multiply) { + return this._parseExpression(true); + } + + return this._parseTestExpression(); + } + + // test: or_test ['if' or_test 'else' test] | lambdef + private _parseTestExpression(): ExpressionNode { + if (this._peekKeywordType() === KeywordType.Lambda) { + return this._parseLambdaExpression(); + } + + let leftExpr = this._parseOrTest(); + if (leftExpr instanceof ErrorExpressionNode) { + return leftExpr; + } + + if (!this._consumeTokenIfKeyword(KeywordType.If)) { + return leftExpr; + } + + let ifExpr = this._parseOrTest(); + if (ifExpr instanceof ErrorExpressionNode) { + return ifExpr; + } + + if (!this._consumeTokenIfKeyword(KeywordType.Else)) { + return this._handleExpressionParseError('Expected "else"'); + } + + let elseExpr = this._parseTestExpression(); + if (elseExpr instanceof ErrorExpressionNode) { + return elseExpr; + } + + return new ConditionalExpressionNode(leftExpr, ifExpr, elseExpr); + } + + // or_test: and_test ('or' and_test)* + private _parseOrTest(): ExpressionNode { + let leftExpr = this._parseAndTest(); + if (leftExpr instanceof ErrorExpressionNode) { + return leftExpr; + } + + if (this._consumeTokenIfKeyword(KeywordType.Or)) { + let rightExpr = this._parseOrTest(); + + return new BinaryExpressionNode(leftExpr, rightExpr, OperatorType.Or); + } + + return leftExpr; + } + + // and_test: not_test ('and' not_test)* + private _parseAndTest(): ExpressionNode { + let leftExpr = this._parseNotTest(); + if (leftExpr instanceof ErrorExpressionNode) { + return leftExpr; + } + + if (this._consumeTokenIfKeyword(KeywordType.And)) { + let rightExpr = this._parseAndTest(); + return new BinaryExpressionNode(leftExpr, rightExpr, OperatorType.And); + } + + return leftExpr; + } + + // not_test: 'not' not_test | comparison + private _parseNotTest(): ExpressionNode { + if (this._consumeTokenIfKeyword(KeywordType.Not)) { + let notExpr = this._parseNotTest(); + return new UnaryExpressionNode(notExpr, OperatorType.Not); + } + + return this._parseComparison(); + } + + // comparison: expr (comp_op expr)* + // comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' + private _parseComparison(): ExpressionNode { + let leftExpr = this._parseBitwiseOrExpression(); + if (leftExpr instanceof ErrorExpressionNode) { + return leftExpr; + } + + let comparisonOperator: OperatorType | undefined; + + if (Tokenizer.isOperatorComparison(this._peekOperatorType())) { + comparisonOperator = this._peekOperatorType(); + this._getNextToken(); + } else if (this._consumeTokenIfKeyword(KeywordType.In)) { + comparisonOperator = OperatorType.In; + } else if (this._consumeTokenIfKeyword(KeywordType.Is)) { + if (this._consumeTokenIfKeyword(KeywordType.Not)) { + comparisonOperator = OperatorType.IsNot; + } else { + comparisonOperator = OperatorType.Is; + } + } else if (this._peekKeywordType() === KeywordType.Not) { + let tokenAfterNot = this._peekToken(1); + if (tokenAfterNot.type === TokenType.Keyword && + (tokenAfterNot as KeywordToken).keywordType === KeywordType.In) { + this._getNextToken(); + this._getNextToken(); + comparisonOperator = OperatorType.NotIn; + } + } + + if (comparisonOperator !== undefined) { + let rightExpr = this._parseComparison(); + return new BinaryExpressionNode(leftExpr, rightExpr, comparisonOperator); + } + + return leftExpr; + } + + // expr: xor_expr ('|' xor_expr)* + private _parseBitwiseOrExpression(): ExpressionNode { + let leftExpr = this._parseExclusiveOrExpression(); + if (leftExpr instanceof ErrorExpressionNode) { + return leftExpr; + } + + if (this._consumeTokenIfOperator(OperatorType.BitwiseOr)) { + let rightExpr = this._parseBitwiseOrExpression(); + return new BinaryExpressionNode(leftExpr, rightExpr, OperatorType.BitwiseOr); + } + + return leftExpr; + } + + // xor_expr: and_expr ('^' and_expr)* + private _parseExclusiveOrExpression(): ExpressionNode { + let leftExpr = this._parseBitwiseAndExpression(); + if (leftExpr instanceof ErrorExpressionNode) { + return leftExpr; + } + + if (this._consumeTokenIfOperator(OperatorType.ExclusiveOr)) { + let rightExpr = this._parseExclusiveOrExpression(); + return new BinaryExpressionNode(leftExpr, rightExpr, OperatorType.ExclusiveOr); + } + + return leftExpr; + } + + // and_expr: shift_expr ('&' shift_expr)* + private _parseBitwiseAndExpression(): ExpressionNode { + let leftExpr = this._parseShiftExpression(); + if (leftExpr instanceof ErrorExpressionNode) { + return leftExpr; + } + + if (this._consumeTokenIfOperator(OperatorType.BitwiseAnd)) { + let rightExpr = this._parseBitwiseAndExpression(); + return new BinaryExpressionNode(leftExpr, rightExpr, OperatorType.BitwiseAnd); + } + + return leftExpr; + } + + // shift_expr: arith_expr (('<<'|'>>') arith_expr)* + private _parseShiftExpression(): ExpressionNode { + let leftExpr = this._parseAirthmeticExpression(); + if (leftExpr instanceof ErrorExpressionNode) { + return leftExpr; + } + + let nextOperator = this._peekOperatorType(); + if (nextOperator === OperatorType.LeftShift || nextOperator === OperatorType.RightShift) { + this._getNextToken(); + let rightExpr = this._parseShiftExpression(); + return new BinaryExpressionNode(leftExpr, rightExpr, nextOperator); + } + + return leftExpr; + } + + // arith_expr: term (('+'|'-') term)* + private _parseAirthmeticExpression(): ExpressionNode { + let leftExpr = this._parseAirthmeticTerm(); + if (leftExpr instanceof ErrorExpressionNode) { + return leftExpr; + } + + let nextOperator = this._peekOperatorType(); + if (nextOperator === OperatorType.Add || nextOperator === OperatorType.Subtract) { + this._getNextToken(); + let rightExpr = this._parseAirthmeticExpression(); + if (rightExpr instanceof ErrorExpressionNode) { + return rightExpr; + } + + return new BinaryExpressionNode(leftExpr, rightExpr, nextOperator); + } + + return leftExpr; + } + + // term: factor (('*'|'@'|'/'|'%'|'//') factor)* + private _parseAirthmeticTerm(): ExpressionNode { + let leftExpr = this._parseAirthmeticFactor(); + if (leftExpr instanceof ErrorExpressionNode) { + return leftExpr; + } + + let nextOperator = this._peekOperatorType(); + if (nextOperator === OperatorType.Multiply || + nextOperator === OperatorType.MatrixMultiply || + nextOperator === OperatorType.Divide || + nextOperator === OperatorType.Mod || + nextOperator === OperatorType.FloorDivide) { + this._getNextToken(); + let rightExpr = this._parseAirthmeticTerm(); + return new BinaryExpressionNode(leftExpr, rightExpr, nextOperator); + } + + return leftExpr; + } + + // factor: ('+'|'-'|'~') factor | power + // power: atom_expr ['**' factor] + private _parseAirthmeticFactor(): ExpressionNode { + let nextOperator = this._peekOperatorType(); + if (nextOperator === OperatorType.Add || + nextOperator === OperatorType.Subtract || + nextOperator === OperatorType.BitwiseInvert) { + this._getNextToken(); + let expression = this._parseAirthmeticFactor(); + return new UnaryExpressionNode(expression, nextOperator); + } + + let leftExpr = this._parseAtomExpression(); + if (leftExpr instanceof ErrorExpressionNode) { + return leftExpr; + } + + if (this._consumeTokenIfOperator(OperatorType.Power)) { + let rightExpr = this._parseAirthmeticFactor(); + return new BinaryExpressionNode(leftExpr, rightExpr, OperatorType.Power); + } + + return leftExpr; + } + + // atom_expr: ['await'] atom trailer* + // trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME + private _parseAtomExpression(): ExpressionNode { + let awaitToken: KeywordToken | undefined; + if (this._peekKeywordType() === KeywordType.Await) { + awaitToken = this._getKeywordToken(KeywordType.Await); + if (this._getLanguageVersion() < PythonVersion.V35) { + this._addError( + `Support for 'await' keyword requires Python 3.5 or newer`, + awaitToken); + } + } + + let atomExpression = this._parseAtom(); + if (atomExpression instanceof ErrorExpressionNode) { + return atomExpression; + } + + // Consume trailers. + while (true) { + // Is it a function call? + if (this._consumeTokenIfType(TokenType.OpenParenthesis)) { + let argList = this._parseArgList(); + let callNode = new CallExpressionNode(atomExpression); + callNode.arguments = argList; + callNode.extend(argList); + + let nextToken = this._peekToken(); + if (!this._consumeTokenIfType(TokenType.CloseParenthesis)) { + return this._handleExpressionParseError('Expected ")"'); + } else { + callNode.extend(nextToken); + } + + atomExpression = callNode; + } else if (this._consumeTokenIfType(TokenType.OpenBracket)) { + // Is it an index operator? + let indexExpr = this._parseSubscriptList(); + let indexNode = new IndexExpressionNode(atomExpression, indexExpr); + indexNode.extend(indexNode); + + let nextToken = this._peekToken(); + if (!this._consumeTokenIfType(TokenType.CloseBracket)) { + return this._handleExpressionParseError('Expected "]"'); + } else { + indexNode.extend(nextToken); + } + + atomExpression = indexNode; + } else if (this._consumeTokenIfType(TokenType.Dot)) { + // Is it a member access? + let memberName = this._getTokenIfIdentifier(); + if (!memberName) { + return this._handleExpressionParseError('Expected member name after "."'); + } + atomExpression = new MemberAccessExpressionNode( + atomExpression, new NameNode(memberName)); + } else { + break; + } + } + + if (awaitToken) { + return new AwaitExpressionNode(awaitToken, atomExpression); + } + + return atomExpression; + } + + // subscriptlist: subscript (',' subscript)* [','] + private _parseSubscriptList(): ExpressionNode { + let listResult = this._parseExpressionListGeneric(() => this._parseSubscript(), () => { + // Override the normal terminal check to exclude colons, + // which are a valid way to start subscription expressions. + if (this._peekTokenType() === TokenType.Colon) { + return false; + } + return this._isNextTokenNeverExpression(); + }); + + if (listResult.parseError) { + return listResult.parseError; + } + + if (listResult.list.length === 0) { + return this._handleExpressionParseError('Expected index or slice expression'); + } + + return this._makeExpressionOrTuple(listResult); + } + + // subscript: test | [test] ':' [test] [sliceop] + // sliceop: ':' [test] + private _parseSubscript(): ExpressionNode { + let firstToken = this._peekToken(); + let sliceExpressions: (ExpressionNode | undefined)[] = [undefined, undefined, undefined]; + let sliceIndex = 0; + let sawColon = false; + + while (true) { + let nextTokenType = this._peekTokenType(); + if (nextTokenType === TokenType.CloseBracket || + nextTokenType === TokenType.Comma) { + break; + } + + if (nextTokenType !== TokenType.Colon) { + sliceExpressions[sliceIndex] = this._parseTestExpression(); + } + sliceIndex++; + + if (sliceIndex >= 3 || !this._consumeTokenIfType(TokenType.Colon)) { + break; + } + sawColon = true; + } + + // If this was a simple expression with no colons return it. + if (!sawColon) { + return sliceExpressions[0]!; + } + + let sliceNode = new SliceExpressionNode(firstToken); + sliceNode.startValue = sliceExpressions[0]; + sliceNode.endValue = sliceExpressions[1]; + sliceNode.stepValue = sliceExpressions[2]; + sliceNode.extend(sliceExpressions[2] || sliceExpressions[1] || sliceExpressions[0]); + + return sliceNode; + } + + // arglist: argument (',' argument)* [','] + private _parseArgList(): ArgumentNode[] { + let argList: ArgumentNode[] = []; + let sawKeywordArg = false; + + while (true) { + let nextTokenType = this._peekTokenType(); + if (nextTokenType === TokenType.CloseParenthesis || + nextTokenType === TokenType.NewLine || + nextTokenType === TokenType.EndOfStream) { + break; + } + + let arg = this._parseArgument(); + if (arg.name) { + sawKeywordArg = true; + } else if (sawKeywordArg && arg.argumentCategory === ArgumentCategory.Simple) { + this._addError( + 'Positional argument cannot appear after named arguments', + arg); + } + argList.push(arg); + + if (!this._consumeTokenIfType(TokenType.Comma)) { + break; + } + } + + return argList; + } + + // argument: ( test [comp_for] | + // test '=' test | + // '**' test | + // '*' test ) + private _parseArgument(): ArgumentNode { + let firstToken = this._peekToken(); + + let argType = ArgumentCategory.Simple; + if (this._consumeTokenIfOperator(OperatorType.Multiply)) { + argType = ArgumentCategory.List; + } else if (this._consumeTokenIfOperator(OperatorType.Power)) { + argType = ArgumentCategory.Dictionary; + } + + let valueExpr = this._parseTestExpression(); + let nameIdentifier: IdentifierToken | undefined; + + if (argType === ArgumentCategory.Simple) { + if (this._consumeTokenIfOperator(OperatorType.Assign)) { + let nameExpr = valueExpr; + valueExpr = this._parseTestExpression(); + + if (nameExpr instanceof NameNode) { + nameIdentifier = nameExpr.nameToken; + } else { + this._addError('Expected parameter name', nameExpr); + } + } else { + let listComp = this._tryParseListComprehension(valueExpr); + if (listComp) { + valueExpr = listComp; + } + } + } + + let argNode = new ArgumentNode(firstToken, valueExpr, argType); + if (nameIdentifier) { + argNode.name = new NameNode(nameIdentifier); + } + + return argNode; + } + + // atom: ('(' [yield_expr | testlist_comp] ')' | + // '[' [testlist_comp] ']' | + // '{' [dictorsetmaker] '}' | + // NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False' | '__debug__') + private _parseAtom(): ExpressionNode { + let nextToken = this._peekToken(); + + if (nextToken.type === TokenType.Ellipsis) { + return new EllipsisNode(this._getNextToken()); + } + + if (nextToken.type === TokenType.Number) { + return new NumberNode(this._getNextToken() as NumberToken); + } + + if (nextToken.type === TokenType.Identifier) { + return new NameNode(this._getNextToken() as IdentifierToken); + } + + if (nextToken.type === TokenType.String) { + let stringTokenList: StringToken[] = []; + + while (this._peekTokenType() === TokenType.String) { + stringTokenList.push(this._getNextToken() as StringToken); + } + + return new StringNode(stringTokenList); + } + + if (nextToken.type === TokenType.OpenParenthesis) { + return this._parseTupleAtom(); + } else if (nextToken.type === TokenType.OpenBracket) { + return this._parseListAtom(); + } else if (nextToken.type === TokenType.OpenCurlyBrace) { + return this._parseDictionaryOrSetAtom(); + } + + if (nextToken.type === TokenType.Keyword) { + let keywordToken = nextToken as KeywordToken; + if (keywordToken.keywordType === KeywordType.False || + keywordToken.keywordType === KeywordType.True || + keywordToken.keywordType === KeywordType.Debug || + keywordToken.keywordType === KeywordType.None) { + return new ConstantNode(this._getNextToken() as KeywordToken); + } + + // Make an identifier out of the keyword. + let keywordAsIdentifier = this._getTokenIfIdentifier(); + if (keywordAsIdentifier) { + return new NameNode(keywordAsIdentifier); + } + } + + return this._handleExpressionParseError('Expected expression'); + } + + // Allocates a dummy "error expression" and consumes the remainder + // of the tokens on the line for error recovery. + private _handleExpressionParseError(errorMsg: string): ErrorExpressionNode { + this._addError(errorMsg, this._peekToken()); + let expr = new ErrorExpressionNode(this._peekToken()); + this._consumeTokensUntilType(TokenType.NewLine); + return expr; + } + + // lambdef: 'lambda' [varargslist] ':' test + private _parseLambdaExpression(allowConditional = true): LambdaNode { + let labmdaToken = this._getKeywordToken(KeywordType.Lambda); + + let argList = this._parseVarArgsList(TokenType.Colon, false); + + if (!this._consumeTokenIfType(TokenType.Colon)) { + this._addError('Expected ":"', this._peekToken()); + } + + let testExpr: ExpressionNode; + if (allowConditional) { + testExpr = this._parseTestExpression(); + } else { + testExpr = this._tryParseLambdaExpression(false) || this._parseOrTest(); + } + + let lambdaNode = new LambdaNode(labmdaToken, testExpr); + lambdaNode.parameters = argList; + return lambdaNode; + } + + private _tryParseLambdaExpression(allowConditional = true): LambdaNode | undefined { + if (this._peekKeywordType() !== KeywordType.Lambda) { + return undefined; + } + + return this._parseLambdaExpression(allowConditional); + } + + // ('(' [yield_expr | testlist_comp] ')' + // testlist_comp: (test | star_expr) (comp_for | (',' (test | star_expr))* [',']) + private _parseTupleAtom(): ExpressionNode { + let startParen = this._getNextToken(); + assert.equal(startParen.type, TokenType.OpenParenthesis); + + let yieldExpr = this._tryParseYieldExpression(); + if (yieldExpr) { + if (this._peekTokenType() !== TokenType.CloseParenthesis) { + return this._handleExpressionParseError('Expected ")"'); + } else { + yieldExpr.extend(this._getNextToken()); + } + + return yieldExpr; + } + + let exprListResult = this._parseTestListWithComprehension(); + let tupleOrExpression = this._makeExpressionOrTuple(exprListResult); + + if (this._peekTokenType() !== TokenType.CloseParenthesis) { + return this._handleExpressionParseError('Expected ")"'); + } else { + tupleOrExpression.extend(this._getNextToken()); + } + + return tupleOrExpression; + } + + // '[' [testlist_comp] ']' + // testlist_comp: (test | star_expr) (comp_for | (',' (test | star_expr))* [',']) + private _parseListAtom(): ListNode | ErrorExpressionNode { + let startBracket = this._getNextToken(); + assert.equal(startBracket.type, TokenType.OpenBracket); + + let exprListResult = this._parseTestListWithComprehension(); + let closeBracket: Token | undefined = this._peekToken(); + if (!this._consumeTokenIfType(TokenType.CloseBracket)) { + return this._handleExpressionParseError('Expected "]"'); + } + + let listAtom = new ListNode(startBracket); + listAtom.extend(closeBracket); + listAtom.extend(exprListResult.list); + listAtom.entries = exprListResult.list; + return listAtom; + } + + private _parseTestListWithComprehension(): ExpressionListResult { + let sawComprehension = false; + + return this._parseExpressionListGeneric(() => { + let expr = this._parseTestOrStarExpression(); + let listComp = this._tryParseListComprehension(expr); + if (listComp) { + expr = listComp; + sawComprehension = true; + } + return expr; + }, + () => this._isNextTokenNeverExpression(), + () => sawComprehension); + } + + // '{' [dictorsetmaker] '}' + // dictorsetmaker: ( + // (dictentry (comp_for | (',' dictentry)* [','])) + // | (setentry (comp_for | (',' setentry)* [','])) + // ) + // dictentry: (test ':' test | '**' expr) + // setentry: test | star_expr + private _parseDictionaryOrSetAtom(): DictionaryNode | SetNode { + let startBrace = this._getNextToken(); + assert.equal(startBrace.type, TokenType.OpenCurlyBrace); + + let dictionaryEntries: DictionaryEntryNode[] = []; + let setEntries: ExpressionNode[] = []; + let isDictionary = false; + let isSet = false; + let sawListComprehension = false; + + while (true) { + if (this._peekTokenType() === TokenType.CloseCurlyBrace) { + break; + } + + let doubleStarExpression: ExpressionNode | undefined; + let keyExpression: ExpressionNode | undefined; + let valueExpression: ExpressionNode | undefined; + + if (this._consumeTokenIfOperator(OperatorType.Power)) { + doubleStarExpression = this._parseExpression(false); + } else { + keyExpression = this._parseTestOrStarExpression(); + + if (this._consumeTokenIfType(TokenType.Colon)) { + valueExpression = this._parseTestExpression(); + } + } + + if (keyExpression && valueExpression) { + if (keyExpression instanceof StarExpressionNode) { + this._addError('Star expressions not allowed in dictionaries', keyExpression); + } + + if (isSet) { + this._addError('Key/value pairs are not allowed within a set', valueExpression); + } else { + let dictEntry: DictionaryEntryNode = new DictionaryKeyEntryNode(keyExpression, valueExpression); + let listComp = this._tryParseListComprehension(dictEntry); + if (listComp) { + dictEntry = listComp; + sawListComprehension = true; + } + dictionaryEntries.push(dictEntry); + isDictionary = true; + } + } else if (doubleStarExpression) { + if (isSet) { + this._addError('Unpack operator not allowed within a set', doubleStarExpression); + } else { + let expandEntryNode: ExpressionNode = new DictionaryExpandEntryNode(doubleStarExpression); + let listComp = this._tryParseListComprehension(expandEntryNode); + if (listComp) { + expandEntryNode = listComp; + sawListComprehension = true; + } + dictionaryEntries.push(); + isDictionary = true; + } + } else { + assert(keyExpression !== undefined); + if (keyExpression) { + if (isDictionary) { + this._addError('Dictionary entries must contain key/value pairs', keyExpression); + } else { + let listComp = this._tryParseListComprehension(keyExpression); + if (listComp) { + keyExpression = listComp; + sawListComprehension = true; + } + setEntries.push(keyExpression); + isSet = true; + } + } + } + + // List comprehension statements always end the list. + if (sawListComprehension) { + break; + } + + if (!this._consumeTokenIfType(TokenType.Comma)) { + break; + } + } + + let closeCurlyBrace: Token | undefined = this._peekToken(); + if (!this._consumeTokenIfType(TokenType.CloseCurlyBrace)) { + this._addError('Expected "}"', this._peekToken()); + closeCurlyBrace = undefined; + } + + if (isSet) { + let setAtom = new SetNode(startBrace); + setAtom.extend(closeCurlyBrace); + setAtom.extend(setEntries); + setAtom.entries = setEntries; + return setAtom; + } + + let dictionaryAtom = new DictionaryNode(startBrace); + dictionaryAtom.extend(closeCurlyBrace); + dictionaryAtom.extend(dictionaryEntries); + dictionaryAtom.entries = dictionaryEntries; + return dictionaryAtom; + } + + private _parseExpressionListGeneric(parser: () => ExpressionNode, + teminalCheck: () => boolean = () => this._isNextTokenNeverExpression(), + finalEntryCheck: () => boolean = () => false): + ExpressionListResult { + let trailingComma = false; + let list: ExpressionNode[] = []; + let parseError: ErrorExpressionNode | undefined; + + while (true) { + if (teminalCheck()) { + break; + } + + let expr = parser(); + if (expr instanceof ErrorExpressionNode) { + parseError = expr; + break; + } + list.push(expr); + + // Should we stop without checking for a trailing comma? + if (finalEntryCheck()) { + break; + } + + if (!this._consumeTokenIfType(TokenType.Comma)) { + trailingComma = false; + break; + } + + trailingComma = true; + } + + return { trailingComma, list, parseError }; + } + + // expr_stmt: testlist_star_expr (annassign | augassign (yield_expr | testlist) | + // ('=' (yield_expr | testlist_star_expr))*) + // testlist_star_expr: (test|star_expr) (',' (test|star_expr))* [','] + // annassign: ':' test ['=' test] + // augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' | + // '<<=' | '>>=' | '**=' | '//=') + private _parseExpressionStatement(): ExpressionNode { + let leftExpr = this._parseTestOrStarListAsExpression(); + let annotationExpr: TypeAnnotationExpression | undefined; + + if (leftExpr instanceof ErrorExpressionNode) { + return leftExpr; + } + + // Is this a type annotation assignment? + if (this._consumeTokenIfType(TokenType.Colon)) { + annotationExpr = this._parseTypeAnnotation(this._parseTestExpression()); + leftExpr = new TypeAnnotationExpressionNode(leftExpr, annotationExpr); + + if (!this._consumeTokenIfOperator(OperatorType.Assign)) { + return leftExpr; + } + + if (!this._parseOptions.isStubFile && this._getLanguageVersion() < PythonVersion.V36) { + this._addError('Type annotations for variables requires Python 3.6 or newer', + annotationExpr.rawExpression); + } + + let rightExpr = this._parseTestExpression(); + return new AssignmentNode(leftExpr, rightExpr); + } + + // Is this a simple assignment? + if (this._consumeTokenIfOperator(OperatorType.Assign)) { + return this._parseChainAssignments(leftExpr); + } + + if (!annotationExpr && Tokenizer.isOperatorAssignment(this._peekOperatorType())) { + let operatorToken = this._getNextToken() as OperatorToken; + + // Is the left side of the assignment assignable? + const assignError = leftExpr.getAssignmentError(); + if (assignError) { + this._addError(assignError, leftExpr); + } + + let rightExpr = this._tryParseYieldExpression() || + this._parseTestListAsExpression('Expected expression to the right of operator'); + return new AugmentedAssignemtnExpressionNode(leftExpr, rightExpr, operatorToken.operatorType); + } + + return leftExpr; + } + + private _parseChainAssignments(leftExpr: ExpressionNode): ExpressionNode { + // Is the left side of the assignment assignable? + const assignError = leftExpr.getAssignmentError(); + if (assignError) { + this._addError(assignError, leftExpr); + } + + let rightExpr: ExpressionNode | undefined; + rightExpr = this._tryParseYieldExpression(); + if (!rightExpr) { + rightExpr = this._parseTestListAsExpression('Expected expression to the right of "="'); + } + + if (rightExpr instanceof ErrorExpressionNode) { + return rightExpr; + } + + // Recurse until we've consumed the entire chain. + if (this._consumeTokenIfOperator(OperatorType.Assign)) { + rightExpr = this._parseChainAssignments(rightExpr); + if (rightExpr instanceof ErrorExpressionNode) { + return rightExpr; + } + } + + return new AssignmentNode(leftExpr, rightExpr); + } + + private _parseTypeAnnotation(node: ExpressionNode): TypeAnnotationExpression { + let rawExpression = node; + let parsedExpression = node; + + if (rawExpression instanceof StringNode) { + if (rawExpression.tokens.length > 1) { + this._addError('Type hints cannot span multiple string literals', node); + } else if (rawExpression.tokens[0].quoteTypeFlags & QuoteTypeFlags.Triplicate) { + this._addError('Type hints cannot use triple quotes', node); + } else if (rawExpression.tokens[0].quoteTypeFlags & + (QuoteTypeFlags.Raw | QuoteTypeFlags.Unicode | QuoteTypeFlags.Byte)) { + this._addError('Type hints cannot use raw, unicode or byte string literals', node); + } else if (rawExpression.tokens[0].value.length !== rawExpression.tokens[0].length - 2) { + this._addError('Type hints cannot contain escape characters', node); + } else { + let stringValue = rawExpression.tokens[0].value; + let tokenOffset = rawExpression.tokens[0].start; + let parser = new Parser(); + let parseResults = parser.parseTextExpression(this._fileContents!, + tokenOffset + 1, stringValue.length, this._parseOptions); + + parseResults.diagnostics.forEach(diag => { + this._addError(diag.message, node); + }); + + if (parseResults.parseTree) { + parsedExpression = parseResults.parseTree; + } + } + } + + return { + rawExpression, + expression: parsedExpression + }; + } + + // Peeks at the next token and returns true if it can never + // represent the start of an expression. + private _isNextTokenNeverExpression(): boolean { + let nextToken = this._peekToken(); + switch (nextToken.type) { + case TokenType.Keyword: { + switch (this._peekKeywordType()) { + case KeywordType.For: + case KeywordType.In: + case KeywordType.If: + return true; + } + break; + } + + case TokenType.Operator: { + switch (this._peekOperatorType()) { + case OperatorType.AddEqual: + case OperatorType.SubtractEqual: + case OperatorType.MultiplyEqual: + case OperatorType.DivideEqual: + case OperatorType.ModEqual: + case OperatorType.BitwiseAndEqual: + case OperatorType.BitwiseOrEqual: + case OperatorType.ExclusiveOrEqual: + case OperatorType.LeftShiftEqual: + case OperatorType.RightShiftEqual: + case OperatorType.PowerEqual: + case OperatorType.FloorDivideEqual: + case OperatorType.Assign: + return true; + } + break; + } + + case TokenType.Indent: + case TokenType.Dedent: + case TokenType.NewLine: + case TokenType.EndOfStream: + case TokenType.Semicolon: + case TokenType.CloseParenthesis: + case TokenType.CloseBracket: + case TokenType.CloseCurlyBrace: + case TokenType.Comma: + case TokenType.Colon: + return true; + } + + return false; + } + + private _checkCancel() { + if (this._cancelToken) { + this._cancelToken.throwIfCanceled(); + } + } + + private _getNextToken(): Token { + let token = this._tokenizerOutput!.tokens.getItemAt(this._tokenIndex); + if (!this._atEof()) { + this._tokenIndex++; + } + + return token; + } + + private _atEof(): boolean { + // Are we pointing at the last token in the stream (which is + // assumed to be an end-of-stream token)? + return this._tokenIndex >= this._tokenizerOutput!.tokens.count - 1; + } + + private _peekToken(count = 0): Token { + if (this._tokenIndex + count < 0) { + this._tokenizerOutput!.tokens.getItemAt(0); + } + + if (this._tokenIndex + count >= this._tokenizerOutput!.tokens.count) { + return this._tokenizerOutput!.tokens.getItemAt( + this._tokenizerOutput!.tokens.count - 1); + } + + return this._tokenizerOutput!.tokens.getItemAt(this._tokenIndex + count); + } + + private _peekTokenType(): TokenType { + return this._peekToken().type; + } + + private _peekKeywordType(): KeywordType | undefined { + let nextToken = this._peekToken(); + if (nextToken.type !== TokenType.Keyword) { + return undefined; + } + + return (nextToken as KeywordToken).keywordType; + } + + private _peekOperatorType(): OperatorType | undefined { + let nextToken = this._peekToken(); + if (nextToken.type !== TokenType.Operator) { + return undefined; + } + + return (nextToken as OperatorToken).operatorType; + } + + private _getTokenIfIdentifier(disallowedKeywords: KeywordType[] = []): IdentifierToken | undefined { + let nextToken = this._peekToken(); + if (nextToken.type === TokenType.Identifier) { + return this._getNextToken() as IdentifierToken; + } + + // If keywords are allowed in this context, convert the keyword + // to an identifier token. + if (nextToken.type === TokenType.Keyword) { + let keywordType = this._peekKeywordType(); + if (!disallowedKeywords.find(type => type === keywordType)) { + const keywordText = this._fileContents!.substring(nextToken.start, nextToken.end); + this._getNextToken(); + return new IdentifierToken(nextToken.start, nextToken.end, keywordText); + } + } + + return undefined; + } + + // Consumes tokens until the next one in the stream is + // either a specified terminator or the end-of-stream + // token. + private _consumeTokensUntilType(terminator: TokenType): boolean { + while (true) { + let token = this._peekToken(); + if (token.type === terminator) { + return true; + } + + if (token.type === TokenType.EndOfStream) { + return false; + } + + this._getNextToken(); + } + } + + private _consumeTokenIfType(tokenType: TokenType): boolean { + if (this._peekTokenType() === tokenType) { + this._getNextToken(); + return true; + } + + return false; + } + + private _consumeTokenIfKeyword(keywordType: KeywordType): boolean { + if (this._peekKeywordType() === keywordType) { + this._getNextToken(); + return true; + } + + return false; + } + + private _consumeTokenIfOperator(operatorType: OperatorType): boolean { + if (this._peekOperatorType() === operatorType) { + this._getNextToken(); + return true; + } + + return false; + } + + private _getKeywordToken(keywordType: KeywordType): KeywordToken { + let keywordToken = this._getNextToken() as KeywordToken; + assert(keywordToken.type === TokenType.Keyword); + assert.equal(keywordToken.keywordType, keywordType); + return keywordToken; + } + + private _getLanguageVersion() { + return this._parseOptions.pythonVersion; + } + + private _addError(message: string, range: TextRange) { + assert(range !== undefined); + this._diagSink.addError(message, + convertOffsetsToRange(range.start, range.end, this._tokenizerOutput!.lines)); + } +} diff --git a/server/src/parser/tokenizer.ts b/server/src/parser/tokenizer.ts new file mode 100644 index 000000000..a834c902c --- /dev/null +++ b/server/src/parser/tokenizer.ts @@ -0,0 +1,867 @@ +/* +* tokenizer.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Based on code from vscode-python repository: +* https://github.com/Microsoft/vscode-python +* +* Converts a Python program text stream into a stream of tokens. +*/ + +import Char from 'typescript-char'; + +import { TextRange } from '../common/textRange'; +import { TextRangeCollection } from '../common/textRangeCollection'; +import { isBinary, isDecimal, isHex, isIdentifierChar, isIdentifierStartChar, isOctal } from './characters'; +import { CharacterStream } from './characterStream'; +import { DedentToken, IdentifierToken, IndentToken, KeywordToken, KeywordType, + NewLineToken, NewLineType, NumberToken, OperatorFlags, OperatorToken, OperatorType, + QuoteTypeFlags, StringToken, Token, TokenType } from './tokenizerTypes'; + +const _keywords: { [key: string]: KeywordType } = { + 'and': KeywordType.And, + 'as': KeywordType.As, + 'assert': KeywordType.Assert, + 'async': KeywordType.Async, + 'await': KeywordType.Await, + 'break': KeywordType.Break, + 'class': KeywordType.Class, + 'continue': KeywordType.Continue, + '__debug__': KeywordType.Debug, + 'def': KeywordType.Def, + 'del': KeywordType.Del, + 'elif': KeywordType.Elif, + 'else': KeywordType.Else, + 'except': KeywordType.Except, + 'finally': KeywordType.Finally, + 'for': KeywordType.For, + 'from': KeywordType.From, + 'global': KeywordType.Global, + 'if': KeywordType.If, + 'import': KeywordType.Import, + 'in': KeywordType.In, + 'is': KeywordType.Is, + 'lambda': KeywordType.Lambda, + 'nonlocal': KeywordType.Nonlocal, + 'not': KeywordType.Not, + 'or': KeywordType.Or, + 'pass': KeywordType.Pass, + 'raise': KeywordType.Raise, + 'return': KeywordType.Return, + 'try': KeywordType.Try, + 'while': KeywordType.While, + 'with': KeywordType.With, + 'yield': KeywordType.Yield, + 'False': KeywordType.False, + 'None': KeywordType.None, + 'True': KeywordType.True +}; + +const _operatorInfo: { [key: number]: OperatorFlags } = { + [OperatorType.Add]: OperatorFlags.Unary | OperatorFlags.Binary, + [OperatorType.AddEqual]: OperatorFlags.Assignment, + [OperatorType.Assign]: OperatorFlags.Assignment, + [OperatorType.BitwiseAnd]: OperatorFlags.Binary, + [OperatorType.BitwiseAndEqual]: OperatorFlags.Assignment, + [OperatorType.BitwiseInvert]: OperatorFlags.Unary, + [OperatorType.BitwiseOr]: OperatorFlags.Binary, + [OperatorType.BitwiseOrEqual]: OperatorFlags.Assignment, + [OperatorType.Divide]: OperatorFlags.Binary, + [OperatorType.DivideEqual]: OperatorFlags.Assignment, + [OperatorType.Equals]: OperatorFlags.Binary | OperatorFlags.Comparison, + [OperatorType.ExclusiveOr]: OperatorFlags.Binary, + [OperatorType.ExclusiveOrEqual]: OperatorFlags.Assignment, + [OperatorType.FloorDivide]: OperatorFlags.Binary, + [OperatorType.FloorDivideEqual]: OperatorFlags.Assignment, + [OperatorType.GreaterThan]: OperatorFlags.Binary | OperatorFlags.Comparison, + [OperatorType.GreaterThanOrEqual]: OperatorFlags.Binary | OperatorFlags.Comparison, + [OperatorType.LeftShift]: OperatorFlags.Binary, + [OperatorType.LeftShiftEqual]: OperatorFlags.Assignment, + [OperatorType.LessThan]: OperatorFlags.Binary | OperatorFlags.Comparison, + [OperatorType.LessThanOrEqual]: OperatorFlags.Binary | OperatorFlags.Comparison, + [OperatorType.MatrixMultiply]: OperatorFlags.Binary, + [OperatorType.MatrixMultiplyEqual]: OperatorFlags.Assignment, + [OperatorType.Mod]: OperatorFlags.Binary, + [OperatorType.ModEqual]: OperatorFlags.Assignment, + [OperatorType.Multiply]: OperatorFlags.Binary, + [OperatorType.MultiplyEqual]: OperatorFlags.Assignment, + [OperatorType.NotEquals]: OperatorFlags.Binary | OperatorFlags.Comparison, + [OperatorType.Power]: OperatorFlags.Binary, + [OperatorType.PowerEqual]: OperatorFlags.Assignment, + [OperatorType.RightShift]: OperatorFlags.Binary, + [OperatorType.RightShiftEqual]: OperatorFlags.Assignment, + [OperatorType.Subtract]: OperatorFlags.Binary, + [OperatorType.SubtractEqual]: OperatorFlags.Assignment, + + [OperatorType.And]: OperatorFlags.Binary, + [OperatorType.Or]: OperatorFlags.Binary, + [OperatorType.Not]: OperatorFlags.Unary, + [OperatorType.Is]: OperatorFlags.Binary, + [OperatorType.IsNot]: OperatorFlags.Binary, + [OperatorType.In]: OperatorFlags.Binary, + [OperatorType.NotIn]: OperatorFlags.Binary +}; + +export interface TokenizerOutput { + tokens: TextRangeCollection; + lines: TextRangeCollection; +} + +export class Tokenizer { + private _cs = new CharacterStream(''); + private _tokens: Token[] = []; + private _prevLineStart = 0; + private _parenDepth = 0; + private _lineRanges: TextRange[] = []; + private _indentAmounts: number[] = []; + + tokenize(text: string, start?: number, length?: number): TokenizerOutput { + if (start === undefined) { + start = 0; + } else if (start < 0 || start > text.length) { + throw new Error('Invalid range start'); + } + + if (length === undefined) { + length = text.length; + } else if (length < 0 || start + length > text.length) { + throw new Error('Invalid range length'); + } + + this._cs = new CharacterStream(text); + this._cs.position = start; + this._tokens = []; + this._prevLineStart = 0; + this._parenDepth = 0; + this._lineRanges = []; + this._indentAmounts = []; + + const end = start + length; + while (!this._cs.isEndOfStream()) { + this._addNextToken(); + + if (this._cs.position >= end) { + break; + } + } + + // Insert an implied new line to make parsing easier. + if (this._tokens.length === 0 || this._tokens[this._tokens.length - 1].type !== TokenType.NewLine) { + this._tokens.push(new NewLineToken(this._cs.position, 0, NewLineType.Implied)); + } + + // Insert any implied dedent tokens. + this._setIndent(0); + + // Add a final end-of-stream token to make parsing easier. + this._tokens.push(new Token(TokenType.EndOfStream, this._cs.position, 0)); + + // Add the final line range. + this._addLineRange(); + + return { + tokens: new TextRangeCollection(this._tokens), + lines: new TextRangeCollection(this._lineRanges) + }; + } + + static getOperatorInfo(operatorType: OperatorType): OperatorFlags { + return _operatorInfo[operatorType]; + } + + static isOperatorAssignment(operatorType?: OperatorType): boolean { + if (operatorType === undefined || _operatorInfo[operatorType] === undefined) { + return false; + } + return (_operatorInfo[operatorType] & OperatorFlags.Assignment) !== 0; + } + + static isOperatorComparison(operatorType?: OperatorType): boolean { + if (operatorType === undefined || _operatorInfo[operatorType] === undefined) { + return false; + } + return (_operatorInfo[operatorType] & OperatorFlags.Comparison) !== 0; + } + + private _addNextToken(): void { + this._cs.skipWhitespace(); + + if (this._cs.isEndOfStream()) { + return; + } + + if (!this._handleCharacter()) { + this._cs.moveNext(); + } + } + + private _handleCharacter(): boolean { + // f-strings, b-strings, etc + const stringPrefixLength = this._getStringPrefixLength(); + + if (stringPrefixLength >= 0) { + let stringPrefix = ''; + if (stringPrefixLength > 0) { + stringPrefix = this._cs.getText().substr(this._cs.position, stringPrefixLength); + // Indeed a string + this._cs.advance(stringPrefixLength); + } + + const quoteTypeFlags = this._getQuoteTypeFlags(stringPrefix); + if (quoteTypeFlags !== QuoteTypeFlags.None) { + this._handleString(quoteTypeFlags, stringPrefixLength); + return true; + } + } + + if (this._cs.currentChar === Char.Hash) { + this._handleComment(); + return true; + } + + switch (this._cs.currentChar) { + case Char.CarriageReturn: + const length = this._cs.nextChar === Char.LineFeed ? 2 : 1; + const newLineType = length === 2 ? + NewLineType.CarriageReturnLineFeed : NewLineType.CarriageReturn; + this._handleNewLine(length, newLineType); + return true; + + case Char.LineFeed: + this._handleNewLine(1, NewLineType.LineFeed); + return true; + + case Char.Backslash: + if (this._cs.nextChar === Char.CarriageReturn) { + if (this._cs.lookAhead(2) === Char.LineFeed) { + this._cs.advance(3); + } else { + this._cs.advance(2); + } + this._addLineRange(); + return true; + } else if (this._cs.nextChar === Char.LineFeed) { + this._cs.advance(2); + this._addLineRange(); + return true; + } + this._handleInvalid(); + return true; + + case Char.OpenParenthesis: + this._parenDepth++; + this._tokens.push(new Token(TokenType.OpenParenthesis, this._cs.position, 1)); + break; + + case Char.CloseParenthesis: + if (this._parenDepth > 0) { + this._parenDepth--; + } + this._tokens.push(new Token(TokenType.CloseParenthesis, this._cs.position, 1)); + break; + + case Char.OpenBracket: + this._parenDepth++; + this._tokens.push(new Token(TokenType.OpenBracket, this._cs.position, 1)); + break; + + case Char.CloseBracket: + if (this._parenDepth > 0) { + this._parenDepth--; + } + this._tokens.push(new Token(TokenType.CloseBracket, this._cs.position, 1)); + break; + + case Char.OpenBrace: + this._parenDepth++; + this._tokens.push(new Token(TokenType.OpenCurlyBrace, this._cs.position, 1)); + break; + + case Char.CloseBrace: + if (this._parenDepth > 0) { + this._parenDepth--; + } + this._tokens.push(new Token(TokenType.CloseCurlyBrace, this._cs.position, 1)); + break; + + case Char.Comma: + this._tokens.push(new Token(TokenType.Comma, this._cs.position, 1)); + break; + + case Char.Semicolon: + this._tokens.push(new Token(TokenType.Semicolon, this._cs.position, 1)); + break; + + case Char.Colon: + this._tokens.push(new Token(TokenType.Colon, this._cs.position, 1)); + break; + + default: + if (this._isPossibleNumber()) { + if (this._tryNumber()) { + return true; + } + } + + if (this._cs.currentChar === Char.Period) { + if (this._cs.nextChar === Char.Period && this._cs.lookAhead(2) === Char.Period) { + this._tokens.push(new Token(TokenType.Ellipsis, this._cs.position, 3)); + this._cs.advance(3); + return true; + } + this._tokens.push(new Token(TokenType.Dot, this._cs.position, 1)); + break; + } + + if (!this._tryIdentifier()) { + if (!this._tryOperator()) { + this._handleInvalid(); + } + } + return true; + } + return false; + } + + private _addLineRange() { + const lineLength = this._cs.position - this._prevLineStart; + if (lineLength > 0) { + this._lineRanges.push(new TextRange(this._prevLineStart, lineLength)); + } + + this._prevLineStart = this._cs.position; + } + + private _handleNewLine(length: number, newLineType: NewLineType) { + if (this._parenDepth === 0 && newLineType !== NewLineType.Implied) { + // New lines are ignored within parentheses. + // We'll also avoid adding multiple newlines in a row to simplify parsing. + if (this._tokens.length === 0 || this._tokens[this._tokens.length - 1].type !== TokenType.NewLine) { + this._tokens.push(new NewLineToken(this._cs.position, length, newLineType)); + } + } + this._cs.advance(length); + this._addLineRange(); + this._readIndentationAfterNewLine(); + } + + private _readIndentationAfterNewLine() { + let spaceCount = 0; + + while (!this._cs.isEndOfStream()) { + switch (this._cs.currentChar) { + case Char.Space: + spaceCount++; + this._cs.moveNext(); + break; + + case Char.Tab: + spaceCount += 8 - (spaceCount % 8); + this._cs.moveNext(); + break; + + case Char.FormFeed: + spaceCount = 0; + this._cs.moveNext(); + break; + + default: + // Non-blank line. Set the current indent level. + this._setIndent(spaceCount); + return; + + case Char.Hash: + case Char.LineFeed: + case Char.CarriageReturn: + // Blank line -- no need to adjust indentation. + return; + } + } + } + + private _setIndent(spaceCount: number) { + // Indentations are ignored within a parenthesized clause. + if (this._parenDepth > 0) { + return; + } + + // Insert indent or dedent tokens as necessary. + if (this._indentAmounts.length === 0) { + if (spaceCount > 0) { + this._indentAmounts.push(spaceCount); + this._tokens.push(new IndentToken(this._cs.position, 0, spaceCount)); + } + } else { + if (this._indentAmounts[this._indentAmounts.length - 1] < spaceCount) { + this._indentAmounts.push(spaceCount); + this._tokens.push(new IndentToken(this._cs.position, 0, spaceCount)); + } else { + // The Python spec says that dedent amounts need to match the indent + // amount exactly. An error is generated at runtime if it doesn't. + // We'll record that error condition within the token, allowing the + // parser to report it later. + let dedentPoints: number[] = []; + while (this._indentAmounts.length > 0 && + this._indentAmounts[this._indentAmounts.length - 1] > spaceCount) { + dedentPoints.push(this._indentAmounts.length > 1 ? + this._indentAmounts[this._indentAmounts.length - 2] : 0); + this._indentAmounts.pop(); + } + + dedentPoints.forEach((dedentAmount, index) => { + let matchesIndent = index < dedentPoints.length - 1 || + dedentAmount === spaceCount; + let actualDedentAmount = index < dedentPoints.length - 1 ? + dedentAmount : spaceCount; + this._tokens.push(new DedentToken(this._cs.position, 0, actualDedentAmount, + matchesIndent)); + }); + } + } + } + + private _tryIdentifier(): boolean { + const start = this._cs.position; + if (isIdentifierStartChar(this._cs.currentChar)) { + this._cs.moveNext(); + while (isIdentifierChar(this._cs.currentChar)) { + this._cs.moveNext(); + } + } + if (this._cs.position > start) { + const value = this._cs.getText().substr(start, this._cs.position - start); + if (_keywords[value] !== undefined) { + this._tokens.push(new KeywordToken(start, this._cs.position - start, _keywords[value])); + } else { + this._tokens.push(new IdentifierToken(start, this._cs.position - start, value)); + } + return true; + } + return false; + } + + private _isPossibleNumber(): boolean { + if (isDecimal(this._cs.currentChar)) { + return true; + } + + if (this._cs.currentChar === Char.Period && isDecimal(this._cs.nextChar)) { + return true; + } + + return false; + } + + private _tryNumber(): boolean { + const start = this._cs.position; + + if (this._cs.currentChar === Char._0) { + let radix = 0; + let leadingChars = 0; + + // Try hex => hexinteger: "0" ("x" | "X") (["_"] hexdigit)+ + if ((this._cs.nextChar === Char.x || this._cs.nextChar === Char.X) && isHex(this._cs.lookAhead(2))) { + this._cs.advance(2); + leadingChars = 2; + while (isHex(this._cs.currentChar)) { + this._cs.moveNext(); + } + radix = 16; + } + // Try binary => bininteger: "0" ("b" | "B") (["_"] bindigit)+ + if ((this._cs.nextChar === Char.b || this._cs.nextChar === Char.B) && isBinary(this._cs.lookAhead(2))) { + this._cs.advance(2); + leadingChars = 2; + while (isBinary(this._cs.currentChar)) { + this._cs.moveNext(); + } + radix = 2; + } + // Try octal => octinteger: "0" ("o" | "O") (["_"] octdigit)+ + if ((this._cs.nextChar === Char.o || this._cs.nextChar === Char.O) && isOctal(this._cs.lookAhead(2))) { + this._cs.advance(2); + leadingChars = 2; + while (isOctal(this._cs.currentChar)) { + this._cs.moveNext(); + } + radix = 8; + } + if (radix > 0) { + const text = this._cs.getText().substr(start, this._cs.position - start); + const value = parseInt(text.substr(leadingChars).replace(/_/g, ''), radix); + if (!isNaN(value)) { + this._tokens.push(new NumberToken(start, text.length, value, true)); + return true; + } + } + } + + let isDecimalInteger = false; + let mightBeFloatingPoint = false; + // Try decimal int => + // decinteger: nonzerodigit (["_"] digit)* | "0" (["_"] "0")* + // nonzerodigit: "1"..."9" + // digit: "0"..."9" + if (this._cs.currentChar >= Char._1 && this._cs.currentChar <= Char._9) { + while (isDecimal(this._cs.currentChar)) { + mightBeFloatingPoint = true; + this._cs.moveNext(); + } + isDecimalInteger = this._cs.currentChar !== Char.Period && this._cs.currentChar !== Char.e && this._cs.currentChar !== Char.E; + } + + // "0" (["_"] "0")* + if (this._cs.currentChar === Char._0) { + mightBeFloatingPoint = true; + while (this._cs.currentChar === Char._0 || this._cs.currentChar === Char.Underscore) { + this._cs.moveNext(); + } + isDecimalInteger = this._cs.currentChar !== Char.Period && this._cs.currentChar !== Char.e && this._cs.currentChar !== Char.E; + } + + if (isDecimalInteger) { + const text = this._cs.getText().substr(start, this._cs.position - start); + const value = parseInt(text.replace(/_/g, ''), 10); + if (!isNaN(value)) { + this._tokens.push(new NumberToken(start, text.length, value, true)); + return true; + } + } + + // Floating point. Sign and leading digits were already skipped over. + this._cs.position = start; + if (mightBeFloatingPoint || + (this._cs.currentChar === Char.Period && this._cs.nextChar >= Char._0 && this._cs.nextChar <= Char._9)) { + if (this._skipFloatingPointCandidate()) { + const text = this._cs.getText().substr(start, this._cs.position - start); + const value = parseFloat(text); + if (!isNaN(value)) { + this._tokens.push(new NumberToken(start, this._cs.position - start, value, false)); + return true; + } + } + } + + this._cs.position = start; + return false; + } + + private _tryOperator(): boolean { + let length = 0; + const nextChar = this._cs.nextChar; + let operatorType: OperatorType; + + switch (this._cs.currentChar) { + case Char.Plus: + length = nextChar === Char.Equal ? 2 : 1; + operatorType = length === 2 ? OperatorType.AddEqual : OperatorType.Add; + break; + + case Char.Ampersand: + length = nextChar === Char.Equal ? 2 : 1; + operatorType = length === 2 ? OperatorType.BitwiseAndEqual : OperatorType.BitwiseAnd; + break; + + case Char.Bar: + length = nextChar === Char.Equal ? 2 : 1; + operatorType = length === 2 ? OperatorType.BitwiseOrEqual : OperatorType.BitwiseOr; + break; + + case Char.Caret: + length = nextChar === Char.Equal ? 2 : 1; + operatorType = length === 2 ? OperatorType.ExclusiveOrEqual : OperatorType.ExclusiveOr; + break; + + case Char.Equal: + length = nextChar === Char.Equal ? 2 : 1; + operatorType = length === 2 ? OperatorType.Equals : OperatorType.Assign; + break; + + case Char.ExclamationMark: + if (nextChar !== Char.Equal) { + return false; + } + length = 2; + operatorType = OperatorType.NotEquals; + break; + + case Char.Percent: + length = nextChar === Char.Equal ? 2 : 1; + operatorType = length === 2 ? OperatorType.ModEqual : OperatorType.Mod; + break; + + case Char.Tilde: + length = 1; + operatorType = OperatorType.BitwiseInvert; + break; + + case Char.Hyphen: + if (nextChar === Char.Greater) { + this._tokens.push(new Token(TokenType.Arrow, this._cs.position, 2)); + this._cs.advance(2); + return true; + } + + length = nextChar === Char.Equal ? 2 : 1; + operatorType = length === 2 ? OperatorType.SubtractEqual : OperatorType.Subtract; + break; + + case Char.Asterisk: + if (nextChar === Char.Asterisk) { + length = this._cs.lookAhead(2) === Char.Equal ? 3 : 2; + operatorType = length === 3 ? OperatorType.PowerEqual : OperatorType.Power; + } else { + length = nextChar === Char.Equal ? 2 : 1; + operatorType = length === 2 ? OperatorType.MultiplyEqual : OperatorType.Multiply; + } + break; + + case Char.Slash: + if (nextChar === Char.Slash) { + length = this._cs.lookAhead(2) === Char.Equal ? 3 : 2; + operatorType = length === 3 ? OperatorType.FloorDivideEqual : OperatorType.FloorDivide; + } else { + length = nextChar === Char.Equal ? 2 : 1; + operatorType = length === 2 ? OperatorType.DivideEqual : OperatorType.Divide; + } + break; + + case Char.Less: + if (nextChar === Char.Less) { + length = this._cs.lookAhead(2) === Char.Equal ? 3 : 2; + operatorType = length === 3 ? OperatorType.LeftShiftEqual : OperatorType.LeftShift; + } else { + length = nextChar === Char.Equal ? 2 : 1; + operatorType = length === 2 ? OperatorType.LessThanOrEqual : OperatorType.LessThan; + } + break; + + case Char.Greater: + if (nextChar === Char.Greater) { + length = this._cs.lookAhead(2) === Char.Equal ? 3 : 2; + operatorType = length === 3 ? OperatorType.RightShiftEqual : OperatorType.RightShift; + } else { + length = nextChar === Char.Equal ? 2 : 1; + operatorType = length === 2 ? OperatorType.GreaterThanOrEqual : OperatorType.GreaterThan; + } + break; + + case Char.At: + length = nextChar === Char.Equal ? 2 : 1; + operatorType = length === 2 ? OperatorType.MatrixMultiplyEqual : OperatorType.MatrixMultiply; + break; + + default: + return false; + } + this._tokens.push(new OperatorToken(this._cs.position, length, operatorType)); + this._cs.advance(length); + return length > 0; + } + + private _handleInvalid(): boolean { + const start = this._cs.position; + this._cs.skipToWhitespace(); + const length = this._cs.position - start; + if (length > 0) { + this._tokens.push(new Token(TokenType.Invalid, start, length)); + return true; + } + return false; + } + + private _handleComment(): void { + this._cs.skipToEol(); + } + + private _getStringPrefixLength(): number { + if (this._cs.currentChar === Char.SingleQuote || this._cs.currentChar === Char.DoubleQuote) { + // Simple string, no prefix + return 0; + } + + if (this._cs.nextChar === Char.SingleQuote || this._cs.nextChar === Char.DoubleQuote) { + switch (this._cs.currentChar) { + case Char.f: + case Char.F: + case Char.r: + case Char.R: + case Char.b: + case Char.B: + case Char.u: + case Char.U: + // Single-char prefix like u"" or r"" + return 1; + default: + break; + } + } + + if (this._cs.lookAhead(2) === Char.SingleQuote || this._cs.lookAhead(2) === Char.DoubleQuote) { + const prefix = this._cs.getText().substr(this._cs.position, 2).toLowerCase(); + switch (prefix) { + case 'rf': + case 'fr': + case 'ur': + case 'ru': + case 'br': + case 'rb': + return 2; + default: + break; + } + } + return -1; + } + + private _getQuoteTypeFlags(prefix: string): QuoteTypeFlags { + let flags = QuoteTypeFlags.None; + + if (prefix.length > 0) { + prefix = prefix.toLowerCase(); + if (prefix[0] === 'u') { + flags |= QuoteTypeFlags.Unicode; + } else if (prefix[0] === 'b') { + flags |= QuoteTypeFlags.Byte; + } + + if (prefix[prefix.length - 1] === 'r') { + flags |= QuoteTypeFlags.Raw; + } + } + + if (this._cs.currentChar === Char.SingleQuote) { + flags |= QuoteTypeFlags.SingleQuote; + if (this._cs.nextChar === Char.SingleQuote && this._cs.lookAhead(2) === Char.SingleQuote) { + flags |= QuoteTypeFlags.Triplicate; + } + return flags; + } + if (this._cs.currentChar === Char.DoubleQuote) { + flags |= QuoteTypeFlags.DoubleQuote; + if (this._cs.nextChar === Char.DoubleQuote && this._cs.lookAhead(2) === Char.DoubleQuote) { + flags |= QuoteTypeFlags.Triplicate; + } + return flags; + } + return QuoteTypeFlags.None; + } + + private _handleString(quoteTypeFlags: QuoteTypeFlags, stringPrefixLength: number): void { + let start = this._cs.position - stringPrefixLength; + let quoteLength = 1; + + if (quoteTypeFlags & QuoteTypeFlags.Triplicate) { + this._cs.advance(3); + this._skipToTripleEndQuote(quoteTypeFlags & QuoteTypeFlags.SingleQuote ? + Char.SingleQuote : Char.DoubleQuote); + quoteLength = 3; + } else { + this._cs.moveNext(); + this._skipToSingleEndQuote(quoteTypeFlags & QuoteTypeFlags.SingleQuote ? + Char.SingleQuote : Char.DoubleQuote); + } + + let end = this._cs.position; + + // TODO - need to handle proper de-escaping to get string value + const value = this._cs.getText().substr(start + stringPrefixLength + quoteLength, + end - start - quoteLength * 2 - stringPrefixLength); + this._tokens.push(new StringToken(start, end - start, quoteTypeFlags, value)); + } + + private _skipToSingleEndQuote(quote: number): void { + let isEscaped = false; + + while (!this._cs.isEndOfStream()) { + if (this._cs.currentChar === Char.LineFeed || this._cs.currentChar === Char.CarriageReturn) { + if (!isEscaped) { + // Unterminated single-line string + return; + } else { + // TODO - need to properly handle escapes \ooo, \xhh, \N{name}, \uxxxx and \Uxxxxxxxx + isEscaped = false; + + // Skip over the escaped new line (either one or two characters). + if (this._cs.currentChar === Char.LineFeed && this._cs.nextChar === Char.CarriageReturn) { + this._cs.advance(2); + continue; + } else { + this._cs.moveNext(); + continue; + } + } + } + + if (this._cs.currentChar === Char.Backslash) { + isEscaped = !isEscaped; + } else { + if (!isEscaped && this._cs.currentChar === quote) { + break; + } + isEscaped = false; + } + this._cs.moveNext(); + } + + this._cs.moveNext(); + } + + private _skipToTripleEndQuote(quote: number): void { + while (!this ._cs.isEndOfStream() && (this._cs.currentChar !== quote || + this._cs.nextChar !== quote || this._cs.lookAhead(2) !== quote)) { + + // TODO - need to handle escaping of all flavors + if (this._cs.currentChar === Char.CarriageReturn) { + if (this._cs.nextChar === Char.LineFeed) { + this._cs.moveNext(); + } + this._cs.moveNext(); + this._addLineRange(); + } else if (this._cs.currentChar === Char.LineFeed) { + this._cs.moveNext(); + this._addLineRange(); + } else { + this._cs.moveNext(); + } + } + this._cs.advance(3); + } + + private _skipFloatingPointCandidate(): boolean { + // Determine end of the potential floating point number + const start = this._cs.position; + this._skipFractionalNumber(); + if (this._cs.position > start) { + // Optional exponent sign + if (this._cs.currentChar === Char.e || this._cs.currentChar === Char.E) { + this._cs.moveNext(); + + // Skip exponent value + this._skipDecimalNumber(true); + } + } + return this._cs.position > start; + } + + private _skipFractionalNumber(): void { + this._skipDecimalNumber(false); + if (this._cs.currentChar === Char.Period) { + // Optional period + this._cs.moveNext(); + } + this._skipDecimalNumber(false); + } + + private _skipDecimalNumber(allowSign: boolean): void { + if (allowSign && (this._cs.currentChar === Char.Hyphen || this._cs.currentChar === Char.Plus)) { + // Optional sign + this._cs.moveNext(); + } + while (isDecimal(this._cs.currentChar)) { + // Skip integer part + this._cs.moveNext(); + } + } +} diff --git a/server/src/parser/tokenizerTypes.ts b/server/src/parser/tokenizerTypes.ts new file mode 100644 index 000000000..0b734accc --- /dev/null +++ b/server/src/parser/tokenizerTypes.ts @@ -0,0 +1,238 @@ + +/* +* tokenizerTypes.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Based on code from vscode-python repository: +* https://github.com/Microsoft/vscode-python +* +* Interface, enumeration and class definitions used within +* the Python tokenizer. +*/ + +import { TextRange } from '../common/textRange'; + +export enum TokenType { + Invalid, + EndOfStream, + NewLine, + Indent, + Dedent, + String, + Number, + Identifier, + Keyword, + Operator, + Colon, + Semicolon, + Comma, + OpenParenthesis, + CloseParenthesis, + OpenBracket, + CloseBracket, + OpenCurlyBrace, + CloseCurlyBrace, + Ellipsis, + Dot, + Arrow +} + +export enum NewLineType { + CarriageReturn, + LineFeed, + CarriageReturnLineFeed, + Implied +} + +export enum OperatorType { + // These operators are used with tokens + // of type TokenType.Operator. + Add, + AddEqual, + Assign, + BitwiseAnd, + BitwiseAndEqual, + BitwiseInvert, + BitwiseOr, + BitwiseOrEqual, + Divide, + DivideEqual, + Equals, + ExclusiveOr, + ExclusiveOrEqual, + FloorDivide, + FloorDivideEqual, + GreaterThan, + GreaterThanOrEqual, + LeftShift, + LeftShiftEqual, + LessThan, + LessThanOrEqual, + MatrixMultiply, + MatrixMultiplyEqual, + Mod, + ModEqual, + Multiply, + MultiplyEqual, + NotEquals, + Power, + PowerEqual, + RightShift, + RightShiftEqual, + Subtract, + SubtractEqual, + + // These operators are used with tokens + // of type TokenType.Keyword. + And, + Or, + Not, + Is, + IsNot, + In, + NotIn +} + +export enum OperatorFlags { + Unary = 0x1, + Binary = 0x2, + Assignment = 0x4, + Comparison = 0x8 +} + +export enum KeywordType { + And, + As, + Assert, + Async, + Await, + Break, + Class, + Continue, + Debug, + Def, + Del, + Elif, + Else, + Except, + False, + Finally, + For, + From, + Global, + If, + Import, + In, + Is, + Lambda, + None, + Nonlocal, + Not, + Or, + Pass, + Raise, + Return, + True, + Try, + While, + With, + Yield +} + +export enum QuoteTypeFlags { + None = 0x0, + SingleQuote = 0x1, + DoubleQuote = 0x2, + Triplicate = 0x4, + Raw = 0x8, + Unicode = 0x10, + Byte = 0x20 +} + +export class Token extends TextRange implements Token { + readonly type: TokenType; + + constructor(type: TokenType, start: number, length: number) { + super(start, length); + this.type = type; + } +} + +export class IndentToken extends Token { + readonly indentAmount: number; + + constructor(start: number, length: number, indentAmount: number) { + super(TokenType.Indent, start, length); + this.indentAmount = indentAmount; + } +} + +export class DedentToken extends Token { + readonly indentAmount: number; + readonly matchesIndent: boolean; + + constructor(start: number, length: number, indentAmount: number, matchesIndent: boolean) { + super(TokenType.Dedent, start, length); + this.indentAmount = indentAmount; + this.matchesIndent = matchesIndent; + } +} + +export class NewLineToken extends Token { + readonly newLineType: NewLineType; + + constructor(start: number, length: number, newLineType: NewLineType) { + super(TokenType.NewLine, start, length); + this.newLineType = newLineType; + } +} + +export class KeywordToken extends Token { + readonly keywordType: KeywordType; + + constructor(start: number, length: number, keywordType: KeywordType) { + super(TokenType.Keyword, start, length); + this.keywordType = keywordType; + } +} + +export class StringToken extends Token { + readonly quoteTypeFlags: QuoteTypeFlags; + readonly value: string; + + constructor(start: number, length: number, quoteTypeFlags: QuoteTypeFlags, value: string) { + super(TokenType.String, start, length); + this.quoteTypeFlags = quoteTypeFlags; + this.value = value; + } +} + +export class NumberToken extends Token { + readonly value: number; + readonly isInteger: boolean; + + constructor(start: number, length: number, value: number, isInteger: boolean) { + super(TokenType.Number, start, length); + this.value = value; + this.isInteger = isInteger; + } +} + +export class OperatorToken extends Token { + readonly operatorType: OperatorType; + + constructor(start: number, length: number, operatorType: OperatorType) { + super(TokenType.Operator, start, length); + this.operatorType = operatorType; + } +} + +export class IdentifierToken extends Token { + readonly value: string; + + constructor(start: number, length: number, value: string) { + super(TokenType.Identifier, start, length); + this.value = value; + } +} diff --git a/server/src/parser/unicode.ts b/server/src/parser/unicode.ts new file mode 100644 index 000000000..0ee78aa3b --- /dev/null +++ b/server/src/parser/unicode.ts @@ -0,0 +1,252 @@ +/* +* unicode.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Tables that encode Unicode character codes for various Unicode- +* defined categories used in the Python spec. These tables were built +* from the npm package unicode, which contains the same information +* in a much more verbose form. +*/ + +export type UnicodeRangeTable = ([number, number] | number)[]; + +export const unicodeLu: UnicodeRangeTable = [[65, 90], [192, 214], [216, 222], 256, 258, 260, 262, 264, 266, + 268, 270, 272, 274, 276, 278, 280, 282, 284, 286, 288, 290, 292, 294, 296, 298, 300, 302, 304, 306, 308, + 310, 313, 315, 317, 319, 321, 323, 325, 327, 330, 332, 334, 336, 338, 340, 342, 344, 346, 348, 350, 352, + 354, 356, 358, 360, 362, 364, 366, 368, 370, 372, 374, [376, 377], 379, 381, [385, 386], 388, [390, 391], + [393, 395], [398, 401], [403, 404], [406, 408], [412, 413], [415, 416], 418, 420, [422, 423], 425, + 428, [430, 431], [433, 435], 437, [439, 440], 444, 452, 455, 458, 461, 463, 465, 467, 469, 471, 473, + 475, 478, 480, 482, 484, 486, 488, 490, 492, 494, 497, 500, [502, 504], 506, 508, 510, 512, 514, 516, + 518, 520, 522, 524, 526, 528, 530, 532, 534, 536, 538, 540, 542, 544, 546, 548, 550, 552, 554, 556, + 558, 560, 562, [570, 571], [573, 574], 577, [579, 582], 584, 586, 588, 590, 880, 882, 886, 895, 902, + [904, 906], 908, [910, 911], [913, 929], [931, 939], 975, [978, 980], 984, 986, 988, 990, 992, 994, + 996, 998, 1000, 1002, 1004, 1006, 1012, 1015, [1017, 1018], [1021, 1071], 1120, 1122, 1124, 1126, + 1128, 1130, 1132, 1134, 1136, 1138, 1140, 1142, 1144, 1146, 1148, 1150, 1152, 1162, 1164, 1166, 1168, + 1170, 1172, 1174, 1176, 1178, 1180, 1182, 1184, 1186, 1188, 1190, 1192, 1194, 1196, 1198, 1200, 1202, + 1204, 1206, 1208, 1210, 1212, 1214, [1216, 1217], 1219, 1221, 1223, 1225, 1227, 1229, 1232, 1234, + 1236, 1238, 1240, 1242, 1244, 1246, 1248, 1250, 1252, 1254, 1256, 1258, 1260, 1262, 1264, 1266, 1268, + 1270, 1272, 1274, 1276, 1278, 1280, 1282, 1284, 1286, 1288, 1290, 1292, 1294, 1296, 1298, 1300, 1302, + 1304, 1306, 1308, 1310, 1312, 1314, 1316, 1318, 1320, 1322, 1324, 1326, [1329, 1366], [4256, 4293], + 4295, 4301, [5024, 5109], 7680, 7682, 7684, 7686, 7688, 7690, 7692, 7694, 7696, 7698, 7700, 7702, + 7704, 7706, 7708, 7710, 7712, 7714, 7716, 7718, 7720, 7722, 7724, 7726, 7728, 7730, 7732, 7734, 7736, + 7738, 7740, 7742, 7744, 7746, 7748, 7750, 7752, 7754, 7756, 7758, 7760, 7762, 7764, 7766, 7768, 7770, + 7772, 7774, 7776, 7778, 7780, 7782, 7784, 7786, 7788, 7790, 7792, 7794, 7796, 7798, 7800, 7802, 7804, + 7806, 7808, 7810, 7812, 7814, 7816, 7818, 7820, 7822, 7824, 7826, 7828, 7838, 7840, 7842, 7844, 7846, + 7848, 7850, 7852, 7854, 7856, 7858, 7860, 7862, 7864, 7866, 7868, 7870, 7872, 7874, 7876, 7878, 7880, + 7882, 7884, 7886, 7888, 7890, 7892, 7894, 7896, 7898, 7900, 7902, 7904, 7906, 7908, 7910, 7912, 7914, + 7916, 7918, 7920, 7922, 7924, 7926, 7928, 7930, 7932, 7934, [7944, 7951], [7960, 7965], [7976, 7983], + [7992, 7999], [8008, 8013], 8025, 8027, 8029, 8031, [8040, 8047], [8120, 8123], [8136, 8139], [8152, 8155], + [8168, 8172], [8184, 8187], 8450, 8455, [8459, 8461], [8464, 8466], 8469, [8473, 8477], 8484, 8486, 8488, + [8490, 8493], [8496, 8499], [8510, 8511], 8517, 8579, [11264, 11310], 11360, [11362, 11364], 11367, 11369, + 11371, [11373, 11376], 11378, 11381, [11390, 11392], 11394, 11396, 11398, 11400, 11402, 11404, 11406, 11408, + 11410, 11412, 11414, 11416, 11418, 11420, 11422, 11424, 11426, 11428, 11430, 11432, 11434, 11436, 11438, + 11440, 11442, 11444, 11446, 11448, 11450, 11452, 11454, 11456, 11458, 11460, 11462, 11464, 11466, 11468, + 11470, 11472, 11474, 11476, 11478, 11480, 11482, 11484, 11486, 11488, 11490, 11499, 11501, 11506, 42560, + 42562, 42564, 42566, 42568, 42570, 42572, 42574, 42576, 42578, 42580, 42582, 42584, 42586, 42588, 42590, + 42592, 42594, 42596, 42598, 42600, 42602, 42604, 42624, 42626, 42628, 42630, 42632, 42634, 42636, 42638, + 42640, 42642, 42644, 42646, 42648, 42650, 42786, 42788, 42790, 42792, 42794, 42796, 42798, 42802, 42804, + 42806, 42808, 42810, 42812, 42814, 42816, 42818, 42820, 42822, 42824, 42826, 42828, 42830, 42832, 42834, + 42836, 42838, 42840, 42842, 42844, 42846, 42848, 42850, 42852, 42854, 42856, 42858, 42860, 42862, 42873, + 42875, [42877, 42878], 42880, 42882, 42884, 42886, 42891, 42893, 42896, 42898, 42902, 42904, 42906, + 42908, 42910, 42912, 42914, 42916, 42918, 42920, [42922, 42926], [42928, 42932], 42934, [65313, 65338], + [66560, 66599], [66736, 66771], [68736, 68786], [71840, 71871], [119808, 119833], [119860, 119885], + [119912, 119937], 119964, [119966, 119967], 119970, [119973, 119974], [119977, 119980], [119982, 119989], + [120016, 120041], [120068, 120069], [120071, 120074], [120077, 120084], [120086, 120092], [120120, 120121], + [120123, 120126], [120128, 120132], 120134, [120138, 120144], [120172, 120197], [120224, 120249], + [120276, 120301], [120328, 120353], [120380, 120405], [120432, 120457], [120488, 120512], [120546, 120570], + [120604, 120628], [120662, 120686], [120720, 120744], 120778, [125184, 125217]]; + +export const unicodeLl: UnicodeRangeTable = [[97, 122], 181, [223, 246], [248, 255], 257, 259, 261, 263, 265, + 267, 269, 271, 273, 275, 277, 279, 281, 283, 285, 287, 289, 291, 293, 295, 297, 299, 301, 303, 305, 307, 309, + [311, 312], 314, 316, 318, 320, 322, 324, 326, [328, 329], 331, 333, 335, 337, 339, 341, 343, 345, 347, 349, + 351, 353, 355, 357, 359, 361, 363, 365, 367, 369, 371, 373, 375, 378, 380, [382, 384], 387, 389, 392, [396, 397], + 402, 405, [409, 411], 414, 417, 419, 421, 424, [426, 427], 429, 432, 436, 438, [441, 442], [445, 447], 454, 457, + 460, 462, 464, 466, 468, 470, 472, 474, [476, 477], 479, 481, 483, 485, 487, 489, 491, 493, [495, 496], 499, + 501, 505, 507, 509, 511, 513, 515, 517, 519, 521, 523, 525, 527, 529, 531, 533, 535, 537, 539, 541, 543, + 545, 547, 549, 551, 553, 555, 557, 559, 561, [563, 569], 572, [575, 576], 578, 583, 585, 587, 589, [591, + 659], [661, 687], 881, 883, 887, [891, 893], 912, [940, 974], [976, 977], [981, 983], 985, 987, 989, 991, + 993, 995, 997, 999, 1001, 1003, 1005, [1007, 1011], 1013, 1016, [1019, 1020], [1072, 1119], 1121, 1123, 1125, + 1127, 1129, 1131, 1133, 1135, 1137, 1139, 1141, 1143, 1145, 1147, 1149, 1151, 1153, 1163, 1165, 1167, 1169, + 1171, 1173, 1175, 1177, 1179, 1181, 1183, 1185, 1187, 1189, 1191, 1193, 1195, 1197, 1199, 1201, 1203, 1205, + 1207, 1209, 1211, 1213, 1215, 1218, 1220, 1222, 1224, 1226, 1228, [1230, 1231], 1233, 1235, 1237, 1239, 1241, + 1243, 1245, 1247, 1249, 1251, 1253, 1255, 1257, 1259, 1261, 1263, 1265, 1267, 1269, 1271, 1273, 1275, 1277, + 1279, 1281, 1283, 1285, 1287, 1289, 1291, 1293, 1295, 1297, 1299, 1301, 1303, 1305, 1307, 1309, 1311, 1313, + 1315, 1317, 1319, 1321, 1323, 1325, 1327, [1377, 1415], [5112, 5117], [7296, 7304], [7424, 7467], [7531, 7543], + [7545, 7578], 7681, 7683, 7685, 7687, 7689, 7691, 7693, 7695, 7697, 7699, 7701, 7703, 7705, 7707, 7709, 7711, + 7713, 7715, 7717, 7719, 7721, 7723, 7725, 7727, 7729, 7731, 7733, 7735, 7737, 7739, 7741, 7743, 7745, 7747, + 7749, 7751, 7753, 7755, 7757, 7759, 7761, 7763, 7765, 7767, 7769, 7771, 7773, 7775, 7777, 7779, 7781, 7783, + 7785, 7787, 7789, 7791, 7793, 7795, 7797, 7799, 7801, 7803, 7805, 7807, 7809, 7811, 7813, 7815, 7817, 7819, + 7821, 7823, 7825, 7827, [7829, 7837], 7839, 7841, 7843, 7845, 7847, 7849, 7851, 7853, 7855, 7857, 7859, 7861, + 7863, 7865, 7867, 7869, 7871, 7873, 7875, 7877, 7879, 7881, 7883, 7885, 7887, 7889, 7891, 7893, 7895, 7897, + 7899, 7901, 7903, 7905, 7907, 7909, 7911, 7913, 7915, 7917, 7919, 7921, 7923, 7925, 7927, 7929, 7931, 7933, + [7935, 7943], [7952, 7957], [7968, 7975], [7984, 7991], [8000, 8005], [8016, 8023], [8032, 8039], [8048, 8061], + [8064, 8071], [8080, 8087], [8096, 8103], [8112, 8116], [8118, 8119], 8126, [8130, 8132], [8134, 8135], + [8144, 8147], [8150, 8151], [8160, 8167], [8178, 8180], [8182, 8183], 8458, [8462, 8463], 8467, 8495, 8500, + 8505, [8508, 8509], [8518, 8521], 8526, 8580, [11312, 11358], 11361, [11365, 11366], 11368, 11370, 11372, + 11377, [11379, 11380], [11382, 11387], 11393, 11395, 11397, 11399, 11401, 11403, 11405, 11407, 11409, 11411, + 11413, 11415, 11417, 11419, 11421, 11423, 11425, 11427, 11429, 11431, 11433, 11435, 11437, 11439, 11441, + 11443, 11445, 11447, 11449, 11451, 11453, 11455, 11457, 11459, 11461, 11463, 11465, 11467, 11469, 11471, + 11473, 11475, 11477, 11479, 11481, 11483, 11485, 11487, 11489, [11491, 11492], 11500, 11502, 11507, + [11520, 11557], 11559, 11565, 42561, 42563, 42565, 42567, 42569, 42571, 42573, 42575, 42577, 42579, + 2581, 42583, 42585, 42587, 42589, 42591, 42593, 42595, 42597, 42599, 42601, 42603, 42605, 42625, 42627, + 42629, 42631, 42633, 42635, 42637, 42639, 42641, 42643, 42645, 42647, 42649, 42651, 42787, 42789, 42791, + 42793, 42795, 42797, [42799, 42801], 42803, 42805, 42807, 42809, 42811, 42813, 42815, 42817, 42819, 42821, + 42823, 42825, 42827, 42829, 42831, 42833, 42835, 42837, 42839, 42841, 42843, 42845, 42847, 42849, 42851, + 42853, 42855, 42857, 42859, 42861, 42863, [42865, 42872], 42874, 42876, 42879, 42881, 42883, 42885, 42887, + 42892, 42894, 42897, [42899, 42901], 42903, 42905, 42907, 42909, 42911, 42913, 42915, 42917, 42919, 42921, + 42933, 42935, 43002, [43824, 43866], [43872, 43877], [43888, 43967], [64256, 64262], [64275, 64279], + [65345, 65370], [66600, 66639], [66776, 66811], [68800, 68850], [71872, 71903], [119834, 119859], + [119886, 119892], [119894, 119911], [119938, 119963], [119990, 119993], 119995, [119997, 120003], + [120005, 120015], [120042, 120067], [120094, 120119], [120146, 120171], [120198, 120223], [120250, 120275], + [120302, 120327], [120354, 120379], [120406, 120431], [120458, 120485], [120514, 120538], [120540, 120545], + [120572, 120596], [120598, 120603], [120630, 120654], [120656, 120661], [120688, 120712], [120714, 120719], + [120746, 120770], [120772, 120777], 120779, [125218, 125251]]; + +export const unicodeLt: UnicodeRangeTable = [453, 456, 459, 498, [8072, 8079], [8088, 8095], [8104, 8111], + 8124, 8140, 8188]; + +export const unicodeLo: UnicodeRangeTable = [170, 186, 443, [448, 451], 660, [1488, 1514], [1520, 1522], + [1568, 1599], [1601, 1610], [1646, 1647], [1649, 1747], 1749, [1774, 1775], [1786, 1788], 1791, 1808, + [1810, 1839], [1869, 1957], 1969, [1994, 2026], [2048, 2069], [2112, 2136], [2144, 2154], [2208, 2228], + [2230, 2237], [2308, 2361], 2365, 2384, [2392, 2401], [2418, 2432], [2437, 2444], [2447, 2448], [2451, 2472], + [2474, 2480], 2482, [2486, 2489], 2493, 2510, [2524, 2525], [2527, 2529], [2544, 2545], 2556, [2565, 2570], + [2575, 2576], [2579, 2600], [2602, 2608], [2610, 2611], [2613, 2614], [2616, 2617], [2649, 2652], 2654, + [2674, 2676], [2693, 2701], [2703, 2705], [2707, 2728], [2730, 2736], [2738, 2739], [2741, 2745], 2749, 2768, + [2784, 2785], 2809, [2821, 2828], [2831, 2832], [2835, 2856], [2858, 2864], [2866, 2867], [2869, 2873], + 2877, [2908, 2909], [2911, 2913], 2929, 2947, [2949, 2954], [2958, 2960], [2962, 2965], [2969, 2970], + 2972, [2974, 2975], [2979, 2980], [2984, 2986], [2990, 3001], 3024, [3077, 3084], [3086, 3088], + [3090, 3112], [3114, 3129], 3133, [3160, 3162], [3168, 3169], 3200, [3205, 3212], [3214, 3216], + [3218, 3240], [3242, 3251], [3253, 3257], 3261, 3294, [3296, 3297], [3313, 3314], [3333, 3340], + [3342, 3344], [3346, 3386], 3389, 3406, [3412, 3414], [3423, 3425], [3450, 3455], [3461, 3478], + [3482, 3505], [3507, 3515], 3517, [3520, 3526], [3585, 3632], [3634, 3635], [3648, 3653], [3713, 3714], + 3716, [3719, 3720], 3722, 3725, [3732, 3735], [3737, 3743], [3745, 3747], 3749, 3751, [3754, 3755], + [3757, 3760], [3762, 3763], 3773, [3776, 3780], [3804, 3807], 3840, [3904, 3911], [3913, 3948], + [3976, 3980], [4096, 4138], 4159, [4176, 4181], [4186, 4189], 4193, [4197, 4198], [4206, 4208], + [4213, 4225], 4238, [4304, 4346], [4349, 4680], [4682, 4685], [4688, 4694], 4696, [4698, 4701], + [4704, 4744], [4746, 4749], [4752, 4784], [4786, 4789], [4792, 4798], 4800, [4802, 4805], [4808, 4822], + [4824, 4880], [4882, 4885], [4888, 4954], [4992, 5007], [5121, 5740], [5743, 5759], [5761, 5786], + [5792, 5866], [5873, 5880], [5888, 5900], [5902, 5905], [5920, 5937], [5952, 5969], [5984, 5996], + [5998, 6000], [6016, 6067], 6108, [6176, 6210], [6212, 6263], [6272, 6276], [6279, 6312], 6314, + [6320, 6389], [6400, 6430], [6480, 6509], [6512, 6516], [6528, 6571], [6576, 6601], [6656, 6678], + [6688, 6740], [6917, 6963], [6981, 6987], [7043, 7072], [7086, 7087], [7098, 7141], [7168, 7203], + [7245, 7247], [7258, 7287], [7401, 7404], [7406, 7409], [7413, 7414], [8501, 8504], [11568, 11623], + [11648, 11670], [11680, 11686], [11688, 11694], [11696, 11702], [11704, 11710], [11712, 11718], + [11720, 11726], [11728, 11734], [11736, 11742], 12294, 12348, [12353, 12438], 12447, [12449, 12538], + 12543, [12549, 12590], [12593, 12686], [12704, 12730], [12784, 12799], 13312, 19893, 19968, 40938, + [40960, 40980], [40982, 42124], [42192, 42231], [42240, 42507], [42512, 42527], [42538, 42539], 42606, + [42656, 42725], 42895, 42999, [43003, 43009], [43011, 43013], [43015, 43018], [43020, 43042], + [43072, 43123], [43138, 43187], [43250, 43255], 43259, 43261, [43274, 43301], [43312, 43334], + [43360, 43388], [43396, 43442], [43488, 43492], [43495, 43503], [43514, 43518], [43520, 43560], + [43584, 43586], [43588, 43595], [43616, 43631], [43633, 43638], 43642, [43646, 43695], 43697, + [43701, 43702], [43705, 43709], 43712, 43714, [43739, 43740], [43744, 43754], 43762, [43777, 43782], + [43785, 43790], [43793, 43798], [43808, 43814], [43816, 43822], [43968, 44002], 44032, 55203, + [55216, 55238], [55243, 55291], [63744, 64109], [64112, 64217], 64285, [64287, 64296], [64298, 64310], + [64312, 64316], 64318, [64320, 64321], [64323, 64324], [64326, 64433], [64467, 64829], [64848, 64911], + [64914, 64967], [65008, 65019], [65136, 65140], [65142, 65276], [65382, 65391], [65393, 65437], + [65440, 65470], [65474, 65479], [65482, 65487], [65490, 65495], [65498, 65500], [65536, 65547], + [65549, 65574], [65576, 65594], [65596, 65597], [65599, 65613], [65616, 65629], [65664, 65786], + [66176, 66204], [66208, 66256], [66304, 66335], [66349, 66368], [66370, 66377], [66384, 66421], + [66432, 66461], [66464, 66499], [66504, 66511], [66640, 66717], [66816, 66855], [66864, 66915], + [67072, 67382], [67392, 67413], [67424, 67431], [67584, 67589], 67592, [67594, 67637], [67639, 67640], + 67644, [67647, 67669], [67680, 67702], [67712, 67742], [67808, 67826], [67828, 67829], [67840, 67861], + [67872, 67897], [67968, 68023], [68030, 68031], 68096, [68112, 68115], [68117, 68119], [68121, 68147], + [68192, 68220], [68224, 68252], [68288, 68295], [68297, 68324], [68352, 68405], [68416, 68437], + [68448, 68466], [68480, 68497], [68608, 68680], [69635, 69687], [69763, 69807], [69840, 69864], + [69891, 69926], [69968, 70002], 70006, [70019, 70066], [70081, 70084], 70106, 70108, [70144, 70161], + [70163, 70187], [70272, 70278], 70280, [70282, 70285], [70287, 70301], [70303, 70312], [70320, 70366], + [70405, 70412], [70415, 70416], [70419, 70440], [70442, 70448], [70450, 70451], [70453, 70457], 70461, + 70480, [70493, 70497], [70656, 70708], [70727, 70730], [70784, 70831], [70852, 70853], 70855, + [71040, 71086], [71128, 71131], [71168, 71215], 71236, [71296, 71338], [71424, 71449], 71935, 72192, + [72203, 72242], 72250, 72272, [72284, 72323], [72326, 72329], [72384, 72440], [72704, 72712], + [72714, 72750], 72768, [72818, 72847], [72960, 72966], [72968, 72969], [72971, 73008], 73030, + [73728, 74649], [74880, 75075], [77824, 78894], [82944, 83526], [92160, 92728], [92736, 92766], + [92880, 92909], [92928, 92975], [93027, 93047], [93053, 93071], [93952, 94020], 94032, 94208, + 100332, [100352, 101106], [110592, 110878], [110960, 111355], [113664, 113770], [113776, 113788], + [113792, 113800], [113808, 113817], [124928, 125124], [126464, 126467], [126469, 126495], + [126497, 126498], 126500, 126503, [126505, 126514], [126516, 126519], 126521, 126523, 126530, + 126535, 126537, 126539, [126541, 126543], [126545, 126546], 126548, 126551, 126553, 126555, 126557, + 126559, [126561, 126562], 126564, [126567, 126570], [126572, 126578], [126580, 126583], + [126585, 126588], 126590, [126592, 126601], [126603, 126619], [126625, 126627], [126629, 126633], + [126635, 126651], 131072, 173782, 173824, 177972, 177984, 178205, 178208, 183969, 183984, 191456, + [194560, 195101]]; + +export const unicodeLm: UnicodeRangeTable = [[688, 705], [710, 721], [736, 740], 748, 750, 884, 890, 1369, + 1600, [1765, 1766], [2036, 2037], 2042, 2074, 2084, 2088, 2417, 3654, 3782, 4348, 6103, 6211, 6823, + [7288, 7293], [7468, 7530], 7544, [7579, 7615], 8305, 8319, [8336, 8348], [11388, 11389], 11631, 11823, + 12293, [12337, 12341], 12347, [12445, 12446], [12540, 12542], 40981, [42232, 42237], 42508, 42623, + [42652, 42653], [42775, 42783], 42864, 42888, [43000, 43001], 43471, 43494, 43632, 43741, + [43763, 43764], [43868, 43871], 65392, [65438, 65439], [92992, 92995], [94099, 94111], [94176, 94177]]; + +export const unicodeNl: UnicodeRangeTable = [[5870, 5872], [8544, 8578], [8581, 8584], 12295, [12321, 12329], + [12344, 12346], [42726, 42735], [65856, 65908], 66369, 66378, [66513, 66517], [74752, 74862]]; + +export const unicodeMn: UnicodeRangeTable = [[768, 879], [1155, 1159], [1425, 1469], 1471, [1473, 1474], + [1476, 1477], 1479, [1552, 1562], [1611, 1631], 1648, [1750, 1756], [1759, 1764], [1767, 1768], + [1770, 1773], 1809, [1840, 1866], [1958, 1968], [2027, 2035], [2070, 2073], [2075, 2083], [2085, 2087], + [2089, 2093], [2137, 2139], [2260, 2273], [2275, 2306], 2362, 2364, [2369, 2376], 2381, [2385, 2391], + [2402, 2403], 2433, 2492, [2497, 2500], 2509, [2530, 2531], [2561, 2562], 2620, [2625, 2626], [2631, 2632], + [2635, 2637], 2641, [2672, 2673], 2677, [2689, 2690], 2748, [2753, 2757], [2759, 2760], 2765, [2786, 2787], + [2810, 2815], 2817, 2876, 2879, [2881, 2884], 2893, 2902, [2914, 2915], 2946, 3008, 3021, 3072, + [3134, 3136], [3142, 3144], [3146, 3149], [3157, 3158], [3170, 3171], 3201, 3260, 3263, 3270, + [3276, 3277], [3298, 3299], [3328, 3329], [3387, 3388], [3393, 3396], 3405, [3426, 3427], 3530, + [3538, 3540], 3542, 3633, [3636, 3642], [3655, 3662], 3761, [3764, 3769], [3771, 3772], [3784, 3789], + [3864, 3865], 3893, 3895, 3897, [3953, 3966], [3968, 3972], [3974, 3975], [3981, 3991], [3993, 4028], + 4038, [4141, 4144], [4146, 4151], [4153, 4154], [4157, 4158], [4184, 4185], [4190, 4192], [4209, 4212], + 4226, [4229, 4230], 4237, 4253, [4957, 4959], [5906, 5908], [5938, 5940], [5970, 5971], [6002, 6003], + [6068, 6069], [6071, 6077], 6086, [6089, 6099], 6109, [6155, 6157], [6277, 6278], 6313, [6432, 6434], + [6439, 6440], 6450, [6457, 6459], [6679, 6680], 6683, 6742, [6744, 6750], 6752, 6754, [6757, 6764], + [6771, 6780], 6783, [6832, 6845], [6912, 6915], 6964, [6966, 6970], 6972, 6978, [7019, 7027], + [7040, 7041], [7074, 7077], [7080, 7081], [7083, 7085], 7142, [7144, 7145], 7149, [7151, 7153], + [7212, 7219], [7222, 7223], [7376, 7378], [7380, 7392], [7394, 7400], 7405, 7412, [7416, 7417], + [7616, 7673], [7675, 7679], [8400, 8412], 8417, [8421, 8432], [11503, 11505], 11647, [11744, 11775], + [12330, 12333], [12441, 12442], 42607, [42612, 42621], [42654, 42655], [42736, 42737], 43010, 43014, + 43019, [43045, 43046], [43204, 43205], [43232, 43249], [43302, 43309], [43335, 43345], [43392, 43394], + 43443, [43446, 43449], 43452, 43493, [43561, 43566], [43569, 43570], [43573, 43574], 43587, 43596, + 43644, 43696, [43698, 43700], [43703, 43704], [43710, 43711], 43713, [43756, 43757], 43766, 44005, + 44008, 44013, 64286, [65024, 65039], [65056, 65071], 66045, 66272, [66422, 66426], [68097, 68099], + [68101, 68102], [68108, 68111], [68152, 68154], 68159, [68325, 68326], 69633, [69688, 69702], + [69759, 69761], [69811, 69814], [69817, 69818], [69888, 69890], [69927, 69931], [69933, 69940], + 70003, [70016, 70017], [70070, 70078], [70090, 70092], [70191, 70193], 70196, [70198, 70199], 70206, + 70367, [70371, 70378], [70400, 70401], 70460, 70464, [70502, 70508], [70512, 70516], [70712, 70719], + [70722, 70724], 70726, [70835, 70840], 70842, [70847, 70848], [70850, 70851], [71090, 71093], + [71100, 71101], [71103, 71104], [71132, 71133], [71219, 71226], 71229, [71231, 71232], 71339, 71341, + [71344, 71349], 71351, [71453, 71455], [71458, 71461], [71463, 71467], [72193, 72198], [72201, 72202], + [72243, 72248], [72251, 72254], 72263, [72273, 72278], [72281, 72283], [72330, 72342], [72344, 72345], + [72752, 72758], [72760, 72765], 72767, [72850, 72871], [72874, 72880], [72882, 72883], [72885, 72886], + [73009, 73014], 73018, [73020, 73021], [73023, 73029], 73031, [92912, 92916], [92976, 92982], + [94095, 94098], [113821, 113822], [119143, 119145], [119163, 119170], [119173, 119179], [119210, 119213], + [119362, 119364], [121344, 121398], [121403, 121452], 121461, 121476, [121499, 121503], [121505, 121519], + [122880, 122886], [122888, 122904], [122907, 122913], [122915, 122916], [122918, 122922], [125136, 125142], + [125252, 125258], [917760, 917999]]; + +export const unicodeMc: UnicodeRangeTable = [2307, 2363, [2366, 2368], [2377, 2380], [2382, 2383], [2434, 2435], + [2494, 2496], [2503, 2504], [2507, 2508], 2519, 2563, [2622, 2624], 2691, [2750, 2752], 2761, [2763, 2764], + [2818, 2819], 2878, 2880, [2887, 2888], [2891, 2892], 2903, [3006, 3007], [3009, 3010], [3014, 3016], + [3018, 3020], 3031, [3073, 3075], [3137, 3140], [3202, 3203], 3262, [3264, 3268], [3271, 3272], + [3274, 3275], [3285, 3286], [3330, 3331], [3390, 3392], [3398, 3400], [3402, 3404], 3415, [3458, 3459], + [3535, 3537], [3544, 3551], [3570, 3571], [3902, 3903], 3967, [4139, 4140], 4145, 4152, [4155, 4156], + [4182, 4183], [4194, 4196], [4199, 4205], [4227, 4228], [4231, 4236], 4239, [4250, 4252], 6070, [6078, 6085], + [6087, 6088], [6435, 6438], [6441, 6443], [6448, 6449], [6451, 6456], [6681, 6682], 6741, 6743, 6753, + [6755, 6756], [6765, 6770], 6916, 6965, 6971, [6973, 6977], [6979, 6980], 7042, 7073, [7078, 7079], 7082, + 7143, [7146, 7148], 7150, [7154, 7155], [7204, 7211], [7220, 7221], 7393, [7410, 7411], 7415, [12334, 12335], + [43043, 43044], 43047, [43136, 43137], [43188, 43203], [43346, 43347], 43395, [43444, 43445], [43450, 43451], + [43453, 43456], [43567, 43568], [43571, 43572], 43597, 43643, 43645, 43755, [43758, 43759], 43765, + [44003, 44004], [44006, 44007], [44009, 44010], 44012, 69632, 69634, 69762, [69808, 69810], [69815, 69816], + 69932, 70018, [70067, 70069], [70079, 70080], [70188, 70190], [70194, 70195], 70197, [70368, 70370], + [70402, 70403], [70462, 70463], [70465, 70468], [70471, 70472], [70475, 70477], 70487, [70498, 70499], + [70709, 70711], [70720, 70721], 70725, [70832, 70834], 70841, [70843, 70846], 70849, [71087, 71089], + [71096, 71099], 71102, [71216, 71218], [71227, 71228], 71230, 71340, [71342, 71343], 71350, [71456, 71457], + 71462, [72199, 72200], 72249, [72279, 72280], 72343, 72751, 72766, 72873, 72881, 72884, [94033, 94078], + [119141, 119142], [119149, 119154]]; + +export const unicodeNd: UnicodeRangeTable = [[48, 57], [1632, 1641], [1776, 1785], [1984, 1993], [2406, 2415], + [2534, 2543], [2662, 2671], [2790, 2799], [2918, 2927], [3046, 3055], [3174, 3183], [3302, 3311], [3430, 3439], + [3558, 3567], [3664, 3673], [3792, 3801], [3872, 3881], [4160, 4169], [4240, 4249], [6112, 6121], [6160, 6169], + [6470, 6479], [6608, 6617], [6784, 6793], [6800, 6809], [6992, 7001], [7088, 7097], [7232, 7241], [7248, 7257], + [42528, 42537], [43216, 43225], [43264, 43273], [43472, 43481], [43504, 43513], [43600, 43609], [44016, 44025], + [65296, 65305], [66720, 66729], [69734, 69743], [69872, 69881], [69942, 69951], [70096, 70105], [70384, 70393], + [70736, 70745], [70864, 70873], [71248, 71257], [71360, 71369], [71472, 71481], [71904, 71913], [72784, 72793], + [73040, 73049], [92768, 92777], [93008, 93017], [120782, 120831], [125264, 125273]]; + +export const unicodePc: UnicodeRangeTable = [95, [8255, 8256], 8276, [65075, 65076], [65101, 65103], 65343]; diff --git a/server/src/pyright.ts b/server/src/pyright.ts new file mode 100644 index 000000000..c624452f8 --- /dev/null +++ b/server/src/pyright.ts @@ -0,0 +1,154 @@ +/* +* pyright.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Command-line entry point for pyright type checker. +*/ + +// Add the start timer at the very top of the file, before we import other modules. +import { timingStats } from './common/timing'; + +import * as commandLineArgs from 'command-line-args'; +// tslint:disable-next-line +import { CommandLineOptions, OptionDefinition } from 'command-line-args'; +import * as process from 'process'; + +import { AnalyzerService } from './analyzer/service'; +import { CommandLineOptions as PyrightCommandLineOptions } from './common/commandLineOptions'; +import { DiagnosticCategory } from './common/diagnostic'; +import { FileDiagnostics } from './common/diagnosticSink'; +import { combinePaths, normalizePath } from './common/pathUtils'; + +const toolName = 'pyright'; + +// Stash the base directory into a global variable. +(global as any).__basedir = __dirname; + +enum ExitStatus { + Success = 0, + DiagnosticsPresent_OutputsSkipped = 1, + DiagnosticsPresent_OutputsGenerated = 2 +} + +function processArgs() { + const optionDefinitions: OptionDefinition[] = [ + { name: 'files', type: String, multiple: true, defaultOption: true }, + { name: 'help', alias: 'h', type: Boolean }, + { name: 'project', alias: 'p', type: String }, + { name: 'python-path', alias: 'P', type: String }, + { name: 'typeshed-path', alias: 't', type: String }, + { name: 'venv-path', alias: 'v', type: String }, + { name: 'watch', alias: 'w', type: Boolean } + ]; + + let args: CommandLineOptions; + + try { + args = commandLineArgs(optionDefinitions); + } catch (err) { + let argErr: { name: string; optionName: string } = err; + if (argErr && argErr.optionName) { + console.error(`Unexpected option ${ argErr.optionName }.\n${ toolName } --help for usage`); + return; + } + + console.error(`Unexpected error\n${ toolName } --help for usage`); + return; + } + + if (args.help !== undefined) { + printUsage(); + return; + } + + let options = new PyrightCommandLineOptions(process.cwd()); + options.fileSpecs = args.files; + + if (args.project) { + options.configFilePath = combinePaths(process.cwd(), normalizePath(args.project)); + } + + if (args['venv-path']) { + options.venvPath = combinePaths(process.cwd(), normalizePath(args['venv-path'])); + } + if (args['python-path']) { + options.pythonPath = combinePaths(process.cwd(), normalizePath(args['python-path'])); + } + if (args['typeshed-path']) { + options.typeshedPath = combinePaths(process.cwd(), normalizePath(args['typeshed-path'])); + } + + let watch = !!args.watch; + options.watch = watch; + + let service = new AnalyzerService(); + + service.setCompletionCallback(results => { + if (results.fatalErrorOccurred) { + process.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + + if (results.diagnostics.length > 0) { + reportDiagnostics(results.diagnostics); + } + + timingStats.print(console); + + if (!watch) { + process.exit(ExitStatus.DiagnosticsPresent_OutputsGenerated); + } + }); + + // This will trigger the analyzer. + service.setOptions(options); + + // Sleep indefinitely. + let brokenPromise = new Promise(resolve => { + // Do nothing. + }); + brokenPromise.then().catch(); +} + +function printUsage() { + console.log( + 'Usage: ' + toolName + ' [options] file...\n' + + ' Options:\n' + + ' -h,--help Show this help message\n' + + ' -P,--python-path DIRECTORY Directory that contains the python environment\n' + + ' -p,--project FILE OR DIRECTORY Use the configuration file at this location\n' + + ' -t,--typeshed-path DIRECTORY Use typeshed type stubs at this location\n' + + ' -v,--venv-path DIRECTORY Directory that contains virtual environments\n' + + ' -w,--watch Continue to run and watch for changes\n' + ); +} + +function reportDiagnostics(fileDiagnostics: FileDiagnostics[]) { + let errorCount = 0; + let warningCount = 0; + + fileDiagnostics.forEach(fileDiagnostics => { + if (fileDiagnostics.diagnostics.length > 0) { + console.log(`${ fileDiagnostics.filePath }`); + fileDiagnostics.diagnostics.forEach(diag => { + let message = ` ${ diag.message }`; + if (diag.range) { + message += ` (${ diag.range.start.line + 1 }, ${ diag.range.start.column + 1 })`; + } + console.log(message); + + if (diag.category === DiagnosticCategory.Error) { + errorCount++; + } else if (diag.category === DiagnosticCategory.Warning) { + warningCount++; + } + }); + } + }); + + console.log( + `${ errorCount.toString() } ${ errorCount === 1 ? 'error' : 'errors' }, ` + + `${ warningCount.toString() } ${ warningCount === 1 ? 'warning' : 'warnings' } `); +} + +processArgs(); diff --git a/server/src/server.ts b/server/src/server.ts new file mode 100644 index 000000000..e1fd58dac --- /dev/null +++ b/server/src/server.ts @@ -0,0 +1,248 @@ +/* +* server.ts +* +* Implements pyright language server. +*/ + +import { + createConnection, Diagnostic, DiagnosticSeverity, IConnection, + InitializeResult, IPCMessageReader, IPCMessageWriter, Location, + MarkupContent, Position, Range, TextDocuments +} from 'vscode-languageserver'; + +import { AnalyzerService } from './analyzer/service'; +import { CommandLineOptions } from './common/commandLineOptions'; +import { Diagnostic as AnalyzerDiagnostic, DiagnosticCategory, DiagnosticTextPosition, + DiagnosticTextRange } from './common/diagnostic'; +import { combinePaths, normalizePath } from './common/pathUtils'; + +interface PythonSettings { + venvPath?: string; + pythonPath?: string; +} + +interface Settings { + python: PythonSettings; +} + +// Stash the base directory into a global variable. +(global as any).__basedir = __dirname; + +// Create a connection for the server. The connection uses Node's IPC as a transport +let _connection: IConnection = createConnection(new IPCMessageReader(process), new IPCMessageWriter(process)); + +_connection.console.log('Pyright language server starting'); + +// Create a simple text document manager. The text document manager +// supports full document sync only. +let _documents: TextDocuments = new TextDocuments(); + +// Allocate the analyzer service instance. +let _analyzerService: AnalyzerService = new AnalyzerService(_connection.console); + +// Root path of the workspace. +let _rootPath = '/'; + +// Make the text document manager listen on the connection +// for open, change and close text document events. +_documents.listen(_connection); + +// After the server has started the client sends an initialize request. The server receives +// in the passed params the rootPath of the workspace plus the client capabilities. +_connection.onInitialize((params): InitializeResult => { + _rootPath = params.rootPath || '/'; + + // Don't allow the analysis engine to go too long without + // reporting results. This will keep it responsive. + _analyzerService.setMaxAnalysisDuration(50); + + _analyzerService.setCompletionCallback(results => { + results.diagnostics.forEach(fileDiag => { + let diagnostics = _convertDiagnostics(fileDiag.diagnostics); + + // Send the computed diagnostics to the client. + _connection.sendDiagnostics({ + uri: _convertPathToUri(fileDiag.filePath), + diagnostics + }); + }); + }); + + return { + capabilities: { + // Tell the client that the server works in FULL text document + // sync mode (as opposed to incremental). + textDocumentSync: _documents.syncKind, + definitionProvider: true, + hoverProvider: true + } + }; +}); + +// The content of a text document has changed. This event is emitted +// when the text document first opened or when its content has changed. +_documents.onDidChangeContent(change => { + let filePath = _convertUriToPath(change.document.uri); + _connection.console.log(`File "${ filePath }" changed -- marking dirty`); + _analyzerService.markFilesChanged([filePath]); + updateOptionsAndRestartService(); +}); + +_connection.onDidChangeConfiguration(change => { + _connection.console.log(`Received updated settings.`); + updateOptionsAndRestartService(change.settings); +}); + +_connection.onDefinition(params => { + let filePath = _convertUriToPath(params.textDocument.uri); + + let position: DiagnosticTextPosition = { + line: params.position.line, + column: params.position.character + }; + + let location = _analyzerService.getDefinitionForPosition(filePath, position); + if (!location) { + return undefined; + } + return Location.create(_convertPathToUri(location.path), _convertRange(location.range)); +}); + +_connection.onHover(params => { + let filePath = _convertUriToPath(params.textDocument.uri); + + let position: DiagnosticTextPosition = { + line: params.position.line, + column: params.position.character + }; + + let hoverMarkdown = _analyzerService.getHoverForPosition(filePath, position); + if (!hoverMarkdown) { + return undefined; + } + let markupContent: MarkupContent = { + kind: 'markdown', + value: hoverMarkdown + }; + return { contents: markupContent }; +}); + +function updateOptionsAndRestartService(settings?: Settings) { + let commandLineOptions = new CommandLineOptions(_rootPath); + commandLineOptions.watch = true; + if (settings && settings.python) { + if (settings.python.venvPath) { + commandLineOptions.venvPath = combinePaths(_rootPath, + normalizePath(settings.python.venvPath)); + } + if (settings.python.pythonPath) { + commandLineOptions.pythonPath = combinePaths(_rootPath, + normalizePath(settings.python.pythonPath)); + } + } + + _analyzerService.setOptions(commandLineOptions); +} + +function _convertDiagnostics(diags: AnalyzerDiagnostic[]): Diagnostic[] { + return diags.map(diag => { + let severity = diag.category === DiagnosticCategory.Error ? + DiagnosticSeverity.Error : DiagnosticSeverity.Warning; + + return Diagnostic.create(_convertRange(diag.range), diag.message, severity); + }); +} + +function _convertRange(range?: DiagnosticTextRange): Range { + if (!range) { + return Range.create(_convertPosition(), _convertPosition()); + } + return Range.create(_convertPosition(range.start), _convertPosition(range.end)); +} + +function _convertPosition(position?: DiagnosticTextPosition): Position { + if (!position) { + return Position.create(0, 0); + } + return Position.create(position.line, position.column); +} + +_connection.onDidOpenTextDocument(params => { + let filePath = _convertUriToPath(params.textDocument.uri); + _connection.console.log(`${ filePath } opened.`); + _analyzerService.setFileOpened( + filePath, + params.textDocument.version, + params.textDocument.text); +}); + +_connection.onDidChangeTextDocument(params => { + let filePath = _convertUriToPath(params.textDocument.uri); + _connection.console.log( + `${ filePath } changed (version ${ params.textDocument.version }).`); + _analyzerService.updateOpenFileContents( + filePath, + params.textDocument.version, + params.contentChanges[0].text); +}); + +_connection.onDidCloseTextDocument(params => { + _connection.console.log(`${params.textDocument.uri} closed.`); + + _analyzerService.setFileClosed( + _convertUriToPath(params.textDocument.uri)); +}); + +function _convertUriToPath(uri: string): string { + const fileScheme = 'file://'; + if (uri.startsWith(fileScheme)) { + return uri.substr(fileScheme.length); + } + + return uri; +} + +function _convertPathToUri(path: string): string { + return 'file://' + path; +} + +/* +_connection.onExecuteCommand((cmdParams: ExecuteCommandParams) => { + return new ResponseError(1, 'Unsupported command'); +}); + +// This handler provides the initial list of the completion items. +_connection.onCompletion((_textDocumentPosition: TextDocumentPositionParams): CompletionItem[] => { + // The pass parameter contains the position of the text document in + // which code complete got requested. For the example we ignore this + // info and always provide the same completion items. + return [ + { + label: 'TypeScript', + kind: CompletionItemKind.Text, + data: 1 + }, + { + label: 'JavaScript', + kind: CompletionItemKind.Text, + data: 2 + } + ] +}); + +// This handler resolve additional information for the item selected in +// the completion list. +_connection.onCompletionResolve((item: CompletionItem): CompletionItem => { + if (item.data === 1) { + item.detail = 'TypeScript details', + item.documentation = 'TypeScript documentation' + } else if (item.data === 2) { + item.detail = 'JavaScript details', + item.documentation = 'JavaScript documentation' + } + return item; +}); +*/ + +// Listen on the connection +_connection.listen(); diff --git a/server/src/tests/config.test.ts b/server/src/tests/config.test.ts new file mode 100644 index 000000000..f012ff820 --- /dev/null +++ b/server/src/tests/config.test.ts @@ -0,0 +1,122 @@ +/* +* config.test.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Unit tests for parsing of pyrightconfig.json files. +*/ + +import * as assert from 'assert'; + +import { AnalyzerService } from '../analyzer/service'; +import { CommandLineOptions } from '../common/commandLineOptions'; +import { ConfigOptions, ExecutionEnvironment } from '../common/configOptions'; +import { NullConsole } from '../common/console'; +import { combinePaths } from '../common/pathUtils'; + +test('FindFilesWithConfigFile', () => { + let service = new AnalyzerService(new NullConsole()); + let commandLineOptions = new CommandLineOptions(process.cwd()); + commandLineOptions.configFilePath = 'src/tests/samples/project1'; + + let configOptions = service.test_getConfigOptions(commandLineOptions); + service.setOptions(commandLineOptions); + + // The config file specifies a single file spec (a directory). + assert.equal(configOptions.include.length, 1); + assert.equal(configOptions.projectRoot, + combinePaths(process.cwd(), commandLineOptions.configFilePath)); + + let fileList = service.test_getFileNamesFromFileSpecs(); + + // The config file specifies a subdirectory, so we should find + // only two of the three "*.py" files present in the project + // directory. + assert.equal(fileList.length, 2); +}); + +test('FileSpecNotAnArray', () => { + let nullConsole = new NullConsole(); + let service = new AnalyzerService(nullConsole); + let commandLineOptions = new CommandLineOptions(process.cwd()); + commandLineOptions.configFilePath = 'src/tests/samples/project2'; + service.setOptions(commandLineOptions); + + service.test_getConfigOptions(commandLineOptions); + + // The method should return a default config and log an error. + assert(nullConsole.logCount > 0); +}); + +test('FileSpecNotAString', () => { + let nullConsole = new NullConsole(); + let service = new AnalyzerService(nullConsole); + let commandLineOptions = new CommandLineOptions(process.cwd()); + commandLineOptions.configFilePath = 'src/tests/samples/project3'; + service.setOptions(commandLineOptions); + + service.test_getConfigOptions(commandLineOptions); + + // The method should return a default config and log an error. + assert(nullConsole.logCount > 0); +}); + +test('SomeFileSpecsAreInvalid', () => { + let nullConsole = new NullConsole(); + let service = new AnalyzerService(nullConsole); + let commandLineOptions = new CommandLineOptions(process.cwd()); + commandLineOptions.configFilePath = 'src/tests/samples/project4'; + service.setOptions(commandLineOptions); + + let configOptions = service.test_getConfigOptions(commandLineOptions); + + // The config file specifies four file specs in the include array + // and one in the exclude array. + assert.equal(configOptions.include.length, 4); + assert.equal(configOptions.exclude.length, 1); + assert.equal(configOptions.projectRoot, + combinePaths(process.cwd(), commandLineOptions.configFilePath)); + + let fileList = service.test_getFileNamesFromFileSpecs(); + + // We should receive two final files that match the include/exclude rules. + assert.equal(fileList.length, 2); +}); + +test('ConfigBadJson', () => { + let nullConsole = new NullConsole(); + let service = new AnalyzerService(nullConsole); + let commandLineOptions = new CommandLineOptions(process.cwd()); + commandLineOptions.configFilePath = 'src/tests/samples/project5'; + service.setOptions(commandLineOptions); + + service.test_getConfigOptions(commandLineOptions); + + // The method should return a default config and log an error. + assert(nullConsole.logCount > 0); +}); + +test('FindExecEnv1', () => { + let configOptions = new ConfigOptions(process.cwd()); + + // Build a config option with three execution environments. + let execEnv1 = new ExecutionEnvironment('src/foo'); + configOptions.executionEnvironments.push(execEnv1); + let execEnv2 = new ExecutionEnvironment('src'); + configOptions.executionEnvironments.push(execEnv2); + let execEnv3 = new ExecutionEnvironment(); + configOptions.executionEnvironments.push(execEnv3); + + let file1 = combinePaths(process.cwd(), 'src/foo/bar.py'); + assert.equal(configOptions.findExecEnvironment(file1), execEnv1); + let file2 = combinePaths(process.cwd(), 'src/foo2/bar.py'); + assert.equal(configOptions.findExecEnvironment(file2), execEnv2); + let file3 = combinePaths(process.cwd(), 'src2/foo2/bar.py'); + assert.equal(configOptions.findExecEnvironment(file3), execEnv3); + + // If none of the execution environments matched, we should get + // a default environment with the root equal to that of the config. + let file4 = '/nothing/bar.py'; + let defaultExecEnv = configOptions.findExecEnvironment(file4); + assert.equal(defaultExecEnv.root, '/nothing'); +}); diff --git a/server/src/tests/parser.test.ts b/server/src/tests/parser.test.ts new file mode 100644 index 000000000..25a067c51 --- /dev/null +++ b/server/src/tests/parser.test.ts @@ -0,0 +1,64 @@ +/* +* parser.test.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Unit tests for Python parser. +*/ + +import * as assert from 'assert'; +import * as fs from 'fs'; +import * as path from 'path'; + +import { PostParseWalker } from '../analyzer/postParseWalker'; +import { DiagnosticSink, TextRangeDiagnosticSink } from '../common/diagnosticSink'; +import { ModuleNode } from '../parser/parseNodes'; +import { ParseOptions, Parser } from '../parser/parser'; +import { TestWalker } from './testWalker'; + +function _parseText(text: string, diagSink: DiagnosticSink): ModuleNode { + const parser = new Parser(); + let parseOptions = new ParseOptions(); + let parseResults = parser.parseSourceFile(text, parseOptions, diagSink); + let textRangeDiagSink = new TextRangeDiagnosticSink(parseResults.lines, + diagSink.diagnostics); + + // Link the parents. + let parentWalker = new PostParseWalker(textRangeDiagSink, + parseResults.parseTree, false); + parentWalker.analyze(); + + // Walk the AST to verify internal consistency. + let testWalker = new TestWalker(); + testWalker.walk(parseResults.parseTree); + + return parseResults.parseTree; +} + +function readTextFile(fileName: string): string { + let filePath = path.resolve(path.dirname(module.filename), `./samples/${ fileName }`); + + try { + return fs.readFileSync(filePath, { encoding: 'utf8' }); + } catch { + console.error(`Could not read file "${ fileName }"`); + return ''; + } +} + +test('Empty', () => { + let diagSink = new DiagnosticSink(); + let ast = _parseText('', diagSink); + + assert.equal(diagSink.diagnostics.length, 0); + assert.equal(ast.statements.length, 0); +}); + +test('Sample1', () => { + let fileText = readTextFile('sample1.py'); + let diagSink = new DiagnosticSink(); + let ast = _parseText(fileText, diagSink); + + assert.equal(diagSink.diagnostics.length, 0); + assert.equal(ast.statements.length, 4); +}); diff --git a/server/src/tests/samples/project1/pyrightconfig.json b/server/src/tests/samples/project1/pyrightconfig.json new file mode 100644 index 000000000..1ed3a3933 --- /dev/null +++ b/server/src/tests/samples/project1/pyrightconfig.json @@ -0,0 +1,5 @@ +{ + "include": [ + "subfolder1" + ] +} diff --git a/server/src/tests/samples/project1/sample1.py b/server/src/tests/samples/project1/sample1.py new file mode 100644 index 000000000..e69de29bb diff --git a/server/src/tests/samples/project1/subfolder1/sample2.py b/server/src/tests/samples/project1/subfolder1/sample2.py new file mode 100644 index 000000000..e69de29bb diff --git a/server/src/tests/samples/project1/subfolder1/subfolder1-1/sample3.py b/server/src/tests/samples/project1/subfolder1/subfolder1-1/sample3.py new file mode 100644 index 000000000..e69de29bb diff --git a/server/src/tests/samples/project2/pyrightconfig.json b/server/src/tests/samples/project2/pyrightconfig.json new file mode 100644 index 000000000..2fefc82b6 --- /dev/null +++ b/server/src/tests/samples/project2/pyrightconfig.json @@ -0,0 +1,3 @@ +{ + "files": "NotAnArray.py" +} diff --git a/server/src/tests/samples/project3/pyrightconfig.json b/server/src/tests/samples/project3/pyrightconfig.json new file mode 100644 index 000000000..561317c6b --- /dev/null +++ b/server/src/tests/samples/project3/pyrightconfig.json @@ -0,0 +1,7 @@ +{ + "files": [ + { + "NotAString": "Bad" + } + ] +} diff --git a/server/src/tests/samples/project4/presentfile.py b/server/src/tests/samples/project4/presentfile.py new file mode 100644 index 000000000..e69de29bb diff --git a/server/src/tests/samples/project4/pyrightconfig.json b/server/src/tests/samples/project4/pyrightconfig.json new file mode 100644 index 000000000..562e7702d --- /dev/null +++ b/server/src/tests/samples/project4/pyrightconfig.json @@ -0,0 +1,11 @@ +{ + "include": [ + "missingfile.py", + "presentfile.py", + "missingdirectory", + "subfolder" + ], + "exclude": [ + "subfolder/presentfile2.py" + ] +} diff --git a/server/src/tests/samples/project4/subfolder/presentfile2.py b/server/src/tests/samples/project4/subfolder/presentfile2.py new file mode 100644 index 000000000..e69de29bb diff --git a/server/src/tests/samples/project4/subfolder/presentfile3.py b/server/src/tests/samples/project4/subfolder/presentfile3.py new file mode 100644 index 000000000..e69de29bb diff --git a/server/src/tests/samples/project5/pyrightconfig.json b/server/src/tests/samples/project5/pyrightconfig.json new file mode 100644 index 000000000..d2cfcddc8 --- /dev/null +++ b/server/src/tests/samples/project5/pyrightconfig.json @@ -0,0 +1,4 @@ +{ + "files": [ + // Bad json +} diff --git a/server/src/tests/samples/sample1.py b/server/src/tests/samples/sample1.py new file mode 100644 index 000000000..508b62c25 --- /dev/null +++ b/server/src/tests/samples/sample1.py @@ -0,0 +1,7 @@ + +# This file should parse without errors +a +b +c; d; e; +f;g + diff --git a/server/src/tests/samples/test_file1.py b/server/src/tests/samples/test_file1.py new file mode 100644 index 000000000..e69de29bb diff --git a/server/src/tests/sourceFile.test.ts b/server/src/tests/sourceFile.test.ts new file mode 100644 index 000000000..f42d9181e --- /dev/null +++ b/server/src/tests/sourceFile.test.ts @@ -0,0 +1,19 @@ +/* +* sourceFile.test.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Unit tests for pyright sourceFile module. +*/ + +import { SourceFile } from '../analyzer/sourceFile'; +import { ConfigOptions } from '../common/configOptions'; +import { combinePaths } from '../common/pathUtils'; + +test('Empty', () => { + let filePath = combinePaths(process.cwd(), 'tests/samples/test_file1.py'); + let sourceFile = new SourceFile(filePath, false); + let configOptions = new ConfigOptions(process.cwd()); + + sourceFile.parse(configOptions); +}); diff --git a/server/src/tests/testWalker.ts b/server/src/tests/testWalker.ts new file mode 100644 index 000000000..81f9eb523 --- /dev/null +++ b/server/src/tests/testWalker.ts @@ -0,0 +1,50 @@ +/* +* testWalker.ts +* +* Walks a parse tree to validate internal consistency and completeness. +*/ + +import * as assert from 'assert'; + +import { ParseTreeWalker } from '../analyzer/parseTreeWalker'; +import { ParseNode } from '../parser/parseNodes'; + +export class TestWalker extends ParseTreeWalker { + constructor() { + super(); + } + + visitNode(node: ParseNode): boolean { + let children = this.getChildren(node); + this._verifyParentChildLinks(node, children); + this._verifyChildRanges(node, children); + + return super.visitNode(node); + } + + // Make sure that all of the children point to their parent. + private _verifyParentChildLinks(node: ParseNode, children: ParseNode[]) { + children.forEach(child => { + assert.equal(child.parent, node); + }); + } + + // Verify that: + // Children are all contained within the parent + // Children have non-overlapping ranges + // Children are listed in increasing order + private _verifyChildRanges(node: ParseNode, children: ParseNode[]) { + let prevNode: ParseNode | undefined; + + children.forEach(child => { + // Make sure the child is contained within the parent. + assert(child.start >= node.start && child.end <= node.end); + if (prevNode) { + // Make sure the child is after the previous child. + assert(child.start >= prevNode.end); + } + + prevNode = child; + }); + } +} diff --git a/server/src/tests/tokenizer.test.ts b/server/src/tests/tokenizer.test.ts new file mode 100644 index 000000000..f2c997c0f --- /dev/null +++ b/server/src/tests/tokenizer.test.ts @@ -0,0 +1,753 @@ +/* +* tokenizer.test.ts +* Copyright (c) Microsoft Corporation. All rights reserved. +* Author: Eric Traut +* +* Based on code from vscode-python repository: +* https://github.com/Microsoft/vscode-python +* +* Unit tests for Python tokenizer. +*/ + +import * as assert from 'assert'; + +import { Tokenizer } from '../parser/tokenizer'; +import { DedentToken, IdentifierToken, IndentToken, NewLineToken, NewLineType, + NumberToken, OperatorToken, OperatorType, TokenType } from '../parser/tokenizerTypes'; + +const _implicitTokenCount = 2; +const _implicitTokenCountNoImplicitNewLine = 1; + +test('Empty', () => { + const t = new Tokenizer(); + const results = t.tokenize(''); + assert.equal(results.tokens.count, 0 + _implicitTokenCount); + assert.equal(results.tokens.length, 0); + assert.equal(results.tokens.getItemAt(0).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(1).type, TokenType.EndOfStream); +}); + +test('NewLines', () => { + const t = new Tokenizer(); + const results = t.tokenize('\na\r\nb\r'); + assert.equal(results.tokens.count, 5 + _implicitTokenCountNoImplicitNewLine); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.NewLine); + assert.equal((results.tokens.getItemAt(0) as NewLineToken).newLineType, NewLineType.LineFeed); + assert.equal(results.tokens.getItemAt(2).type, TokenType.NewLine); + assert.equal((results.tokens.getItemAt(2) as NewLineToken).newLineType, NewLineType.CarriageReturnLineFeed); + assert.equal(results.tokens.getItemAt(4).type, TokenType.NewLine); + assert.equal((results.tokens.getItemAt(4) as NewLineToken).newLineType, NewLineType.CarriageReturn); + assert.equal(results.tokens.getItemAt(5).type, TokenType.EndOfStream); +}); + +test('ParenNewLines', () => { + const t = new Tokenizer(); + const results = t.tokenize('\n(\n(\n)\n)\n)\n'); + assert.equal(results.tokens.count, 8 + _implicitTokenCountNoImplicitNewLine); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(1).type, TokenType.OpenParenthesis); + assert.equal(results.tokens.getItemAt(2).type, TokenType.OpenParenthesis); + assert.equal(results.tokens.getItemAt(3).type, TokenType.CloseParenthesis); + assert.equal(results.tokens.getItemAt(4).type, TokenType.CloseParenthesis); + assert.equal(results.tokens.getItemAt(5).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(6).type, TokenType.CloseParenthesis); +}); + +test('BraceNewLines', () => { + const t = new Tokenizer(); + const results = t.tokenize('\n{\n{\n}\n}\n}\n'); + assert.equal(results.tokens.count, 8 + _implicitTokenCountNoImplicitNewLine); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(1).type, TokenType.OpenCurlyBrace); + assert.equal(results.tokens.getItemAt(2).type, TokenType.OpenCurlyBrace); + assert.equal(results.tokens.getItemAt(3).type, TokenType.CloseCurlyBrace); + assert.equal(results.tokens.getItemAt(4).type, TokenType.CloseCurlyBrace); + assert.equal(results.tokens.getItemAt(5).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(6).type, TokenType.CloseCurlyBrace); +}); + +test('BracketNewLines', () => { + const t = new Tokenizer(); + const results = t.tokenize('\n[\n[\n]\n]\n]\n'); + assert.equal(results.tokens.count, 8 + _implicitTokenCountNoImplicitNewLine); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(1).type, TokenType.OpenBracket); + assert.equal(results.tokens.getItemAt(2).type, TokenType.OpenBracket); + assert.equal(results.tokens.getItemAt(3).type, TokenType.CloseBracket); + assert.equal(results.tokens.getItemAt(4).type, TokenType.CloseBracket); + assert.equal(results.tokens.getItemAt(5).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(6).type, TokenType.CloseBracket); +}); + +test('NewLinesWithWhiteSpace', () => { + const t = new Tokenizer(); + const results = t.tokenize(' \na \r\nb \rc'); + assert.equal(results.tokens.count, 6 + _implicitTokenCount); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(0).length, 1); + assert.equal((results.tokens.getItemAt(0) as NewLineToken).newLineType, NewLineType.LineFeed); + + assert.equal(results.tokens.getItemAt(2).type, TokenType.NewLine); + assert.equal((results.tokens.getItemAt(2) as NewLineToken).newLineType, NewLineType.CarriageReturnLineFeed); + assert.equal(results.tokens.getItemAt(2).length, 2); + + assert.equal(results.tokens.getItemAt(4).type, TokenType.NewLine); + assert.equal((results.tokens.getItemAt(4) as NewLineToken).newLineType, NewLineType.CarriageReturn); + assert.equal(results.tokens.getItemAt(4).length, 1); + + assert.equal(results.tokens.getItemAt(6).type, TokenType.NewLine); + assert.equal((results.tokens.getItemAt(6) as NewLineToken).newLineType, NewLineType.Implied); + assert.equal(results.tokens.getItemAt(6).length, 0); +}); + +test('NewLineEliding', () => { + const t = new Tokenizer(); + const results = t.tokenize('\n\r\n\r'); + assert.equal(results.tokens.count, 1 + _implicitTokenCountNoImplicitNewLine); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(0).length, 1); + assert.equal((results.tokens.getItemAt(0) as NewLineToken).newLineType, NewLineType.LineFeed); +}); + +test('LineContinuation', () => { + const t = new Tokenizer(); + const results = t.tokenize('foo \\\na \\\r\nb \\\rc \\ \n # Comment \\\n'); + assert.equal(results.tokens.count, 6 + _implicitTokenCountNoImplicitNewLine); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(1).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(2).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(3).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(4).type, TokenType.Invalid); + assert.equal(results.tokens.getItemAt(5).type, TokenType.NewLine); +}); + +test('Dots', () => { + const t = new Tokenizer(); + const results = t.tokenize('. .. ... ....'); + assert.equal(results.tokens.count, 6 + _implicitTokenCount); + assert.equal(results.tokens.getItemAt(0).type, TokenType.Dot); + assert.equal(results.tokens.getItemAt(1).type, TokenType.Dot); + assert.equal(results.tokens.getItemAt(2).type, TokenType.Dot); + assert.equal(results.tokens.getItemAt(3).type, TokenType.Ellipsis); + assert.equal(results.tokens.getItemAt(4).type, TokenType.Ellipsis); + assert.equal(results.tokens.getItemAt(5).type, TokenType.Dot); +}); + +test('PunctiationTokens', () => { + const t = new Tokenizer(); + const results = t.tokenize(':;,()[]{}->'); + assert.equal(results.tokens.count, 10 + _implicitTokenCount); + assert.equal(results.tokens.getItemAt(0).type, TokenType.Colon); + assert.equal(results.tokens.getItemAt(1).type, TokenType.Semicolon); + assert.equal(results.tokens.getItemAt(2).type, TokenType.Comma); + assert.equal(results.tokens.getItemAt(3).type, TokenType.OpenParenthesis); + assert.equal(results.tokens.getItemAt(4).type, TokenType.CloseParenthesis); + assert.equal(results.tokens.getItemAt(5).type, TokenType.OpenBracket); + assert.equal(results.tokens.getItemAt(6).type, TokenType.CloseBracket); + assert.equal(results.tokens.getItemAt(7).type, TokenType.OpenCurlyBrace); + assert.equal(results.tokens.getItemAt(8).type, TokenType.CloseCurlyBrace); + assert.equal(results.tokens.getItemAt(9).type, TokenType.Arrow); +}); + +test('IndentDedent', () => { + const t = new Tokenizer(); + const results = t.tokenize( + 'test\n' + + ' i1\n' + + ' i2 # \n' + + ' # \n' + + ' \ti3\n' + + '\ti4\n' + + ' i1'); + assert.equal(results.tokens.count, 15 + _implicitTokenCount); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(1).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(2).type, TokenType.Indent); + assert.equal((results.tokens.getItemAt(2) as IndentToken).indentAmount, 2); + assert.equal(results.tokens.getItemAt(3).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(4).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(5).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(6).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(7).type, TokenType.Indent); + assert.equal((results.tokens.getItemAt(7) as IndentToken).indentAmount, 8); + assert.equal(results.tokens.getItemAt(8).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(9).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(10).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(11).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(12).type, TokenType.Dedent); + assert.equal((results.tokens.getItemAt(12) as DedentToken).indentAmount, 2); + assert.equal((results.tokens.getItemAt(12) as DedentToken).matchesIndent, true); + assert.equal(results.tokens.getItemAt(13).type, TokenType.Dedent); + assert.equal((results.tokens.getItemAt(13) as DedentToken).indentAmount, 1); + assert.equal((results.tokens.getItemAt(13) as DedentToken).matchesIndent, false); + assert.equal(results.tokens.getItemAt(14).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(15).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(16).type, TokenType.EndOfStream); +}); + +test('IndentDedentParen', () => { + const t = new Tokenizer(); + const results = t.tokenize('test (\n i1\n )\n foo'); + assert.equal(results.tokens.count, 8 + _implicitTokenCount); + + // Test that indent and dedent tokens are suppressed within + // a parnethetical clause. + assert.equal(results.tokens.getItemAt(0).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(1).type, TokenType.OpenParenthesis); + assert.equal(results.tokens.getItemAt(2).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(3).type, TokenType.CloseParenthesis); + assert.equal(results.tokens.getItemAt(4).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(5).type, TokenType.Indent); + assert.equal(results.tokens.getItemAt(6).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(7).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(8).type, TokenType.Dedent); + assert.equal(results.tokens.getItemAt(9).type, TokenType.EndOfStream); +}); + +test('Strings: unclosed', () => { + const t = new Tokenizer(); + const results = t.tokenize(' "string" """line1\n#line2"""\t\'un#closed'); + assert.equal(results.tokens.count, 3 + _implicitTokenCount); + + const ranges = [[1, 8], [10, 18], [29, 10]]; + for (let i = 0; i < ranges.length; i += 1) { + assert.equal(results.tokens.getItemAt(i).start, ranges[i][0]); + assert.equal(results.tokens.getItemAt(i).length, ranges[i][1]); + assert.equal(results.tokens.getItemAt(i).type, TokenType.String); + } +}); + +test('Strings: escaped across multiple lines', () => { + const t = new Tokenizer(); + const results = t.tokenize(' "a\\\nb" \'c\\\n\rb\''); + assert.equal(results.tokens.count, 2 + _implicitTokenCount); + + const ranges = [[1, 6], [8, 7]]; + for (let i = 0; i < ranges.length; i += 1) { + assert.equal(results.tokens.getItemAt(i).start, ranges[i][0]); + assert.equal(results.tokens.getItemAt(i).length, ranges[i][1]); + assert.equal(results.tokens.getItemAt(i).type, TokenType.String); + } +}); + +test('Strings: block next to regular, double-quoted', () => { + const t = new Tokenizer(); + const results = t.tokenize('"string""""s2"""'); + assert.equal(results.tokens.count, 2 + _implicitTokenCount); + + const ranges = [[0, 8], [8, 8]]; + for (let i = 0; i < ranges.length; i += 1) { + assert.equal(results.tokens.getItemAt(i).start, ranges[i][0]); + assert.equal(results.tokens.getItemAt(i).length, ranges[i][1]); + assert.equal(results.tokens.getItemAt(i).type, TokenType.String); + } +}); + +test('Strings: block next to block, double-quoted', () => { + const t = new Tokenizer(); + const results = t.tokenize('""""""""'); + assert.equal(results.tokens.count, 2 + _implicitTokenCount); + + const ranges = [[0, 6], [6, 2]]; + for (let i = 0; i < ranges.length; i += 1) { + assert.equal(results.tokens.getItemAt(i).start, ranges[i][0]); + assert.equal(results.tokens.getItemAt(i).length, ranges[i][1]); + assert.equal(results.tokens.getItemAt(i).type, TokenType.String); + } +}); + +test('Strings: unclosed sequence of quotes', () => { + const t = new Tokenizer(); + const results = t.tokenize('"""""'); + assert.equal(results.tokens.count, 1 + _implicitTokenCount); + + const ranges = [[0, 5]]; + for (let i = 0; i < ranges.length; i += 1) { + assert.equal(results.tokens.getItemAt(i).start, ranges[i][0]); + assert.equal(results.tokens.getItemAt(i).length, ranges[i][1]); + assert.equal(results.tokens.getItemAt(i).type, TokenType.String); + } +}); + +test('Strings: single quote escape', () => { + const t = new Tokenizer(); + // tslint:disable-next-line:quotemark + const results = t.tokenize("'\\'quoted\\''"); + assert.equal(results.tokens.count, 1 + _implicitTokenCount); + assert.equal(results.tokens.getItemAt(0).type, TokenType.String); + assert.equal(results.tokens.getItemAt(0).length, 12); +}); + +test('Strings: double quote escape', () => { + const t = new Tokenizer(); + const results = t.tokenize('"\\"quoted\\""'); + assert.equal(results.tokens.count, 1 + _implicitTokenCount); + assert.equal(results.tokens.getItemAt(0).type, TokenType.String); + assert.equal(results.tokens.getItemAt(0).length, 12); +}); + +test('Strings: single quoted f-string ', () => { + const t = new Tokenizer(); + // tslint:disable-next-line:quotemark + const results = t.tokenize("a+f'quoted'"); + assert.equal(results.tokens.count, 3 + _implicitTokenCount); + assert.equal(results.tokens.getItemAt(0).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(1).type, TokenType.Operator); + assert.equal(results.tokens.getItemAt(2).type, TokenType.String); + assert.equal(results.tokens.getItemAt(2).length, 9); +}); + +test('Strings: double quoted f-string ', () => { + const t = new Tokenizer(); + const results = t.tokenize('x(1,f"quoted")'); + assert.equal(results.tokens.count, 6 + _implicitTokenCount); + assert.equal(results.tokens.getItemAt(0).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(1).type, TokenType.OpenParenthesis); + assert.equal(results.tokens.getItemAt(2).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(3).type, TokenType.Comma); + assert.equal(results.tokens.getItemAt(4).type, TokenType.String); + assert.equal(results.tokens.getItemAt(4).length, 9); + assert.equal(results.tokens.getItemAt(5).type, TokenType.CloseParenthesis); +}); + +test('Strings: single quoted multiline f-string ', () => { + const t = new Tokenizer(); + // tslint:disable-next-line:quotemark + const results = t.tokenize("f'''quoted'''"); + assert.equal(results.tokens.count, 1 + _implicitTokenCount); + assert.equal(results.tokens.getItemAt(0).type, TokenType.String); + assert.equal(results.tokens.getItemAt(0).length, 13); +}); + +test('Strings: double quoted multiline f-string ', () => { + const t = new Tokenizer(); + const results = t.tokenize('f"""quoted """'); + assert.equal(results.tokens.count, 1 + _implicitTokenCount); + assert.equal(results.tokens.getItemAt(0).type, TokenType.String); + assert.equal(results.tokens.getItemAt(0).length, 14); +}); + +test('Strings: escape at the end of single quoted string ', () => { + const t = new Tokenizer(); + // tslint:disable-next-line:quotemark + const results = t.tokenize("'quoted\\'\nx"); + assert.equal(results.tokens.count, 3 + _implicitTokenCount); + assert.equal(results.tokens.getItemAt(0).type, TokenType.String); + assert.equal(results.tokens.getItemAt(0).length, 9); + assert.equal(results.tokens.getItemAt(1).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(2).type, TokenType.Identifier); +}); + +test('Strings: escape at the end of double quoted string ', () => { + const t = new Tokenizer(); + const results = t.tokenize('"quoted\\"\nx'); + assert.equal(results.tokens.count, 3 + _implicitTokenCount); + assert.equal(results.tokens.getItemAt(0).type, TokenType.String); + assert.equal(results.tokens.getItemAt(0).length, 9); + assert.equal(results.tokens.getItemAt(1).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(2).type, TokenType.Identifier); +}); + +test('Strings: b/u/r-string', () => { + const t = new Tokenizer(); + const results = t.tokenize('b"b" u"u" br"br" ur"ur"'); + assert.equal(results.tokens.count, 4 + _implicitTokenCount); + assert.equal(results.tokens.getItemAt(0).type, TokenType.String); + assert.equal(results.tokens.getItemAt(0).length, 4); + assert.equal(results.tokens.getItemAt(1).type, TokenType.String); + assert.equal(results.tokens.getItemAt(1).length, 4); + assert.equal(results.tokens.getItemAt(2).type, TokenType.String); + assert.equal(results.tokens.getItemAt(2).length, 6); + assert.equal(results.tokens.getItemAt(3).type, TokenType.String); + assert.equal(results.tokens.getItemAt(3).length, 6); +}); + +test('Strings: escape at the end of double quoted string ', () => { + const t = new Tokenizer(); + const results = t.tokenize('"quoted\\"\nx'); + assert.equal(results.tokens.count, 3 + _implicitTokenCount); + assert.equal(results.tokens.getItemAt(0).type, TokenType.String); + assert.equal(results.tokens.getItemAt(0).length, 9); + assert.equal(results.tokens.getItemAt(1).type, TokenType.NewLine); + assert.equal(results.tokens.getItemAt(2).type, TokenType.Identifier); +}); + +test('Comments', () => { + const t = new Tokenizer(); + const results = t.tokenize(' #co"""mment1\n\t\n#comm\'ent2 '); + assert.equal(results.tokens.count, 1 + _implicitTokenCountNoImplicitNewLine); + assert.equal(results.tokens.getItemAt(0).type, TokenType.NewLine); +}); + +test('Period to operator token', () => { + const t = new Tokenizer(); + const results = t.tokenize('x.y'); + assert.equal(results.tokens.count, 3 + _implicitTokenCount); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(1).type, TokenType.Dot); + assert.equal(results.tokens.getItemAt(2).type, TokenType.Identifier); +}); + +test('@ to operator token', () => { + const t = new Tokenizer(); + const results = t.tokenize('@x'); + assert.equal(results.tokens.count, 2 + _implicitTokenCount); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.Operator); + assert.equal(results.tokens.getItemAt(1).type, TokenType.Identifier); +}); + +test('Unknown token', () => { + const t = new Tokenizer(); + const results = t.tokenize('`$'); + assert.equal(results.tokens.count, 1 + _implicitTokenCount); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.Invalid); +}); + +test('Hex number', () => { + const t = new Tokenizer(); + const results = t.tokenize('1 0X2 0xFe_Ab 0x'); + assert.equal(results.tokens.count, 5 + _implicitTokenCount); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(0).length, 1); + assert.equal((results.tokens.getItemAt(0) as NumberToken).value, 1); + assert.equal((results.tokens.getItemAt(0) as NumberToken).isInteger, true); + + assert.equal(results.tokens.getItemAt(1).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(1).length, 3); + assert.equal((results.tokens.getItemAt(1) as NumberToken).value, 2); + assert.equal((results.tokens.getItemAt(1) as NumberToken).isInteger, true); + + assert.equal(results.tokens.getItemAt(2).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(2).length, 7); + assert.equal((results.tokens.getItemAt(2) as NumberToken).value, 0xFEAB); + assert.equal((results.tokens.getItemAt(2) as NumberToken).isInteger, true); + + assert.equal(results.tokens.getItemAt(3).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(3).length, 1); + + assert.equal(results.tokens.getItemAt(4).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(4).length, 1); +}); + +test('Binary number', () => { + const t = new Tokenizer(); + const results = t.tokenize('1 0B1 0b010 0b3 0b'); + assert.equal(results.tokens.count, 7 + _implicitTokenCount); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(0).length, 1); + assert.equal((results.tokens.getItemAt(0) as NumberToken).value, 1); + assert.equal((results.tokens.getItemAt(0) as NumberToken).isInteger, true); + + assert.equal(results.tokens.getItemAt(1).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(1).length, 3); + assert.equal((results.tokens.getItemAt(1) as NumberToken).value, 1); + assert.equal((results.tokens.getItemAt(1) as NumberToken).isInteger, true); + + assert.equal(results.tokens.getItemAt(2).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(2).length, 5); + assert.equal((results.tokens.getItemAt(2) as NumberToken).value, 2); + assert.equal((results.tokens.getItemAt(2) as NumberToken).isInteger, true); + + assert.equal(results.tokens.getItemAt(3).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(3).length, 1); + assert.equal((results.tokens.getItemAt(3) as NumberToken).value, 0); + assert.equal((results.tokens.getItemAt(3) as NumberToken).isInteger, true); + + assert.equal(results.tokens.getItemAt(4).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(4).length, 2); + + assert.equal(results.tokens.getItemAt(5).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(5).length, 1); + + assert.equal(results.tokens.getItemAt(6).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(6).length, 1); +}); + +test('Octal number', () => { + const t = new Tokenizer(); + const results = t.tokenize('1 0o4 0O0_7_7 -0o200 0o9 0oO'); + assert.equal(results.tokens.count, 9 + _implicitTokenCount); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(0).length, 1); + assert.equal((results.tokens.getItemAt(0) as NumberToken).value, 1); + assert.equal((results.tokens.getItemAt(0) as NumberToken).isInteger, true); + + assert.equal(results.tokens.getItemAt(1).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(1).length, 3); + assert.equal((results.tokens.getItemAt(1) as NumberToken).value, 4); + assert.equal((results.tokens.getItemAt(1) as NumberToken).isInteger, true); + + assert.equal(results.tokens.getItemAt(2).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(2).length, 7); + assert.equal((results.tokens.getItemAt(2) as NumberToken).value, 0o77); + assert.equal((results.tokens.getItemAt(2) as NumberToken).isInteger, true); + + assert.equal(results.tokens.getItemAt(3).type, TokenType.Operator); + assert.equal(results.tokens.getItemAt(3).length, 1); + + assert.equal(results.tokens.getItemAt(4).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(4).length, 5); + assert.equal((results.tokens.getItemAt(4) as NumberToken).value, 0o200); + assert.equal((results.tokens.getItemAt(4) as NumberToken).isInteger, true); + + assert.equal(results.tokens.getItemAt(5).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(5).length, 1); + assert.equal((results.tokens.getItemAt(5) as NumberToken).value, 0); + assert.equal((results.tokens.getItemAt(5) as NumberToken).isInteger, true); + + assert.equal(results.tokens.getItemAt(6).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(6).length, 2); + assert.equal((results.tokens.getItemAt(6) as IdentifierToken).value, 'o9'); + + assert.equal(results.tokens.getItemAt(7).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(7).length, 1); + assert.equal((results.tokens.getItemAt(7) as NumberToken).value, 0); + assert.equal((results.tokens.getItemAt(7) as NumberToken).isInteger, true); + + assert.equal(results.tokens.getItemAt(8).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(8).length, 2); + assert.equal((results.tokens.getItemAt(8) as IdentifierToken).value, 'oO'); +}); + +test('Decimal number', () => { + const t = new Tokenizer(); + const results = t.tokenize('-2147483647 ++2147483647'); + assert.equal(results.tokens.count, 5 + _implicitTokenCount); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.Operator); + assert.equal(results.tokens.getItemAt(0).length, 1); + + assert.equal(results.tokens.getItemAt(1).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(1).length, 10); + assert.equal((results.tokens.getItemAt(1) as NumberToken).value, 2147483647); + assert.equal((results.tokens.getItemAt(1) as NumberToken).isInteger, true); + + assert.equal(results.tokens.getItemAt(2).type, TokenType.Operator); + assert.equal(results.tokens.getItemAt(2).length, 1); + + assert.equal(results.tokens.getItemAt(3).type, TokenType.Operator); + assert.equal(results.tokens.getItemAt(3).length, 1); + + assert.equal(results.tokens.getItemAt(4).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(4).length, 10); + assert.equal((results.tokens.getItemAt(4) as NumberToken).value, 2147483647); + assert.equal((results.tokens.getItemAt(4) as NumberToken).isInteger, true); +}); + +test('Decimal number operator', () => { + const t = new Tokenizer(); + const results = t.tokenize('a[: -1]'); + assert.equal(results.tokens.count, 6 + _implicitTokenCount); + + assert.equal(results.tokens.getItemAt(4).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(4).length, 1); +}); + +test('Floating point number', () => { + const t = new Tokenizer(); + const results = t.tokenize('3.0 .2 ++.3e+12 --.4e1 1e-4 0.01'); + assert.equal(results.tokens.count, 10 + _implicitTokenCount); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.Number); + assert.equal((results.tokens.getItemAt(0) as NumberToken).value, 3); + assert.equal((results.tokens.getItemAt(0) as NumberToken).isInteger, false); + assert.equal(results.tokens.getItemAt(0).length, 3); + + assert.equal(results.tokens.getItemAt(1).type, TokenType.Number); + assert.equal((results.tokens.getItemAt(1) as NumberToken).value, 0.2); + assert.equal((results.tokens.getItemAt(1) as NumberToken).isInteger, false); + assert.equal(results.tokens.getItemAt(1).length, 2); + + assert.equal(results.tokens.getItemAt(2).type, TokenType.Operator); + assert.equal(results.tokens.getItemAt(2).length, 1); + + assert.equal(results.tokens.getItemAt(3).type, TokenType.Operator); + assert.equal(results.tokens.getItemAt(3).length, 1); + + assert.equal(results.tokens.getItemAt(4).type, TokenType.Number); + assert.equal((results.tokens.getItemAt(4) as NumberToken).value, 0.3e12); + assert.equal((results.tokens.getItemAt(4) as NumberToken).isInteger, false); + assert.equal(results.tokens.getItemAt(4).length, 6); + + assert.equal(results.tokens.getItemAt(5).type, TokenType.Operator); + assert.equal(results.tokens.getItemAt(5).length, 1); + + assert.equal(results.tokens.getItemAt(6).type, TokenType.Operator); + assert.equal(results.tokens.getItemAt(6).length, 1); + + assert.equal(results.tokens.getItemAt(7).type, TokenType.Number); + assert.equal((results.tokens.getItemAt(7) as NumberToken).value, 0.4e1); + assert.equal((results.tokens.getItemAt(7) as NumberToken).isInteger, false); + assert.equal(results.tokens.getItemAt(7).length, 4); + + assert.equal(results.tokens.getItemAt(8).type, TokenType.Number); + assert.equal((results.tokens.getItemAt(8) as NumberToken).value, 1e-4); + assert.equal((results.tokens.getItemAt(8) as NumberToken).isInteger, false); + assert.equal(results.tokens.getItemAt(8).length, 4); + + assert.equal(results.tokens.getItemAt(9).type, TokenType.Number); + assert.equal((results.tokens.getItemAt(9) as NumberToken).value, 0.01); + assert.equal((results.tokens.getItemAt(9) as NumberToken).isInteger, false); + assert.equal(results.tokens.getItemAt(9).length, 4); +}); + +test('Floating point numbers with parens', () => { + const t = new Tokenizer(); + const results = t.tokenize('(3.0) (.2) (+.3e+12, .4e1; 0)'); + assert.equal(results.tokens.count, 14 + _implicitTokenCount); + + assert.equal(results.tokens.getItemAt(1).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(1).length, 3); + + assert.equal(results.tokens.getItemAt(4).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(4).length, 2); + + assert.equal(results.tokens.getItemAt(8).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(8).length, 6); + + assert.equal(results.tokens.getItemAt(10).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(10).length, 4); + + assert.equal(results.tokens.getItemAt(12).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(12).length, 1); +}); + +test('Floating point numbers with operators', () => { + const t = new Tokenizer(); + const results = t.tokenize('88.9/100.0*4.0-2.0,'); + assert.equal(results.tokens.count, 8 + _implicitTokenCount); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(0).length, 4); + + assert.equal(results.tokens.getItemAt(2).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(2).length, 5); + + assert.equal(results.tokens.getItemAt(4).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(4).length, 3); + + assert.equal(results.tokens.getItemAt(6).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(6).length, 3); +}); + +test('Underscore numbers', () => { + const t = new Tokenizer(); + const results = t.tokenize('1_0_0_0 0_0 .5_00_3e-4 0xC__A_FE_F00D 10_000_000.0 0b_0011_1111_0100_1110'); + const lengths = [7, 3, 10, 14, 12, 22]; + const isIntegers = [true, true, false, true, false, true]; + assert.equal(results.tokens.count, 6 + _implicitTokenCount); + + for (let i = 0; i < lengths.length; i += 1) { + assert.equal(results.tokens.getItemAt(i).type, TokenType.Number); + assert.equal(results.tokens.getItemAt(i).length, lengths[i]); + assert.equal((results.tokens.getItemAt(i) as NumberToken).isInteger, isIntegers[i]); + } +}); + +test('Simple expression, leading minus', () => { + const t = new Tokenizer(); + const results = t.tokenize('x == -y'); + assert.equal(results.tokens.count, 4 + _implicitTokenCount); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(0).length, 1); + + assert.equal(results.tokens.getItemAt(1).type, TokenType.Operator); + assert.equal(results.tokens.getItemAt(1).length, 2); + + assert.equal(results.tokens.getItemAt(2).type, TokenType.Operator); + assert.equal(results.tokens.getItemAt(2).length, 1); + + assert.equal(results.tokens.getItemAt(3).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(3).length, 1); +}); + +test('Operators', () => { + const text = '< << <<= ' + + '== != > >> >>= >= <=' + + '+ - ~ %' + + '* ** / // /= //=' + + '*= += -= %= **= ' + + '& &= | |= ^ ^='; + const results = new Tokenizer().tokenize(text); + const lengths = [ + 1, 2, 3, + 2, 2, 1, 2, 3, 2, 2, + 1, 1, 1, 1, + 1, 2, 1, 2, 2, 3, + 2, 2, 2, 2, 3, + 1, 2, 1, 2, 1, 2]; + const operatorTypes = [ + OperatorType.LessThan, + OperatorType.LeftShift, + OperatorType.LeftShiftEqual, + OperatorType.Equals, + OperatorType.NotEquals, + OperatorType.GreaterThan, + OperatorType.RightShift, + OperatorType.RightShiftEqual, + OperatorType.GreaterThanOrEqual, + OperatorType.LessThanOrEqual, + OperatorType.Add, + OperatorType.Subtract, + OperatorType.BitwiseInvert, + OperatorType.Mod, + OperatorType.Multiply, + OperatorType.Power, + OperatorType.Divide, + OperatorType.FloorDivide, + OperatorType.DivideEqual, + OperatorType.FloorDivideEqual, + OperatorType.MultiplyEqual, + OperatorType.AddEqual, + OperatorType.SubtractEqual, + OperatorType.ModEqual, + OperatorType.PowerEqual, + OperatorType.BitwiseAnd, + OperatorType.BitwiseAndEqual, + OperatorType.BitwiseOr, + OperatorType.BitwiseOrEqual, + OperatorType.ExclusiveOr, + OperatorType.ExclusiveOrEqual]; + assert.equal(results.tokens.count - _implicitTokenCount, lengths.length); + assert.equal(results.tokens.count - _implicitTokenCount, operatorTypes.length); + for (let i = 0; i < lengths.length; i += 1) { + const t = results.tokens.getItemAt(i); + assert.equal(t.type, TokenType.Operator, `${t.type} at ${i} is not an operator`); + assert.equal((t as OperatorToken).operatorType, operatorTypes[i]); + assert.equal(t.length, lengths[i], + `Length ${t.length} at ${i} (text ${text.substr(t.start, t.length)}), expected ${lengths[i]}`); + } +}); + +test('Identifiers', () => { + const t = new Tokenizer(); + const results = t.tokenize('and __and __and__ and__'); + assert.equal(results.tokens.count, 4 + _implicitTokenCount); + + assert.equal(results.tokens.getItemAt(0).type, TokenType.Keyword); + assert.equal(results.tokens.getItemAt(0).length, 3); + + assert.equal(results.tokens.getItemAt(1).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(1).length, 5); + + assert.equal(results.tokens.getItemAt(2).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(2).length, 7); + + assert.equal(results.tokens.getItemAt(3).type, TokenType.Identifier); + assert.equal(results.tokens.getItemAt(3).length, 5); +}); diff --git a/server/tsconfig.json b/server/tsconfig.json new file mode 100644 index 000000000..05ed4b1be --- /dev/null +++ b/server/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "noUnusedLocals": false, + "noImplicitAny": true, + "noImplicitReturns": true, + "strictNullChecks": true, + "skipLibCheck": true, + "target": "es6", + "module": "commonjs", + "moduleResolution": "node", + "sourceMap": true, + "lib" : [ "es2016" ], + "outDir": "../client/server" + }, + "exclude": [ + "node_modules" + ] +} diff --git a/server/tslint.json b/server/tslint.json new file mode 100644 index 000000000..b66302095 --- /dev/null +++ b/server/tslint.json @@ -0,0 +1,123 @@ +{ + "rulesDirectory": [ + "./node_modules/tslint-microsoft-contrib" + ], + "rules": { + // Rules from tslint-microsoft-contrib + "function-name": [true, { + "method-regex": "^[a-z]\\w+$", + "private-method-regex": "^_[a-z]\\w+$", + "protected-method-regex": "^[a-z_]\\w+$", + "static-method-regex": "^[a-z]\\w+$", + "function-regex": "^\\w+$" + }], + "no-delete-expression": true, + "no-document-domain": true, + "no-disable-auto-sanitization": true, + "no-exec-script": true, + "no-function-constructor-with-string-args": true, + "no-string-based-set-immediate": true, + "no-string-based-set-interval": true, + "no-string-based-set-timeout": true, + "react-no-dangerous-html": true, + "react-this-binding-issue": [true, { "allow-anonymous-listeners": true }], + "no-inner-html": true, + "no-document-write": true, + + // Rules that are built in to tslint + "align": [true, "statements"], + "class-name": true, + "curly": true, + "eofline": true, + "forin": true, + "indent": [true, "spaces"], + "interface-name": [true, "never-prefix"], + "label-position": true, + "max-line-length": [true, 140], + "member-access": [true, "no-public"], + "new-parens": true, + "no-arg": true, + "no-console": [true, + "debug", + "info", + "time", + "timeEnd", + "trace" + ], + "no-consecutive-blank-lines": true, + "no-conditional-assignment": true, + "no-construct": true, + "no-debugger": true, + "no-duplicate-variable": true, + "no-empty": true, + "no-duplicate-super": true, + "no-duplicate-switch-case": true, + "no-eval": true, + "no-inferrable-types": true, + "no-invalid-this": true, + "no-string-throw": true, + "no-switch-case-fall-through": true, + "no-trailing-whitespace": true, + "no-unused-expression": true, + "no-var-keyword": true, + "no-string-literal": true, + "no-sparse-arrays": true, + "ban-comma-operator": true, + "restrict-plus-operands": true, + "use-isnan": true, + "linebreak-style": true, + "comment-format": true, + "no-boolean-literal-compare": true, + "no-unnecessary-initializer": true, + "number-literal-format": true, + "space-before-function-paren": [true, "never"], + "trailing-comma": [ + true, + { + "multiline": "never", + "singleline": "never", + "esSpecCompliant": true + } + ], + "arrow-parens": [true, "ban-single-arg-parens"], + "one-line": [true, + "check-open-brace", + "check-catch", + "check-finally", + "check-else", + "check-whitespace" + ], + "quotemark": [true, "single", "jsx-single"], + "radix": true, + "semicolon": true, + "triple-equals": true, + "whitespace": [true, + "check-branch", + "check-decl", + "check-operator", + "check-module", + "check-separator", + "check-type", + "check-rest-spread", + "check-type-operator", + "check-preblock" + ], + "arrow-return-shorthand": true, + "no-angle-bracket-type-assertion": true, + "one-variable-per-declaration": true, + "no-object-literal-type-assertion": true, + "no-unnecessary-type-assertion": true, + "no-duplicate-imports": true, + "import-spacing": true, + "no-floating-promises": [true], + "no-void-expression": [true], + "file-header": [true], + "ordered-imports": [true, + { + "import-sources-order": "case-insensitive", + "module-source-path": "full", + "named-imports-order": "case-insensitive" + } + ] + } +} diff --git a/server/webpack.config.js b/server/webpack.config.js new file mode 100644 index 000000000..73fb30eb9 --- /dev/null +++ b/server/webpack.config.js @@ -0,0 +1,43 @@ +/** +* webpack.config.js +* Copyright: Microsoft 2018 +* +* Configuration for webpack to bundle the javascript into a single file. +*/ + +const path = require('path'); + +module.exports = { + entry: './src/server.ts', + mode: 'development', + target: 'node', + output: { + filename: 'server.js', + path: path.resolve(__dirname, '../client/server') + }, + + resolve: { + modules: [ + path.resolve(__dirname, '.'), + 'node_modules' + ], + // Add '.ts' and '.tsx' as resolvable extensions. + extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js'] + }, + + module: { + rules: [ + { + test: /\.tsx?$/, + loader: 'ts-loader', + options: { + configFile: 'tsconfig.json' + } + } + ] + }, + + node: { + fs: 'empty' + } +};