Merge pull request #30112 from nkappler/tern

Add Type Declarations for Tern
This commit is contained in:
Daniel Rosenwasser
2018-10-31 18:03:18 -07:00
committed by GitHub
6 changed files with 816 additions and 0 deletions
+15
View File
@@ -0,0 +1,15 @@
// Type definitions for tern 0.22
// Project: https://github.com/ternjs/tern
// Definitions by: Nikolaj Kappler <https://github.com/nkappler>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
// IMPORTANT Note: These type definitions adhere strictly to the official documentation,
// which does not seem to match the implementation exactly in some places.
// As a result, these type definitions may lack some parts of the API that are actually exposed.
// The type definitions are at a point where they are usable and match the documentation,
// thus if you want to use undocumented APIs, you should extends these definitions with
// ambient declaration merging: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
export * from "./lib/tern";
export * from "./lib/infer";
+218
View File
@@ -0,0 +1,218 @@
import * as ESTree from "estree";
export { };
// #### Context ####
interface ContextConstructor {
new(defs: any[]): Context;
}
export const Context: ContextConstructor;
export interface Context {
topScope: Scope;
/** The primitive number type. */
num: Type;
/** The primitive string type. */
str: Type;
/** The primitive boolean type. */
bool: Type;
}
export function cx(): Context;
export function withContext(context: Context, f: () => void): void;
// #### Analysis ####
/** Parse a piece of code for use by Tern. Will automatically fall back to the error-tolerant parser if the regular parser can’t parse the code. */
export function parse(text: string, options?: {}): ESTree.Program;
/**
* Analyze a syntax tree. `name` will be used to set the origin of types, properties, and variables produced by this code.
* The optional `scope` argument can be used to specify a scope in which the code should be analyzed.
* It will default to the top-level scope.
*/
export function analyze(ast: ESTree.Program, name: string, scope?: Scope): void;
/**
* Purges the types that have one of the origins given from the context. `start` and `end` can be given to only purge
* types that occurred in the source code between those offsets. This is not entirely precise — the state of the
* context won’t be back where it was before the file was analyzed — but it prevents most of the
* noticeable inaccuracies that re-analysis tends to produce.
*/
export function purgeTypes(origins: string[], start?: number, end?: number): void;
/**
* Cleaning up variables is slightly trickier than cleaning up types. This does a first pass over the given scope,
* and marks variables defined by the given origins. This is indended to be followed by a call to `analyze` and then a call to `purgeMarkedVariables`.
*/
export function markVariablesDefinedBy(scope: Scope, origins: string[], start?: number, end?: number): void;
/** Purges variables that were marked by a call to markVariablesDefinedBy and not re-defined in the meantime. */
export function purgeMarkedVariables(): void;
// #### Types ####
interface ObjConstructor {
new(proto: object | true | null, name?: string): Obj;
}
/** Constructor for the type that represents JavaScript objects. `proto` may be another object, or `true` as a short-hand for `Object.prototype`, or `null` for prototype-less objects. */
export const Obj: ObjConstructor;
export interface Obj extends Type {
/** The prototype of the object, or null. */
proto: any;
/** An object mapping the object’s known properties to AVals. Don’t manipulate this directly (ever), only use it if you have to iterate over the properties. */
props: Readonly<{
[key: string]: AVal;
}>;
/** Looks up the AVal associated with the given property, or returns null if it doesn’t exist. */
hasProp(prop: string): AVal | null;
/** Looks up the given property, or defines it if it did not yet exist (in which case it will be associated with the given AST node). */
defProp(prop: string, originNode?: ESTree.Node): AVal;
}
interface FnConstructor {
new(name: string | undefined, self: AVal, args: AVal[], argNames: string[], retval: AVal): Fn;
}
/** Constructor for the type that implements functions. Inherits from `Obj`. The `AVal` types are used to track the input and output types of the function. */
export const Fn: FnConstructor;
export type Fn = Obj;
interface ArrConstructor {
/** Constructor that creates an array type with the given content type. */
new(contentType: AVal): Arr;
}
export const Arr: ArrConstructor;
export type Arr = Obj;
export interface Type extends AVal {
/** The name of the type, if any. */
name: string;
/** The origin file of the type. */
origin: string;
/**
* The syntax node that defined the type. Only present for object and function types,
* and even for those it may be missing (if the type was created by a type definition file,
* or synthesized in some other way).
*/
originNode?: ESTree.Node;
/** Return a string that describes the type. maxDepth indicates the depth to which inner types should be shown. */
toString(maxDepth: number): string;
/** Get an `AVal` that represents the named property of this type. */
getProp(prop: string): AVal;
/** Call the given function for all properties of the object, including properties that are added in the future. */
forAllProps(f: (prop: string, val: AVal, local: boolean) => void): void;
}
// #### Abstract Values ####
interface AValConstructor {
new(): AVal;
}
export const AVal: AValConstructor;
export interface AVal {
/**
* Add a type to this abstract value. If the type is already in there,
* this is a no-op. weight can be given to give this type a non-default
* weight, which is mostly useful when adding a provisionary type that
* should be overridden later if a real type is found. The default weight
* is 100, and passing a weight lower than that will make the type
* assignment “weak”.
*/
addType(type: Type, weight?: number): void;
/**
* Sets this AVal to propagate all types it receives to the given
* constraint. This is the mechanism by which types are propagated
* through the type graph.
*/
propagate(target: Constraint): void;
/** Queries whether the AVal _currently_ holds the given type. */
hasType(type: Type): boolean;
/** Queries whether the AVal is empty. */
isEmpty(): boolean;
/**
* Asks the abstract value for its current type. May return `null`
* when there is no type, or conflicting types are present. When
* `guess` is true or not given, an empty AVal will try to use
* heuristics based on its propagation edges to guess a type.
*/
getType(guess?: boolean): Type | null;
/**
* Asks the AVal if it contains a function type. Useful when
* you aren’t interested in other kinds of types.
*/
getFunctionType(): Type | undefined;
/**
* Abstract values that are used to represent variables
* or properties will have, when possible, an `originNode`
* property pointing to an AST node.
*/
originNode?: ESTree.Node;
}
export const ANull: ANull;
export interface ANull extends AVal {
addType(): void;
propagate(target: never): void;
hasType(): false;
isEmpty(): true;
getFunctionType(): undefined;
getType(): null;
originNode: undefined;
}
// #### Constraints ####
interface ConstraintConstructor {
new(methods: { [key: string]: any }): { new(): Constraint };
}
/**
* This is a constructor-constructor for constraints. It’ll create a
* constructor with all the given methods copied into its prototype,
* which will run its construct method on its arguments when instantiated.
*/
export const constraint: ConstraintConstructor;
export interface Constraint extends AVal {
/** May return a type that `getType` can use to “guess” its type based on the fact that it propagates to this constraint. */
typeHint?(): Type | undefined;
/** May return a string when this constraint is indicative of the presence of a specific property in the source AVal. */
propHint?(): string | undefined;
}
// #### Scopes ####
interface ScopeConstructor {
new(parent?: Scope): Scope;
}
export const Scope: ScopeConstructor;
export interface Scope extends Obj {
/**
* Ensures that this scope or some scope above it has a property by the given name
* (defining it in the top scope if it is missing), and, if the property doesn’t
* already have an `originNode`, assigns the given node to it.
*/
defVar(name: string, originNode: ESTree.Node): AVal;
}
// #### Utilities ####
/**
* Searches the given syntax tree for an expression that ends at the given `end` offset and,
* if `start` is given, starts at the given start offset. `scope` can be given to override the
* outer scope, which defaults to the context’s top scope. Will return a `{node, state}`
* object if successful, where `node` is AST node, and `state` is the scope at that point.
* Returns `null` if unsuccessful.
*/
export function findExpressionAt(ast: ESTree.Program, start: number | undefined, end: number, scope?: Scope): { node: ESTree.Node, state: Scope } | null;
/**
* Similar to `findExpressionAt`, except that it will return the innermost expression
* node that spans the given range, rather than only exact matches.
*/
export function findExpressionAround(ast: ESTree.Program, start: number | undefined, end: number, scope?: Scope): { node: ESTree.Node, state: Scope } | null;
/** Similar to `findExpressionAround`, except that it use the same AST walker as `findExpressionAt`. */
export function findClosestExpression(ast: ESTree.Program, start: number | undefined, end: number, scope?: Scope): { node: ESTree.Node, state: Scope } | null;
/** Determine an expression for the given node and scope (as returned by the functions above). Will return an `AVal` or plain `Type`. */
export function expressionType(expr: { node: ESTree.Node, state: Scope }): AVal | Type;
/** Find the scope at a given position in the syntax tree. The `scope` parameter can be used to override the scope used for code that isn’t wrapped in any function. */
export function scopeAt(ast: ESTree.Program, pos: number, scope?: Scope): Scope;
/**
* Will traverse the given syntax tree, using `scope` as the starting scope, looking for references to variable `name` that
* resolve to scope `refScope`, and call `f` with the node of the reference and its local scope for each of them.
*/
export function findRefs(ast: ESTree.Program, scope: Scope, name: string, refScope: Scope, f: (Node: ESTree.Node, Scope: Scope) => void): void;
/**
* Analogous to `findRefs`, but used to look for references to a specific property instead. Whereas `findRefs`
* is precise, this is dependent on type inference, and thus can not be relied on to be precise.
*/
export function findPropRefs(ast: ESTree.Program, scope: Scope, objType: Obj, propName: string, f: (Node: ESTree.Node) => void): void;
/** Whenever infer guesses a type through fuzzy heuristics (through `getType` or `expressionType`), it sets a flag. `didGuess` tests whether the guessing flag is set. */
export function didGuess(): boolean;
/** Whenever infer guesses a type through fuzzy heuristics (through `getType` or `expressionType`), it sets a flag. `resetGuessing` resets the guessing flag. */
export function resetGuessing(val?: boolean): void;
+500
View File
@@ -0,0 +1,500 @@
import * as ESTree from "estree";
import { Scope, Type } from "../infer";
export { };
// #### Programming interface ####
export type ConstructorOptions = CtorOptions & (SyncConstructorOptions | ASyncConstructorOptions);
interface CtorOptions {
/** The definition objects to load into the server’s environment. */
defs?: Def[];
/** The ECMAScript version to parse. Should be either 5 or 6. Default is 6. */
ecmaVersion?: 5 | 6;
/** Indicates the maximum amount of milliseconds to wait for an asynchronous getFile before giving up on it. Defaults to 1000. */
fetchTimeout?: number;
/** Specifies the set of plugins that the server should load. The property names of the object name the plugins, and their values hold options that will be passed to them. */
plugins?: { [key: string]: object };
}
interface SyncConstructorOptions {
/** Indicates whether `getFile` is asynchronous. Default is `false`. */
async?: false;
/**
* Provides a way for the server to try and fetch the content of files.
* Depending on the `async` option, this is either a function that takes a filename and returns a string (when not `async`), or
* a function that takes a `filename` and a `callback`, and calls the callback with an optional `error` as the first argument,
* and the `content` string (if no error) as the second.
*/
getFile?(filename: string): string;
}
interface ASyncConstructorOptions {
/** Indicates whether `getFile` is asynchronous. Default is `false`. */
async: true;
/**
* Provides a way for the server to try and fetch the content of files.
* Depending on the `async` option, this is either a function that takes a filename and returns a string (when not `async`), or
* a function that takes a `filename` and a `callback`, and calls the callback with an optional `error` as the first argument,
* and the `content` string (if no error) as the second.
*/
getFile?(filename: string, callback: (error: Error | undefined, content?: string) => void): void;
}
interface TernConstructor {
new(options?: ConstructorOptions): Server;
}
export const Server: TernConstructor;
export interface Server {
/**
* Add a set of type definitions to the server. If `atFront` is true, they will be added before all other
* existing definitions. Otherwise, they are added at the back.
*/
addDefs(defs: Def[], atFront?: boolean): void;
/**
* Register a file with the server. Note that files can also be included in requests. When using this
* to automatically load a dependency, specify the name of the file (as Tern knows it) as the third
* argument. That way, the file is counted towards the dependency budget of the root of its dependency graph.
*/
addFile(name: string, text?: string, parent?: string): void;
/** Unregister a file. */
delFile(name: string): void;
/**
* Delete a set of type definitions from the server, by providing the name, taken from
* `defs[!name]` property from the definitions. If that property is not available in the
* current type definitions, it can’t be removed.
*/
deleteDefs(name: string): void;
/** Forces all files to be fetched an analyzed, and then calls the callback function. */
flush(callback: () => void): void;
/** Load a server plugin (or don’t do anything, if the plugin is already loaded). */
loadPlugin(name: string, options: object): void;
/** Unregister an event handler. */
off<K extends keyof Events>(eventType: K, handler: Events[K]): void;
/** Register an event handler for the named type of event. */
on<K extends keyof Events>(eventType: K, handler: Events[K]): void;
/**
* Perform a request. `doc` is a (parsed) JSON document as described in the protocol documentation.
* The `callback` function will be called when the request completes. If an `error` occurred,
* it will be passed as a first argument. Otherwise, the `response` (parsed) JSON object will be passed as second argument.
*
* When the server hasn’t been configured to be asynchronous, the callback will be called before request returns.
*/
request<Q extends Query, D extends Document>(
doc: D & { query?: Q },
callback: (
error: Error | undefined,
response: (D extends { query: undefined } ? {} : D extends { query: Query } ? QueryResult<Q> : {}) | undefined
) => void
): void;
}
// #### JSON Protocol ####
type QueryResult<Q extends Query> = QueryRegistry[Q["type"]]["result"];
type Query = QueryRegistry[keyof QueryRegistry]["query"];
export interface QueryRegistry {
completions: {
query: CompletionsQuery,
result: CompletionsQueryResult
};
type: {
query: TypeQuery,
result: TypeQueryResult
};
definition: {
query: DefinitionQuery,
result: DefinitionQueryResult
};
documentation: {
query: DocumentationQuery;
result: DocumentationQueryResult;
};
refs: {
query: RefsQuery;
result: RefsQueryResult;
};
rename: {
query: RenameQuery,
result: RenameQueryResult
};
properties: {
query: PropertiesQuery,
result: PropertiesQueryResult
};
files: {
query: FilesQuery,
result: FilesQueryResult
};
}
export interface Def {
[key: string]: string | Def;
}
export interface Document {
query?: Query;
files?: File[];
timeout?: number;
}
export interface File {
name: string;
text: string;
scope: Scope;
ast: ESTree.Program;
type?: "full" | "part" | "delete";
}
export interface BaseQuery {
type: string;
lineCharPositions?: boolean;
docFormat?: "full";
}
interface Position {
ch: number;
line: number;
}
/** Asks the server for a set of completions at the given point. */
export interface CompletionsQuery extends BaseQuery {
/** Asks the server for a set of completions at the given point. */
type: "completions";
/** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */
file: string;
/** Specify the location to complete at. */
end: number | Position;
/** Whether to include the types of the completions in the result data. Default `false` */
types?: boolean;
/** Whether to include the distance (in scopes for variables, in prototypes for properties) between the completions and the origin position in the result data. Default `false` */
depths?: boolean;
/** Whether to include documentation strings in the result data. Default `false` */
docs?: boolean;
/** Whether to include urls in the result data. Default `false` */
urls?: boolean;
/** Whether to include origin files (if found) in the result data. Default `false` */
origins?: boolean;
/** When on, only completions that match the current word at the given point will be returned. Turn this off to get all results, so that you can filter on the client side. Default `true` */
filter?: boolean;
/** Whether to use a case-insensitive compare between the current word and potential completions. Default `false` */
caseInsensitive?: boolean;
/** When completing a property and no completions are found, Tern will use some heuristics to try and return some properties anyway. Set this to `false` to turn that off. Default `true` */
guess?: boolean;
/** Determines whether the result set will be sorted. Default `true` */
sort?: boolean;
/**
* When disabled, only the text before the given position is considered part of the word. When enabled (the default),
* the whole variable name that the cursor is on will be included. Default `true`
*/
expandWordForward?: boolean;
/** Whether to ignore the properties of `Object.prototype` unless they have been spelled out by at least two characters. Default `true` */
omitObjectPrototype?: boolean;
/** Whether to include JavaScript keywords when completing something that is not a property. Default `false` */
includeKeywords?: boolean;
/** If completions should be returned when inside a literal. Default `true` */
inLiteral?: boolean;
}
interface CompletionsQueryResult {
/** start offsets of the word that was completed */
start: number | Position;
/** end offsets of the word that was completed */
end: number | Position;
/** whether the completion is for a property or a variable */
isProperty: boolean;
// TODO depends on completionsquery settings -> conditional types?
/**
* array of completions. When one of the `types`, `depths`, `docs`, `urls`, or `origins`
* options was passed, the array will hold objects with a `name` property (the completion text),
* and, depending on the options, `type`, `depth`, `doc`, `url`, and `origin` properties.
* When none of these options are enabled, the result array will hold plain strings.
*/
completions: string[] | Array<{
name: string,
type?: string,
depth?: number,
doc?: string,
url?: string,
origin?: string
}>;
}
/** Query the type of something. */
export interface TypeQuery extends BaseQuery {
/** Query the type of something. */
type: "type";
/** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */
file: string;
/** Specify the location of the expression. */
end: number | Position;
/** Specify the location of the expression. */
start?: number | Position;
/**
* Set to `true` when you are interested in a function type.
* This will cause function types to win when something has multiple types.
* Default `false`
*/
preferFunction?: boolean;
/**
* Determines how deep the type string must be expanded.
* Nested objects will only display property types up to this depth,
* and be represented by their type name or a representation showing
* only property names below it. Default `0`
*/
depth?: number;
}
interface TypeQueryResult {
/** A description of the type of the value. May be "?" when no type was found. */
type: string;
/** Whether the given type was guessed, or should be considered reliable. */
guess: boolean;
/** The name associated with the type. */
name?: string;
/** When the inspected expression was an identifier or a property access, this will hold the name of the variable or property. */
exprName?: string;
/** If the type had documentation associated with it, these will also be returned. */
doc?: string;
/** If the type had urls associated with it, these will also be returned. */
url?: string;
/** If the type had origin information associated with it, these will also be returned. */
origin?: string;
}
/**
* Asks for the definition of something. This will try, for a variable or property,
* to return the point at which it was defined. If that fails, or the chosen
* expression is not an identifier or property reference, it will try to return
* the definition site of the type the expression has. If no type is found, or the
* type is not an object or function (other types don’t store their definition site),
* it will fail to return useful information.
*/
export interface DefinitionQuery extends BaseQuery {
/**
* Asks for the definition of something. This will try, for a variable or property,
* to return the point at which it was defined. If that fails, or the chosen
* expression is not an identifier or property reference, it will try to return
* the definition site of the type the expression has. If no type is found, or the
* type is not an object or function (other types don’t store their definition site),
* it will fail to return useful information.
*/
type: "definition";
/** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */
file: string;
/** Specify the location of the expression. */
end: number | Position;
/** Specify the location of the expression. */
start?: number | Position;
}
interface DefinitionQueryResult {
/** The start position of the expression. */
start?: number | Position;
/** The end position of the expression. */
end?: number | Position;
/** The file in which the definition was defined. */
file?: string;
/** A slice of the code in front of the definition Can be used to find a definition’s location in a modified file. */
context?: string;
/** The offset from the start of the context to the actual definition. Can be used to find a definition’s location in a modified file. */
contextOffset?: number;
/** If the definition had documentation associated with it, these will also be returned. */
doc?: string;
/** If the definition had urls associated with it, these will also be returned. */
url?: string;
/** If the definition had origin information associated with it, these will also be returned. */
origin?: string;
}
/** Get the documentation string and URL for a given expression, if any. */
export interface DocumentationQuery extends BaseQuery {
/** Get the documentation string and URL for a given expression, if any. */
type: "documentation";
/** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */
file: string;
/** Specify the location of the expression. */
end: number | Position;
/** Specify the location of the expression. */
start?: number | Position;
}
interface DocumentationQueryResult {
/** The documentation string of the definition or value, if any. */
doc?: string;
/** The url of the definition or value, if any. */
url?: string;
/** The origin of the definition or value, if any. */
origin?: string;
}
/** Used to find all references to a given variable or property. */
export interface RefsQuery extends BaseQuery {
/** Used to find all references to a given variable or property. */
type: "refs";
/** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */
file: string;
/** Specify the location of the expression. */
end: number | Position;
/** Specify the location of the expression. */
start?: number | Position;
}
interface RefsQueryResult {
/** The name of the variable or property */
name: string;
refs: Array<{
file: string,
start: number | Position,
end: number | Position
}>;
/** for variables: a type property holding either "global" or "local". */
type?: "global" | "local";
}
/** Rename a variable in a scope-aware way. */
export interface RenameQuery extends BaseQuery {
/** Rename a variable in a scope-aware way. */
type: "rename";
/** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */
file: string;
/** Specify the location of the variable. */
end: number | Position;
/** Specify the location of the variable. */
start?: number | Position;
/** The new name of the variable */
newName: string;
}
/**
* Returns an object whose `changes` property holds an array of `{file, start, end, text}` objects, which
* give the changes that must be performed to apply the rename. The client is responsible for doing the actual modification.
*/
interface RenameQueryResult {
/** Array of changes that must be performed to apply the rename. The client is responsible for doing the actual modification. */
changes: Array<{
file: string,
start: number | Position,
end: number | Position,
text: string
}>;
}
/** Get a list of all known object property names (for any object). */
export interface PropertiesQuery extends BaseQuery {
/** Get a list of all known object property names (for any object). */
type: "properties";
/** Causes the server to only return properties that start with the given string. */
prefix?: string;
/** Whether the result should be sorted. Default `true` */
sort?: boolean;
}
interface PropertiesQueryResult {
/** The property names. */
completions: string[];
}
/** Get the files that the server currently holds in its set of analyzed files. */
export interface FilesQuery extends BaseQuery {
/** Get the files that the server currently holds in its set of analyzed files. */
type: "files";
docFormat?: never;
lineCharPositions?: never;
}
interface FilesQueryResult {
/** The file names. */
files: string[];
}
export interface Events {
/** When the server throws away its current analysis data and starts a fresh run. */
reset(): void;
/** Before analyzing a file. file is an object holding {name, text, scope} properties. */
beforeLoad(file: File): void;
/** After analyzing a file. */
afterLoad(file: File): void;
/**
* Will be run right before a file is parsed, and passed the given text and options. If a handler
* returns a new text value, the origin text will be overriden. This is useful for
* instance when a plugin is able to extract JavaScript content from an HTML file.
*/
preParse(text: string, options: object): string | void;
/** Run right after a file is parsed, and passed the parse tree and the parsed file as arguments. */
postParse(ast: ESTree.Program, text: string): void;
/** Run right before the type inference pass, passing the syntax tree and a scope object. */
preInfer(ast: ESTree.Program, scope: Scope): void;
/** Run after the type inference pass. */
postInfer(ast: ESTree.Program, scope: Scope): void;
/**
* Run after Tern attempts to find the type at the position end in the given file.
* A handler may return either the given type (already calculated by Tern and earlier "typeAt" passes)
* or an alternate type to be used instead. This is useful when
* a plugin can provide a more helpful type than Tern (e.g. within comments).
*/
typeAt(file: File, end: Position, expr: ESTree.Node, type: Type): Type | void;
/** Run at the start of a completion query. May return a valid completion result to replace the default completion algorithm. */
completion(file: File, query: Query): CompletionsQueryResult | void;
}
export const version: string;
// ###### Plugins ########
/**
* This can be used to register an initialization function for the plugin with the given name.
* A Tern server, when configured to load this plugin, will call this initialization function,
* passing in the server instance and the options specified for the plugin (if any). This is the
* place where you register event handlers on the server, add type definitions, load other
* plugins as dependencies, and/or initialize the plugin’s state.
*
* See the server’s [list of events](http://ternjs.net/doc/manual.html#events) for ways to wire up plugin behavior.
*/
export function registerPlugin(name: string, init: (server: Server, options?: ConstructorOptions) => void): void;
interface Desc<T extends Query["type"]> {
run(Server: Server, query: QueryRegistry[T]["query"], file?: File): QueryRegistry[T]["result"];
takesfile?: boolean;
}
/**
* Defines a new type of query with the server. The `desc` object is a property describing the request.
* It should at least have a `run` property, which holds a function fn(Server, query) that will
* be called to handle queries with a type property that matches the given `name`. It may also have
* a `takesFile` property which, if true, will cause the server to try and resolve the file on which
* the query operates (from its file property) and pass that (a {name, text, scope, ast} object) as
* a third argument to the run function. You will probably need to use the inference
* module’s API to do someting useful in this function.
*
* To be able to use this function and the `request` function in a useful way, you probably want
* to define an interface for the query and the result of the query and extend the interface `QueryRegistry` via
* [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html)
* in the following manner:
*
* ```typescript
* declare module "tern/lib/tern" {
* interface QueryRegistry {
* [CustomQueryType]: {
* query: CustomQuery
* result: CustomQueryResult
* }
* }
* }
* ```
* _Note that your query interface should extend_ `BaseQuery` _and that its_ `type` _property has to be spelled
* exactly like the key in the_ `QueryRegistry` _interface._
*/
export function defineQueryType<T extends Query["type"]>(name: T, desc: Desc<T>): void;
+55
View File
@@ -0,0 +1,55 @@
import * as tern from "tern";
const server: tern.Server = null as any;
server.request({
query: {
type: "completions",
file: "",
end: 0
}
}, (error, response) => {
if (response && response.isProperty) {
//
}
});
server.request({
}, (error, response) => {
// $ExpectError
if (response && response.isProperty) {
//
}
});
declare module "tern/lib/tern" {
interface QueryRegistry {
someUnknownType: {
query: {
type: "someUnknownType"
},
result: {
abc: boolean
}
};
}
}
server.request({
query: {
type: "someUnknownType"
}
}, (error, response) => {
if (response && response.abc) {
//
}
});
server.request({
query: undefined
}, (error, response) => {
// $ExpectError
if (response && response.isProperty) {
//
}
});
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"lib/tern/index.d.ts",
"lib/infer/index.d.ts",
"test/tern.test.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}