1
0
Fork 0

Compare commits

..

No commits in common. "master" and "v5.3.6" have entirely different histories.

126 changed files with 2164 additions and 8352 deletions

3
.gitattributes vendored
View File

@ -3,6 +3,7 @@
/.vscode export-ignore
/fixtures export-ignore
/images export-ignore
/tests export-ignore
/validation export-ignore
/.dockerignore export-ignore
/.editorconfig export-ignore
@ -10,9 +11,7 @@
/.gitignore export-ignore
/.gitmodules export-ignore
/.npmrc export-ignore
/.phan export-ignore
/.travis.yml export-ignore
/appveyor.yml export-ignore
/codecov.yml export-ignore
/dependencies.yml export-ignore
/Dockerfile export-ignore

1
.npmrc Normal file
View File

@ -0,0 +1 @@
package-lock=false

View File

@ -1,308 +0,0 @@
<?php
use Phan\Issue;
/**
* This configuration file was automatically generated by 'phan --init --init-level=1'
*
* TODOs (added by 'phan --init'):
*
* - Go through this file and verify that there are no missing/unnecessary files/directories.
* (E.g. this only includes direct composer dependencies - You may have to manually add indirect composer dependencies to 'directory_list')
* - Look at 'plugins' and add or remove plugins if appropriate (see https://github.com/phan/phan/tree/master/.phan/plugins#plugins)
* - Add global suppressions for pre-existing issues to suppress_issue_types (https://github.com/phan/phan/wiki/Tutorial-for-Analyzing-a-Large-Sloppy-Code-Base)
*
* This configuration will be read and overlayed on top of the
* default configuration. Command line arguments will be applied
* after this file is read.
*
* @see src/Phan/Config.php
* See Config for all configurable options.
*
* A Note About Paths
* ==================
*
* Files referenced from this file should be defined as
*
* ```
* Config::projectPath('relative_path/to/file')
* ```
*
* where the relative path is relative to the root of the
* project which is defined as either the working directory
* of the phan executable or a path passed in via the CLI
* '-d' flag.
*/
return [
// Supported values: '7.0', '7.1', '7.2', null.
// If this is set to null,
// then Phan assumes the PHP version which is closest to the minor version
// of the php executable used to execute phan.
// Automatically inferred from composer.json requirement for "php" of "^7.0"
'target_php_version' => '7.0',
// If enabled, missing properties will be created when
// they are first seen. If false, we'll report an
// error message if there is an attempt to write
// to a class property that wasn't explicitly
// defined.
'allow_missing_properties' => false,
// If enabled, null can be cast as any type and any
// type can be cast to null. Setting this to true
// will cut down on false positives.
'null_casts_as_any_type' => false,
// If enabled, allow null to be cast as any array-like type.
// This is an incremental step in migrating away from null_casts_as_any_type.
// If null_casts_as_any_type is true, this has no effect.
'null_casts_as_array' => false,
// If enabled, allow any array-like type to be cast to null.
// This is an incremental step in migrating away from null_casts_as_any_type.
// If null_casts_as_any_type is true, this has no effect.
'array_casts_as_null' => false,
// If enabled, scalars (int, float, bool, string, null)
// are treated as if they can cast to each other.
// This does not affect checks of array keys. See scalar_array_key_cast.
'scalar_implicit_cast' => false,
// If enabled, any scalar array keys (int, string)
// are treated as if they can cast to each other.
// E.g. array<int,stdClass> can cast to array<string,stdClass> and vice versa.
// Normally, a scalar type such as int could only cast to/from int and mixed.
'scalar_array_key_cast' => false,
// If this has entries, scalars (int, float, bool, string, null)
// are allowed to perform the casts listed.
// E.g. ['int' => ['float', 'string'], 'float' => ['int'], 'string' => ['int'], 'null' => ['string']]
// allows casting null to a string, but not vice versa.
// (subset of scalar_implicit_cast)
'scalar_implicit_partial' => [],
// If true, seemingly undeclared variables in the global
// scope will be ignored. This is useful for projects
// with complicated cross-file globals that you have no
// hope of fixing.
'ignore_undeclared_variables_in_global_scope' => false,
// Backwards Compatibility Checking. This is slow
// and expensive, but you should consider running
// it before upgrading your version of PHP to a
// new version that has backward compatibility
// breaks.
'backward_compatibility_checks' => false,
// If true, check to make sure the return type declared
// in the doc-block (if any) matches the return type
// declared in the method signature.
'check_docblock_signature_return_type_match' => true,
// (*Requires check_docblock_signature_param_type_match to be true*)
// If true, make narrowed types from phpdoc params override
// the real types from the signature, when real types exist.
// (E.g. allows specifying desired lists of subclasses,
// or to indicate a preference for non-nullable types over nullable types)
// Affects analysis of the body of the method and the param types passed in by callers.
'prefer_narrowed_phpdoc_param_type' => true,
// (*Requires check_docblock_signature_return_type_match to be true*)
// If true, make narrowed types from phpdoc returns override
// the real types from the signature, when real types exist.
// (E.g. allows specifying desired lists of subclasses,
// or to indicate a preference for non-nullable types over nullable types)
// Affects analysis of return statements in the body of the method and the return types passed in by callers.
'prefer_narrowed_phpdoc_return_type' => true,
'ensure_signature_compatibility' => true,
// Set to true in order to attempt to detect dead
// (unreferenced) code. Keep in mind that the
// results will only be a guess given that classes,
// properties, constants and methods can be referenced
// as variables (like `$class->$property` or
// `$class->$method()`) in ways that we're unable
// to make sense of.
'dead_code_detection' => false,
// If true, this run a quick version of checks that takes less
// time at the cost of not running as thorough
// an analysis. You should consider setting this
// to true only when you wish you had more **undiagnosed** issues
// to fix in your code base.
//
// In quick-mode the scanner doesn't rescan a function
// or a method's code block every time a call is seen.
// This means that the problem here won't be detected:
//
// ```php
// <?php
// function test($arg):int {
// return $arg;
// }
// test("abc");
// ```
//
// This would normally generate:
//
// ```sh
// test.php:3 TypeError return string but `test()` is declared to return int
// ```
//
// The initial scan of the function's code block has no
// type information for `$arg`. It isn't until we see
// the call and rescan test()'s code block that we can
// detect that it is actually returning the passed in
// `string` instead of an `int` as declared.
'quick_mode' => false,
// If true, then before analysis, try to simplify AST into a form
// which improves Phan's type inference in edge cases.
//
// This may conflict with 'dead_code_detection'.
// When this is true, this slows down analysis slightly.
//
// E.g. rewrites `if ($a = value() && $a > 0) {...}`
// into $a = value(); if ($a) { if ($a > 0) {...}}`
'simplify_ast' => true,
// Enable or disable support for generic templated
// class types.
'generic_types_enabled' => true,
// Override to hardcode existence and types of (non-builtin) globals in the global scope.
// Class names should be prefixed with '\\'.
// (E.g. ['_FOO' => '\\FooClass', 'page' => '\\PageClass', 'userId' => 'int'])
'globals_type_map' => [],
// The minimum severity level to report on. This can be
// set to Issue::SEVERITY_LOW, Issue::SEVERITY_NORMAL or
// Issue::SEVERITY_CRITICAL. Setting it to only
// critical issues is a good place to start on a big
// sloppy mature code base.
'minimum_severity' => Issue::SEVERITY_LOW,
// Add any issue types (such as 'PhanUndeclaredMethod')
// to this black-list to inhibit them from being reported.
'suppress_issue_types' => [
'PhanTypeMismatchDeclaredParamNullable',
'PhanUndeclaredProperty', // 66 occurence(s) (e.g. not being specific enough about the subclass)
'PhanUndeclaredMethod', // 32 occurence(s) (e.g. not being specific enough about the subclass of Node)
'PhanTypeMismatchArgument', // 21 occurence(s)
'PhanTypeMismatchProperty', // 13 occurence(s)
'PhanUnreferencedUseNormal', // 10 occurence(s) TODO: Fix
'PhanTypeMismatchDeclaredReturn', // 8 occurence(s)
'PhanUndeclaredTypeProperty', // 7 occurence(s)
'PhanTypeMismatchReturn', // 6 occurence(s)
'PhanUndeclaredVariable', // 4 occurence(s)
'PhanUndeclaredTypeReturnType', // 4 occurence(s)
'PhanParamTooMany', // 3 occurence(s)
'PhanUndeclaredTypeParameter', // 2 occurence(s)
'PhanUndeclaredClassProperty', // 2 occurence(s)
'PhanTypeSuspiciousStringExpression', // 2 occurence(s)
'PhanTypeMismatchArgumentInternal', // 2 occurence(s)
'PhanUnextractableAnnotationElementName', // 1 occurence(s)
'PhanUndeclaredClassMethod', // 1 occurence(s)
'PhanUndeclaredClassInstanceof', // 1 occurence(s)
'PhanTypeSuspiciousNonTraversableForeach', // 1 occurence(s)
'PhanTypeMismatchDimAssignment', // 1 occurence(s)
'PhanTypeMismatchDeclaredParam', // 1 occurence(s)
'PhanTypeInvalidDimOffset', // 1 occurence(s)
],
// A regular expression to match files to be excluded
// from parsing and analysis and will not be read at all.
//
// This is useful for excluding groups of test or example
// directories/files, unanalyzable files, or files that
// can't be removed for whatever reason.
// (e.g. '@Test\.php$@', or '@vendor/.*/(tests|Tests)/@')
'exclude_file_regex' => '@^vendor/.*/(tests?|Tests?)/@',
// A file list that defines files that will be excluded
// from parsing and analysis and will not be read at all.
//
// This is useful for excluding hopelessly unanalyzable
// files that can't be removed for whatever reason.
'exclude_file_list' => [],
// A directory list that defines files that will be excluded
// from static analysis, but whose class and method
// information should be included.
//
// Generally, you'll want to include the directories for
// third-party code (such as "vendor/") in this list.
//
// n.b.: If you'd like to parse but not analyze 3rd
// party code, directories containing that code
// should be added to the `directory_list` as
// to `excluce_analysis_directory_list`.
'exclude_analysis_directory_list' => [
'vendor/',
],
// The number of processes to fork off during the analysis
// phase.
'processes' => 1,
// List of case-insensitive file extensions supported by Phan.
// (e.g. php, html, htm)
'analyzed_file_extensions' => [
'php',
],
// You can put paths to stubs of internal extensions in this config option.
// If the corresponding extension is **not** loaded, then phan will use the stubs instead.
// Phan will continue using its detailed type annotations,
// but load the constants, classes, functions, and classes (and their Reflection types)
// from these stub files (doubling as valid php files).
// Use a different extension from php to avoid accidentally loading these.
// The 'tools/make_stubs' script can be used to generate your own stubs (compatible with php 7.0+ right now)
'autoload_internal_extension_signatures' => [],
// A list of plugin files to execute
// Plugins which are bundled with Phan can be added here by providing their name (e.g. 'AlwaysReturnPlugin')
// Alternately, you can pass in the full path to a PHP file with the plugin's implementation (e.g. 'vendor/phan/phan/.phan/plugins/AlwaysReturnPlugin.php')
'plugins' => [
'AlwaysReturnPlugin',
'DollarDollarPlugin',
'DuplicateArrayKeyPlugin',
'PregRegexCheckerPlugin',
'PrintfCheckerPlugin',
'UnreachableCodePlugin',
],
// A list of directories that should be parsed for class and
// method information. After excluding the directories
// defined in exclude_analysis_directory_list, the remaining
// files will be statically analyzed for errors.
//
// Thus, both first-party and third-party code being used by
// your application should be included in this list.
'directory_list' => [
'src',
'vendor/composer/xdebug-handler/src',
'vendor/felixfbecker/advanced-json-rpc/lib',
'vendor/felixfbecker/language-server-protocol/src/',
'vendor/microsoft/tolerant-php-parser/src',
'vendor/netresearch/jsonmapper/src',
'vendor/phpdocumentor/reflection-common/src',
'vendor/phpdocumentor/reflection-docblock/src',
'vendor/phpdocumentor/type-resolver/src',
'vendor/phpunit/phpunit/src',
'vendor/psr/log/Psr',
'vendor/sabre/event/lib',
'vendor/sabre/uri/lib',
'vendor/webmozart/glob/src',
'vendor/webmozart/path-util/src',
],
// A list of individual files to include in analysis
// with a path relative to the root directory of the
// project
'file_list' => [
'bin/php-language-server.php',
],
];

View File

@ -1,8 +1,9 @@
language: php
php:
- '7.0'
- '7.2'
- '7.2.0RC5'
git:
depth: 10
@ -16,11 +17,8 @@ cache:
install:
- composer install --prefer-dist --no-interaction
- pecl install ast-1.0.0
script:
- vendor/bin/phpcs -n
- vendor/bin/phan
- vendor/bin/phpunit --coverage-clover=coverage.xml --colors=always
- bash <(curl -s https://codecov.io/bash)
@ -33,9 +31,9 @@ jobs:
before_install:
# Fix ruby error https://github.com/Homebrew/brew/issues/3299
- brew update
- brew install php@7.1
- brew link --force --overwrite php@7.1
- pecl install xdebug-2.6.0
- brew tap homebrew/homebrew-php
- brew install php71
- brew install homebrew/php/php71-xdebug
- php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
- php composer-setup.php
- ln -s "`pwd`/composer.phar" /usr/local/bin/composer
@ -44,11 +42,13 @@ jobs:
services:
- docker
install:
- composer install --prefer-dist --no-interaction
- nvm install 8
- nvm use 8
- npm install
script:
- ./node_modules/.bin/semantic-release
- docker build -t felixfbecker/php-language-server .
- npm run semantic-release
stages:
- test

View File

@ -1,19 +1,17 @@
# Running this container will start a language server that listens for TCP connections on port 2088
# Every connection will be run in a forked child process
FROM composer AS builder
COPY ./ /app
RUN composer install
# Please note that before building the image, you have to install dependencies with `composer install`
FROM php:7-cli
LABEL maintainer="Felix Becker <felix.b@outlook.com>"
MAINTAINER Felix Becker <felix.b@outlook.com>
RUN docker-php-ext-configure pcntl --enable-pcntl
RUN docker-php-ext-install pcntl
COPY ./php.ini /usr/local/etc/php/conf.d/
COPY --from=builder /app /srv/phpls
COPY ./ /srv/phpls
WORKDIR /srv/phpls

View File

@ -1,31 +1,23 @@
<?php
namespace LanguageServer\Tests;
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/vendor/autoload.php';
use Composer\XdebugHandler\XdebugHandler;
use Exception;
use LanguageServer\DefinitionResolver;
use LanguageServer\Index\Index;
use LanguageServer\PhpDocument;
use LanguageServer\StderrLogger;
use LanguageServer\DefinitionResolver;
use Microsoft\PhpParser;
use phpDocumentor\Reflection\DocBlockFactory;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
$logger = new StderrLogger();
$xdebugHandler = new XdebugHandler('PHPLS');
$xdebugHandler->setLogger($logger);
$xdebugHandler->check();
unset($xdebugHandler);
$totalSize = 0;
$frameworks = ["drupal", "wordpress", "php-language-server", "tolerant-php-parser", "math-php", "symfony", "codeigniter", "cakephp"];
foreach($frameworks as $framework) {
$iterator = new RecursiveDirectoryIterator(__DIR__ . "/../validation/frameworks/$framework");
$iterator = new RecursiveDirectoryIterator(__DIR__ . "/validation/frameworks/$framework");
$testProviderArray = array();
foreach (new RecursiveIteratorIterator($iterator) as $file) {
@ -45,8 +37,8 @@ foreach($frameworks as $framework) {
if (filesize($testCaseFile) > 10000) {
continue;
}
if ($idx % 500 === 0) {
echo $idx . '/' . count($testProviderArray) . PHP_EOL;
if ($idx % 1000 === 0) {
echo "$idx\n";
}
$fileContents = file_get_contents($testCaseFile);
@ -59,7 +51,11 @@ foreach($frameworks as $framework) {
$definitionResolver = new DefinitionResolver($index);
$parser = new PhpParser\Parser();
try {
$document = new PhpDocument($testCaseFile, $fileContents, $index, $parser, $docBlockFactory, $definitionResolver);
} catch (\Throwable $e) {
continue;
}
}
echo "------------------------------\n";

View File

@ -4,6 +4,7 @@
[![Linux Build Status](https://travis-ci.org/felixfbecker/php-language-server.svg?branch=master)](https://travis-ci.org/felixfbecker/php-language-server)
[![Windows Build status](https://ci.appveyor.com/api/projects/status/2sp5ll052wdjqmdm/branch/master?svg=true)](https://ci.appveyor.com/project/felixfbecker/php-language-server/branch/master)
[![Coverage](https://codecov.io/gh/felixfbecker/php-language-server/branch/master/graph/badge.svg)](https://codecov.io/gh/felixfbecker/php-language-server)
[![Dependency Status](https://gemnasium.com/badges/github.com/felixfbecker/php-language-server.svg)](https://gemnasium.com/github.com/felixfbecker/php-language-server)
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
[![Minimum PHP Version](https://img.shields.io/badge/php-%3E%3D%207.0-8892BF.svg)](https://php.net/)
[![License](https://img.shields.io/packagist/l/felixfbecker/language-server.svg)](https://github.com/felixfbecker/php-language-server/blob/master/LICENSE.txt)
@ -16,16 +17,6 @@ Uses the great [Tolerant PHP Parser](https://github.com/Microsoft/tolerant-php-p
[phpDocumentor's DocBlock reflection](https://github.com/phpDocumentor/ReflectionDocBlock)
and an [event loop](http://sabre.io/event/loop/) for concurrency.
**Table of Contents**
- [Features](#features)
- [Performance](#performance)
- [Versioning](#versioning)
- [Installation](#installation)
- [Running](#running)
- [Used by](#used-by)
- [Contributing](#contributing)
## Features
### [Completion](https://github.com/Microsoft/language-server-protocol/blob/master/protocol.md#textDocument_completion)
@ -220,6 +211,6 @@ The project parses PHPStorm's PHP stubs to get support for PHP builtins. It re-p
To debug with xDebug ensure that you have this set as an environment variable
PHPLS_ALLOW_XDEBUG=1
COMPOSER_ALLOW_XDEBUG=1
This tells the Language Server to not restart without XDebug if it detects that XDebug is enabled (XDebug has a high performance impact).

View File

@ -1,89 +0,0 @@
<?php
namespace LanguageServer\Tests;
require __DIR__ . '/../vendor/autoload.php';
use Composer\XdebugHandler\XdebugHandler;
use Exception;
use LanguageServer\CompletionProvider;
use LanguageServer\DefinitionResolver;
use LanguageServer\Index\Index;
use LanguageServer\PhpDocument;
use LanguageServer\StderrLogger;
use LanguageServerProtocol\Position;
use Microsoft\PhpParser;
use phpDocumentor\Reflection\DocBlockFactory;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
$logger = new StderrLogger();
$xdebugHandler = new XdebugHandler('PHPLS');
$xdebugHandler->setLogger($logger);
$xdebugHandler->check();
unset($xdebugHandler);
$totalSize = 0;
$framework = "symfony";
$iterator = new RecursiveDirectoryIterator(__DIR__ . "/../validation/frameworks/$framework");
$testProviderArray = array();
foreach (new RecursiveIteratorIterator($iterator) as $file) {
if (strpos((string)$file, ".php") !== false) {
$totalSize += $file->getSize();
$testProviderArray[] = $file->getRealPath();
}
}
if (count($testProviderArray) === 0) {
throw new Exception("ERROR: Validation testsuite frameworks not found - run `git submodule update --init --recursive` to download.");
}
$index = new Index;
$definitionResolver = new DefinitionResolver($index);
$completionProvider = new CompletionProvider($definitionResolver, $index);
$docBlockFactory = DocBlockFactory::createInstance();
$completionFile = realpath(__DIR__ . '/../validation/frameworks/symfony/src/Symfony/Component/HttpFoundation/Request.php');
$parser = new PhpParser\Parser();
$completionDocument = null;
echo "Indexing $framework" . PHP_EOL;
foreach ($testProviderArray as $idx => $testCaseFile) {
if (filesize($testCaseFile) > 100000) {
continue;
}
if ($idx % 100 === 0) {
echo $idx . '/' . count($testProviderArray) . PHP_EOL;
}
$fileContents = file_get_contents($testCaseFile);
try {
$d = new PhpDocument($testCaseFile, $fileContents, $index, $parser, $docBlockFactory, $definitionResolver);
if ($testCaseFile === $completionFile) {
$completionDocument = $d;
}
} catch (\Throwable $e) {
echo $e->getMessage() . PHP_EOL;
continue;
}
}
echo "Getting completion". PHP_EOL;
// Completion in $this->|request = new ParameterBag($request);
$start = microtime(true);
$list = $completionProvider->provideCompletion($completionDocument, new Position(274, 15));
$end = microtime(true);
echo 'Time ($this->|): ' . ($end - $start) . 's' . PHP_EOL;
echo count($list->items) . ' completion items' . PHP_EOL;
// Completion in $this->request = new| ParameterBag($request);
// (this only finds ParameterBag though.)
$start = microtime(true);
$list = $completionProvider->provideCompletion($completionDocument, new Position(274, 28));
$end = microtime(true);
echo 'Time (new|): ' . ($end - $start) . 's' . PHP_EOL;
echo count($list->items) . ' completion items' . PHP_EOL;

View File

@ -1,8 +1,8 @@
<?php
use LanguageServer\{LanguageServer, ProtocolStreamReader, ProtocolStreamWriter, StderrLogger};
use LanguageServer\{LanguageServer, ProtocolStreamReader, ProtocolStreamWriter};
use Sabre\Event\Loop;
use Composer\XdebugHandler\XdebugHandler;
use Composer\{Factory, XdebugHandler};
$options = getopt('', ['tcp::', 'tcp-server::', 'memory-limit::']);
@ -24,27 +24,22 @@ set_error_handler(function (int $severity, string $message, string $file, int $l
throw new \ErrorException($message, 0, $severity, $file, $line);
});
$logger = new StderrLogger();
// Only write uncaught exceptions to STDERR, not STDOUT
set_exception_handler(function (\Throwable $e) use ($logger) {
$logger->critical((string)$e);
set_exception_handler(function (\Throwable $e) {
fwrite(STDERR, (string)$e);
});
@cli_set_process_title('PHP Language Server');
// If XDebug is enabled, restart without it
$xdebugHandler = new XdebugHandler('PHPLS');
$xdebugHandler->setLogger($logger);
$xdebugHandler->check();
unset($xdebugHandler);
(new XdebugHandler(Factory::createOutput()))->check();
if (!empty($options['tcp'])) {
// Connect to a TCP server
$address = $options['tcp'];
$socket = stream_socket_client('tcp://' . $address, $errno, $errstr);
if ($socket === false) {
$logger->critical("Could not connect to language client. Error $errno\n$errstr");
fwrite(STDERR, "Could not connect to language client. Error $errno\n$errstr");
exit(1);
}
stream_set_blocking($socket, false);
@ -58,30 +53,29 @@ if (!empty($options['tcp'])) {
$address = $options['tcp-server'];
$tcpServer = stream_socket_server('tcp://' . $address, $errno, $errstr);
if ($tcpServer === false) {
$logger->critical("Could not listen on $address. Error $errno\n$errstr");
fwrite(STDERR, "Could not listen on $address. Error $errno\n$errstr");
exit(1);
}
$logger->debug("Server listening on $address");
$pcntlAvailable = extension_loaded('pcntl');
if (!$pcntlAvailable) {
$logger->notice('PCNTL is not available. Only a single connection will be accepted');
fwrite(STDOUT, "Server listening on $address\n");
if (!extension_loaded('pcntl')) {
fwrite(STDERR, "PCNTL is not available. Only a single connection will be accepted\n");
}
while ($socket = stream_socket_accept($tcpServer, -1)) {
$logger->debug('Connection accepted');
fwrite(STDOUT, "Connection accepted\n");
stream_set_blocking($socket, false);
if ($pcntlAvailable) {
if (extension_loaded('pcntl')) {
// If PCNTL is available, fork a child process for the connection
// An exit notification will only terminate the child process
$pid = pcntl_fork();
if ($pid === -1) {
$logger->critical('Could not fork');
fwrite(STDERR, "Could not fork\n");
exit(1);
} else if ($pid === 0) {
// Child process
$reader = new ProtocolStreamReader($socket);
$writer = new ProtocolStreamWriter($socket);
$reader->on('close', function () use ($logger) {
$logger->debug('Connection closed');
$reader->on('close', function () {
fwrite(STDOUT, "Connection closed\n");
});
$ls = new LanguageServer($reader, $writer);
Loop\run();
@ -100,7 +94,6 @@ if (!empty($options['tcp'])) {
}
} else {
// Use STDIO
$logger->debug('Listening on STDIN');
stream_set_blocking(STDIN, false);
$ls = new LanguageServer(
new ProtocolStreamReader(STDIN),

View File

@ -1,5 +1,5 @@
{
"name": "icedream/language-server",
"name": "felixfbecker/language-server",
"description": "PHP Implementation of the Visual Studio Code Language Server Protocol",
"license": "ISC",
"keywords": [
@ -22,14 +22,12 @@
],
"require": {
"php": "^7.0",
"composer/xdebug-handler": "^1.0",
"composer/composer": "^1.3",
"felixfbecker/advanced-json-rpc": "^3.0.0",
"felixfbecker/language-server-protocol": "^1.0.1",
"jetbrains/phpstorm-stubs": "dev-master",
"microsoft/tolerant-php-parser": "0.0.*",
"netresearch/jsonmapper": "^1.0",
"phpdocumentor/reflection-docblock": "^4.0.0",
"psr/log": "^1.0",
"sabre/event": "^5.0",
"sabre/uri": "^2.0",
"webmozart/glob": "^4.1",
@ -37,12 +35,8 @@
},
"require-dev": {
"phpunit/phpunit": "^6.3",
"phan/phan": "1.1.4",
"squizlabs/php_codesniffer": "^3.1"
},
"replace": {
"felixfbecker/language-server": "self.version"
},
"autoload": {
"psr-4": {
"LanguageServer\\": "src/"

View File

@ -10,6 +10,9 @@ collectors:
commit_message_prefix: "chore: "
- type: js-npm
path: /
settings:
dist_tags:
semantic-release: next
actors:
- type: js-npm
versions: "Y.0.0"

View File

@ -1,10 +0,0 @@
<?php
namespace Whatever;
use TestNamespace\InnerNamespace as AliasNamespace;
class IDontShowUpInCompletion {}
AliasNamespace\I;
AliasNamespace\;

View File

@ -1,20 +0,0 @@
<?php
namespace RecursiveTest;
class A extends A {}
class B extends C {}
class C extends B {}
class D extends E {}
class E extends F {}
class F extends D {}
$a = new A;
$a->undef_prop = 1;
$b = new B;
$b->undef_prop = 1;
$d = new D;
$d->undef_prop = 1;

View File

@ -103,8 +103,3 @@ class Example {
public function __construct() {}
public function __destruct() {}
}
namespace TestNamespace\InnerNamespace;
class InnerClass {
}

6660
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,25 +1,31 @@
{
"name": "php-language-server",
"version": "0.0.0-development",
"private": true,
"repository": {
"type": "git",
"url": "https://github.com/felixfbecker/php-language-server.git"
"scripts": {
"commitmsg": "validate-commit-msg",
"semantic-release": "semantic-release"
},
"devDependencies": {
"@semantic-release/exec": "^3.1.0",
"semantic-release": "^15.9.9",
"semantic-release-docker": "^2.1.0"
"@semantic-release/github": "^2.0.0",
"@semantic-release/last-release-git-tag": "^2.0.0",
"cz-conventional-changelog": "^2.0.0",
"husky": "^0.14.3",
"semantic-release": "^11.0.0",
"semantic-release-docker": "^2.0.0",
"validate-commit-msg": "^2.14.0"
},
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
},
"release": {
"verifyConditions": [
"@semantic-release/github",
"semantic-release-docker"
],
"prepare": [
{
"path": "@semantic-release/exec",
"cmd": "docker build -t felixfbecker/php-language-server ."
}
],
"getLastRelease": "@semantic-release/last-release-git-tag",
"publish": [
"@semantic-release/github",
{
@ -27,5 +33,9 @@
"name": "felixfbecker/php-language-server"
}
]
},
"repository": {
"type": "git",
"url": "https://github.com/felixfbecker/php-language-server.git"
}
}

View File

@ -11,11 +11,6 @@ use Sabre\Event\Promise;
*/
class ClientCache implements Cache
{
/**
* @var LanguageClient
*/
public $client;
/**
* @param LanguageClient $client
*/

View File

@ -3,6 +3,7 @@ declare(strict_types = 1);
namespace LanguageServer\Cache;
use LanguageServer\LanguageClient;
use Sabre\Event\Promise;
/**

View File

@ -4,7 +4,7 @@ declare(strict_types = 1);
namespace LanguageServer\Client;
use LanguageServer\ClientHandler;
use LanguageServerProtocol\{Diagnostic, TextDocumentItem, TextDocumentIdentifier};
use LanguageServer\Protocol\{Message, TextDocumentItem, TextDocumentIdentifier};
use Sabre\Event\Promise;
use JsonMapper;

View File

@ -4,6 +4,7 @@ declare(strict_types = 1);
namespace LanguageServer\Client;
use LanguageServer\ClientHandler;
use LanguageServer\Protocol\Message;
use Sabre\Event\Promise;
/**

View File

@ -4,7 +4,7 @@ declare(strict_types = 1);
namespace LanguageServer\Client;
use LanguageServer\ClientHandler;
use LanguageServerProtocol\TextDocumentIdentifier;
use LanguageServer\Protocol\TextDocumentIdentifier;
use Sabre\Event\Promise;
use JsonMapper;

View File

@ -4,6 +4,7 @@ declare(strict_types = 1);
namespace LanguageServer\Client;
use LanguageServer\ClientHandler;
use LanguageServer\Protocol\Message;
use Sabre\Event\Promise;
/**

View File

@ -41,12 +41,12 @@ class ClientHandler
{
$id = $this->idGenerator->generate();
return $this->protocolWriter->write(
new Message(
new Protocol\Message(
new AdvancedJsonRpc\Request($id, $method, (object)$params)
)
)->then(function () use ($id) {
$promise = new Promise;
$listener = function (Message $msg) use ($id, $promise, &$listener) {
$listener = function (Protocol\Message $msg) use ($id, $promise, &$listener) {
if (AdvancedJsonRpc\Response::isResponse($msg->body) && $msg->body->id === $id) {
// Received a response
$this->protocolReader->removeListener('message', $listener);
@ -72,7 +72,7 @@ class ClientHandler
public function notify(string $method, $params): Promise
{
return $this->protocolWriter->write(
new Message(
new Protocol\Message(
new AdvancedJsonRpc\Notification($method, (object)$params)
)
);

View File

@ -4,8 +4,7 @@ declare(strict_types = 1);
namespace LanguageServer;
use LanguageServer\Index\ReadableIndex;
use LanguageServer\Factory\CompletionItemFactory;
use LanguageServerProtocol\{
use LanguageServer\Protocol\{
TextEdit,
Range,
Position,
@ -17,15 +16,7 @@ use LanguageServerProtocol\{
};
use Microsoft\PhpParser;
use Microsoft\PhpParser\Node;
use Microsoft\PhpParser\ResolvedName;
use Generator;
use function LanguageServer\FqnUtilities\{
nameConcat,
nameGetFirstPart,
nameGetParent,
nameStartsWith,
nameWithoutFirstPart
};
class CompletionProvider
{
@ -100,23 +91,7 @@ class CompletionProvider
'var',
'while',
'xor',
'yield',
// List of other reserved words (http://php.net/manual/en/reserved.other-reserved-words.php)
// (the ones which do not occur as actual keywords above.)
'int',
'float',
'bool',
'string',
'void',
'iterable',
'object',
// Pseudo keywords
'from', // As in yield from
'strict_types',
'ticks', // As in declare(ticks=1)
'encoding', // As in declare(encoding='EBCDIC')
'yield'
];
/**
@ -152,11 +127,8 @@ class CompletionProvider
* @param CompletionContext $context The completion context
* @return CompletionList
*/
public function provideCompletion(
PhpDocument $doc,
Position $pos,
CompletionContext $context = null
): CompletionList {
public function provideCompletion(PhpDocument $doc, Position $pos, CompletionContext $context = null): CompletionList
{
// This can be made much more performant if the tree follows specific invariants.
$node = $doc->getNodeAtPosition($pos);
@ -248,15 +220,17 @@ class CompletionProvider
$this->definitionResolver->resolveExpressionNodeToType($node->dereferencableExpression)
);
// The FQNs of the symbol and its parents (eg the implemented interfaces)
foreach ($this->expandParentFqns($fqns) as $parentFqn) {
// Add the object access operator to only get members of all parents
$prefix = $parentFqn . '->';
$prefixLen = strlen($prefix);
// Collect fqn definitions
foreach ($this->index->getChildDefinitionsForFqn($parentFqn) as $fqn => $def) {
if (substr($fqn, 0, $prefixLen) === $prefix && $def->isMember) {
$list->items[] = CompletionItemFactory::fromDefinition($def);
$prefixes = [];
foreach ($this->expandParentFqns($fqns) as $prefix) {
$prefixes[] = $prefix . '->';
}
// Collect all definitions that match any of the prefixes
foreach ($this->index->getDefinitions() as $fqn => $def) {
foreach ($prefixes as $prefix) {
if (substr($fqn, 0, strlen($prefix)) === $prefix && $def->isMember) {
$list->items[] = CompletionItem::fromDefinition($def);
}
}
}
@ -279,15 +253,17 @@ class CompletionProvider
$classType = $this->definitionResolver->resolveExpressionNodeToType($scoped->scopeResolutionQualifier)
);
// The FQNs of the symbol and its parents (eg the implemented interfaces)
foreach ($this->expandParentFqns($fqns) as $parentFqn) {
// Append :: operator to only get static members of all parents
$prefix = strtolower($parentFqn . '::');
$prefixLen = strlen($prefix);
// Collect fqn definitions
foreach ($this->index->getChildDefinitionsForFqn($parentFqn) as $fqn => $def) {
if (substr(strtolower($fqn), 0, $prefixLen) === $prefix && $def->isMember) {
$list->items[] = CompletionItemFactory::fromDefinition($def);
$prefixes = [];
foreach ($this->expandParentFqns($fqns) as $prefix) {
$prefixes[] = $prefix . '::';
}
// Collect all definitions that match any of the prefixes
foreach ($this->index->getDefinitions() as $fqn => $def) {
foreach ($prefixes as $prefix) {
if (substr(strtolower($fqn), 0, strlen($prefix)) === strtolower($prefix) && $def->isMember) {
$list->items[] = CompletionItem::fromDefinition($def);
}
}
}
@ -304,279 +280,115 @@ class CompletionProvider
// my_func|
// MY_CONS|
// MyCla|
// \MyCla|
// The name Node under the cursor
$nameNode = isset($creation) ? $creation->classTypeDesignator : $node;
if ($nameNode instanceof Node\QualifiedName) {
/** @var string The typed name. */
$prefix = (string)PhpParser\ResolvedName::buildName($nameNode->nameParts, $nameNode->getFileContents());
} else {
$prefix = $nameNode->getText($node->getFileContents());
}
/** The typed name */
$prefix = $nameNode instanceof Node\QualifiedName
? (string)PhpParser\ResolvedName::buildName($nameNode->nameParts, $nameNode->getFileContents())
: $nameNode->getText($node->getFileContents());
$prefixLen = strlen($prefix);
/** Whether the prefix is qualified (contains at least one backslash) */
$isQualified = $nameNode instanceof Node\QualifiedName && $nameNode->isQualifiedName();
/** Whether the prefix is fully qualified (begins with a backslash) */
$isFullyQualified = $nameNode instanceof Node\QualifiedName && $nameNode->isFullyQualifiedName();
/** The closest NamespaceDefinition Node */
$namespaceNode = $node->getNamespaceDefinition();
/** @var string The current namespace without a leading backslash. */
$currentNamespace = $namespaceNode === null ? '' : $namespaceNode->name->getText();
/** @var bool Whether the prefix is qualified (contains at least one backslash) */
$isFullyQualified = false;
/** @var bool Whether the prefix is qualified (contains at least one backslash) */
$isQualified = false;
if ($nameNode instanceof Node\QualifiedName) {
$isFullyQualified = $nameNode->isFullyQualifiedName();
$isQualified = $nameNode->isQualifiedName();
/** @var string The name of the namespace */
$namespacedPrefix = null;
if ($namespaceNode) {
$namespacedPrefix = (string)PhpParser\ResolvedName::buildName($namespaceNode->name->nameParts, $node->getFileContents()) . '\\' . $prefix;
$namespacedPrefixLen = strlen($namespacedPrefix);
}
/** @var bool Whether we are in a new expression */
$isCreation = isset($creation);
// Get the namespace use statements
// TODO: use function statements, use const statements
/** @var array Import (use) tables */
$importTables = $node->getImportTablesForCurrentScope();
/** @var string[] $aliases A map from local alias to fully qualified name */
list($aliases,,) = $node->getImportTablesForCurrentScope();
if ($isFullyQualified) {
// \Prefix\Goes\Here| - Only return completions from the root namespace.
/** @var $items \Generator|CompletionItem[] Generator yielding CompletionItems indexed by their FQN */
$items = $this->getCompletionsForFqnPrefix($prefix, $isCreation, false);
} else if ($isQualified) {
// Prefix\Goes\Here|
$items = $this->getPartiallyQualifiedCompletions(
$prefix,
$currentNamespace,
$importTables,
$isCreation
);
foreach ($aliases as $alias => $name) {
$aliases[$alias] = (string)$name;
}
// If there is a prefix that does not start with a slash, suggest `use`d symbols
if ($prefix && !$isFullyQualified) {
foreach ($aliases as $alias => $fqn) {
// Suggest symbols that have been `use`d and match the prefix
if (substr($alias, 0, $prefixLen) === $prefix && ($def = $this->index->getDefinition($fqn))) {
$list->items[] = CompletionItem::fromDefinition($def);
}
}
}
// Suggest global symbols that either
// - start with the current namespace + prefix, if the Name node is not fully qualified
// - start with just the prefix, if the Name node is fully qualified
foreach ($this->index->getDefinitions() as $fqn => $def) {
$fqnStartsWithPrefix = substr($fqn, 0, $prefixLen) === $prefix;
if (
// Exclude methods, properties etc.
!$def->isMember
&& (
!$prefix
|| (
// Either not qualified, but a matching prefix with global fallback
($def->roamed && !$isQualified && $fqnStartsWithPrefix)
// Or not in a namespace or a fully qualified name or AND matching the prefix
|| ((!$namespaceNode || $isFullyQualified) && $fqnStartsWithPrefix)
// Or in a namespace, not fully qualified and matching the prefix + current namespace
|| (
$namespaceNode
&& !$isFullyQualified
&& substr($fqn, 0, $namespacedPrefixLen) === $namespacedPrefix
)
)
)
// Only suggest classes for `new`
&& (!isset($creation) || $def->canBeInstantiated)
) {
$item = CompletionItem::fromDefinition($def);
// Find the shortest name to reference the symbol
if ($namespaceNode && ($alias = array_search($fqn, $aliases, true)) !== false) {
// $alias is the name under which this definition is aliased in the current namespace
$item->insertText = $alias;
} else if ($namespaceNode && !($prefix && $isFullyQualified)) {
// Insert the global FQN with leading backslash
$item->insertText = '\\' . $fqn;
} else {
// PrefixGoesHere|
$items = $this->getUnqualifiedCompletions($prefix, $currentNamespace, $importTables, $isCreation);
// Insert the FQN without leading backlash
$item->insertText = $fqn;
}
$list->items = array_values(iterator_to_array($items));
foreach ($list->items as $item) {
// Remove ()
if (is_string($item->insertText) && substr($item->insertText, strlen($item->insertText) - 2) === '()') {
// Don't insert the parenthesis for functions
// TODO return a snippet and put the cursor inside
if (substr($item->insertText, -2) === '()') {
$item->insertText = substr($item->insertText, 0, -2);
}
}
}
return $list;
}
private function getPartiallyQualifiedCompletions(
string $prefix,
string $currentNamespace,
array $importTables,
bool $requireCanBeInstantiated
): \Generator {
// If the first part of the partially qualified name matches a namespace alias,
// only definitions below that alias can be completed.
list($namespaceAliases,,) = $importTables;
$prefixFirstPart = nameGetFirstPart($prefix);
$foundAlias = $foundAliasFqn = null;
foreach ($namespaceAliases as $alias => $aliasFqn) {
if (strcasecmp($prefixFirstPart, $alias) === 0) {
$foundAlias = $alias;
$foundAliasFqn = (string)$aliasFqn;
break;
$list->items[] = $item;
}
}
if ($foundAlias !== null) {
yield from $this->getCompletionsFromAliasedNamespace(
$prefix,
$foundAlias,
$foundAliasFqn,
$requireCanBeInstantiated
);
} else {
yield from $this->getCompletionsForFqnPrefix(
nameConcat($currentNamespace, $prefix),
$requireCanBeInstantiated,
false
);
}
}
/**
* Yields completions for non-qualified global names.
*
* Yields
* - Aliased classes
* - Completions from current namespace
* - Roamed completions from the global namespace (when not creating and not already in root NS)
* - PHP keywords (when not creating)
*
* @return \Generator|CompletionItem[]
* Yields CompletionItems
*/
private function getUnqualifiedCompletions(
string $prefix,
string $currentNamespace,
array $importTables,
bool $requireCanBeInstantiated
): \Generator {
// Aliases
list($namespaceAliases,,) = $importTables;
// use Foo\Bar
yield from $this->getCompletionsForAliases(
$prefix,
$namespaceAliases,
$requireCanBeInstantiated
);
// Completions from the current namespace
yield from $this->getCompletionsForFqnPrefix(
nameConcat($currentNamespace, $prefix),
$requireCanBeInstantiated,
false
);
if ($currentNamespace !== '' && $prefix === '') {
// Get additional suggestions from the global namespace.
// When completing e.g. for new |, suggest \DateTime
yield from $this->getCompletionsForFqnPrefix('', $requireCanBeInstantiated, true);
}
if (!$requireCanBeInstantiated) {
if ($currentNamespace !== '' && $prefix !== '') {
// Roamed definitions (i.e. global constants and functions). The prefix is checked against '', since
// in that case global completions have already been provided (including non-roamed definitions.)
yield from $this->getRoamedCompletions($prefix);
}
// Lastly and least importantly, suggest keywords.
yield from $this->getCompletionsForKeywords($prefix);
}
}
/**
* Gets completions for prefixes of fully qualified names in their parent namespace.
*
* @param string $prefix Prefix to complete for. Fully qualified.
* @param bool $requireCanBeInstantiated If set, only return classes.
* @param bool $insertFullyQualified If set, return completion with the leading \ inserted.
* @return \Generator|CompletionItem[]
* Yields CompletionItems.
*/
private function getCompletionsForFqnPrefix(
string $prefix,
bool $requireCanBeInstantiated,
bool $insertFullyQualified
): \Generator {
$namespace = nameGetParent($prefix);
foreach ($this->index->getChildDefinitionsForFqn($namespace) as $fqn => $def) {
if ($requireCanBeInstantiated && !$def->canBeInstantiated) {
continue;
}
if (!nameStartsWith($fqn, $prefix)) {
continue;
}
$completion = CompletionItemFactory::fromDefinition($def);
if ($insertFullyQualified) {
$completion->insertText = '\\' . $fqn;
}
yield $fqn => $completion;
}
}
/**
* Gets completions for non-qualified names matching the start of an used class, function, or constant.
*
* @param string $prefix Non-qualified name being completed for
* @param QualifiedName[] $aliases Array of alias FQNs indexed by the alias.
* @return \Generator|CompletionItem[]
* Yields CompletionItems.
*/
private function getCompletionsForAliases(
string $prefix,
array $aliases,
bool $requireCanBeInstantiated
): \Generator {
foreach ($aliases as $alias => $aliasFqn) {
if (!nameStartsWith($alias, $prefix)) {
continue;
}
$definition = $this->index->getDefinition((string)$aliasFqn);
if ($definition) {
if ($requireCanBeInstantiated && !$definition->canBeInstantiated) {
continue;
}
$completionItem = CompletionItemFactory::fromDefinition($definition);
$completionItem->insertText = $alias;
yield (string)$aliasFqn => $completionItem;
}
}
}
/**
* Gets completions for partially qualified names, where the first part is matched by an alias.
*
* @return \Generator|CompletionItem[]
* Yields CompletionItems.
*/
private function getCompletionsFromAliasedNamespace(
string $prefix,
string $alias,
string $aliasFqn,
bool $requireCanBeInstantiated
): \Generator {
$prefixFirstPart = nameGetFirstPart($prefix);
// Matched alias.
$resolvedPrefix = nameConcat($aliasFqn, nameWithoutFirstPart($prefix));
$completionItems = $this->getCompletionsForFqnPrefix(
$resolvedPrefix,
$requireCanBeInstantiated,
false
);
// Convert FQNs in the CompletionItems so they are expressed in terms of the alias.
foreach ($completionItems as $fqn => $completionItem) {
/** @var string $fqn with the leading parts determined by the alias removed. Has the leading backslash. */
$nameWithoutAliasedPart = substr($fqn, strlen($aliasFqn));
$completionItem->insertText = $alias . $nameWithoutAliasedPart;
yield $fqn => $completionItem;
}
}
/**
* Gets completions for globally defined functions and constants (i.e. symbols which may be used anywhere)
*
* @return \Generator|CompletionItem[]
* Yields CompletionItems.
*/
private function getRoamedCompletions(string $prefix): \Generator
{
foreach ($this->index->getChildDefinitionsForFqn('') as $fqn => $def) {
if (!$def->roamed || !nameStartsWith($fqn, $prefix)) {
continue;
}
$completionItem = CompletionItemFactory::fromDefinition($def);
// Second-guessing the user here - do not trust roaming to work. If the same symbol is
// inserted in the current namespace, the code will stop working.
$completionItem->insertText = '\\' . $fqn;
yield $fqn => $completionItem;
}
}
/**
* Completes PHP keywords.
*
* @return \Generator|CompletionItem[]
* Yields CompletionItems.
*/
private function getCompletionsForKeywords(string $prefix): \Generator
{
// If not a class instantiation, also suggest keywords
if (!isset($creation)) {
foreach (self::KEYWORDS as $keyword) {
if (nameStartsWith($keyword, $prefix)) {
if (substr($keyword, 0, $prefixLen) === $prefix) {
$item = new CompletionItem($keyword, CompletionItemKind::KEYWORD);
$item->insertText = $keyword;
yield $keyword => $item;
$list->items[] = $item;
}
}
}
}
return $list;
}
/**
* Yields FQNs from an array along with the FQNs of all parent classes
@ -644,9 +456,8 @@ class CompletionProvider
}
}
if ($level instanceof Node\Expression\AnonymousFunctionCreationExpression
&& $level->anonymousFunctionUseClause !== null
&& $level->anonymousFunctionUseClause->useVariableNameList !== null) {
if ($level instanceof Node\Expression\AnonymousFunctionCreationExpression && $level->anonymousFunctionUseClause !== null &&
$level->anonymousFunctionUseClause->useVariableNameList !== null) {
foreach ($level->anonymousFunctionUseClause->useVariableNameList->getValues() as $use) {
$useName = $use->getName();
if (empty($namePrefix) || strpos($useName, $namePrefix) !== false) {

View File

@ -4,7 +4,7 @@ declare(strict_types = 1);
namespace LanguageServer\ContentRetriever;
use LanguageServer\LanguageClient;
use LanguageServerProtocol\{TextDocumentIdentifier, TextDocumentItem};
use LanguageServer\Protocol\{TextDocumentIdentifier, TextDocumentItem};
use Sabre\Event\Promise;
/**

View File

@ -4,8 +4,9 @@ declare(strict_types = 1);
namespace LanguageServer;
use LanguageServer\Index\ReadableIndex;
use phpDocumentor\Reflection\{Types, Type, TypeResolver};
use LanguageServerProtocol\SymbolInformation;
use phpDocumentor\Reflection\{Types, Type, Fqsen, TypeResolver};
use LanguageServer\Protocol\SymbolInformation;
use Exception;
use Generator;
/**
@ -68,7 +69,7 @@ class Definition
public $canBeInstantiated;
/**
* @var SymbolInformation
* @var Protocol\SymbolInformation
*/
public $symbolInformation;
@ -80,7 +81,7 @@ class Definition
* Can also be a compound type.
* If it is unknown, will be Types\Mixed_.
*
* @var Type|null
* @var \phpDocumentor\Type|null
*/
public $type;

View File

@ -4,8 +4,7 @@ declare(strict_types = 1);
namespace LanguageServer;
use LanguageServer\Index\ReadableIndex;
use LanguageServer\Factory\SymbolInformationFactory;
use LanguageServerProtocol\SymbolInformation;
use LanguageServer\Protocol\SymbolInformation;
use Microsoft\PhpParser;
use Microsoft\PhpParser\Node;
use Microsoft\PhpParser\FunctionLike;
@ -37,7 +36,7 @@ class DefinitionResolver
private $docBlockFactory;
/**
* Creates SignatureInformation instances
* Creates SignatureInformation
*
* @var SignatureInformationFactory
*/
@ -234,7 +233,7 @@ class DefinitionResolver
}
}
$def->symbolInformation = SymbolInformationFactory::fromNode($node, $fqn);
$def->symbolInformation = SymbolInformation::fromNode($node, $fqn);
if ($def->symbolInformation !== null) {
$def->type = $this->getTypeFromNode($node);
@ -438,7 +437,6 @@ class DefinitionResolver
// Find the right class that implements the member
$implementorFqns = [$classFqn];
$visitedFqns = [];
while ($implementorFqn = array_shift($implementorFqns)) {
// If the member FQN exists, return it
@ -451,18 +449,13 @@ class DefinitionResolver
if ($implementorDef === null) {
break;
}
// Note the FQN as visited
$visitedFqns[] = $implementorFqn;
// Repeat for parent class
if ($implementorDef->extends) {
foreach ($implementorDef->extends as $extends) {
// Don't add the parent FQN if it's already been visited
if (!\in_array($extends, $visitedFqns)) {
$implementorFqns[] = $extends;
}
}
}
}
return $classFqn . $memberSuffix;
}
@ -1239,13 +1232,7 @@ class DefinitionResolver
if (
$node instanceof PhpParser\ClassLike
) {
$className = (string)$node->getNamespacedName();
// An (invalid) class declaration without a name will have an empty string as name,
// but should not define an FQN
if ($className === '') {
return null;
}
return $className;
return (string) $node->getNamespacedName();
}
// INPUT OUTPUT:

View File

@ -1,36 +0,0 @@
<?php
namespace LanguageServer\Factory;
use LanguageServer\Definition;
use LanguageServerProtocol\CompletionItem;
use LanguageServerProtocol\CompletionItemKind;
use LanguageServerProtocol\SymbolKind;
class CompletionItemFactory
{
/**
* Creates a CompletionItem for a Definition
*
* @param Definition $def
* @return CompletionItem|null
*/
public static function fromDefinition(Definition $def)
{
$item = new CompletionItem;
$item->label = $def->symbolInformation->name;
$item->kind = CompletionItemKind::fromSymbolKind($def->symbolInformation->kind);
if ($def->type) {
$item->detail = (string)$def->type;
} else if ($def->symbolInformation->containerName) {
$item->detail = $def->symbolInformation->containerName;
}
if ($def->documentation) {
$item->documentation = $def->documentation;
}
if ($def->isStatic && $def->symbolInformation->kind === SymbolKind::PROPERTY) {
$item->insertText = '$' . $def->symbolInformation->name;
}
return $item;
}
}

View File

@ -1,32 +0,0 @@
<?php
namespace LanguageServer\Factory;
use LanguageServerProtocol\Location;
use LanguageServerProtocol\Position;
use LanguageServerProtocol\Range;
use Microsoft\PhpParser\Node;
use Microsoft\PhpParser\PositionUtilities;
class LocationFactory
{
/**
* Returns the location of the node
*
* @param Node $node
* @return self
*/
public static function fromNode(Node $node): Location
{
$range = PositionUtilities::getRangeFromPosition(
$node->getStart(),
$node->getWidth(),
$node->getFileContents()
);
return new Location($node->getUri(), new Range(
new Position($range->start->line, $range->start->character),
new Position($range->end->line, $range->end->character)
));
}
}

View File

@ -1,31 +0,0 @@
<?php
namespace LanguageServer\Factory;
use LanguageServerProtocol\Position;
use LanguageServerProtocol\Range;
use Microsoft\PhpParser\Node;
use Microsoft\PhpParser\PositionUtilities;
class RangeFactory
{
/**
* Returns the range the node spans
*
* @param Node $node
* @return self
*/
public static function fromNode(Node $node)
{
$range = PositionUtilities::getRangeFromPosition(
$node->getStart(),
$node->getWidth(),
$node->getFileContents()
);
return new Range(
new Position($range->start->line, $range->start->character),
new Position($range->end->line, $range->end->character)
);
}
}

View File

@ -3,6 +3,7 @@ declare(strict_types = 1);
namespace LanguageServer\FilesFinder;
use Webmozart\Glob\Iterator\GlobIterator;
use Sabre\Event\Promise;
use function Sabre\Event\coroutine;
use function LanguageServer\{pathToUri, timeout};
@ -22,7 +23,7 @@ class FileSystemFilesFinder implements FilesFinder
$uris = [];
foreach (new GlobIterator($glob) as $path) {
// Exclude any directories that also match the glob pattern
if (!is_dir($path) || !is_readable($path)) {
if (!is_dir($path)) {
$uris[] = pathToUri($path);
}

View File

@ -1,84 +0,0 @@
<?php
declare (strict_types = 1);
namespace LanguageServer\FilesFinder;
use ArrayIterator;
use EmptyIterator;
use IteratorIterator;
use RecursiveIteratorIterator;
use Webmozart\Glob\Glob;
use Webmozart\Glob\Iterator\GlobFilterIterator;
use Webmozart\Glob\Iterator\RecursiveDirectoryIterator;
/**
* Returns filesystem paths matching a glob.
*
* @since 1.0
*
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @see Glob
*/
class GlobIterator extends IteratorIterator
{
/**
* Creates a new iterator.
*
* @param string $glob The glob pattern.
* @param int $flags A bitwise combination of the flag constants in
* {@link Glob}.
*/
public function __construct($glob, $flags = 0)
{
$basePath = Glob::getBasePath($glob, $flags);
if (!Glob::isDynamic($glob) && file_exists($glob)) {
// If the glob is a file path, return that path
$innerIterator = new ArrayIterator(array($glob));
} elseif (is_dir($basePath)) {
// Use the system's much more efficient glob() function where we can
if (
// glob() does not support /**/
false === strpos($glob, '/**/') &&
// glob() does not support stream wrappers
false === strpos($glob, '://') &&
// glob() does not support [^...] on Windows
('\\' !== DIRECTORY_SEPARATOR || false === strpos($glob, '[^'))
) {
$results = glob($glob, GLOB_BRACE);
// $results may be empty or false if $glob is invalid
if (empty($results)) {
// Parse glob and provoke errors if invalid
Glob::toRegEx($glob);
// Otherwise return empty result set
$innerIterator = new EmptyIterator();
} else {
$innerIterator = new ArrayIterator($results);
}
} else {
// Otherwise scan the glob's base directory for matches
$innerIterator = new GlobFilterIterator(
$glob,
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(
$basePath,
RecursiveDirectoryIterator::CURRENT_AS_PATHNAME,
RecursiveDirectoryIterator::SKIP_DOTS
),
RecursiveIteratorIterator::SELF_FIRST,
RecursiveIteratorIterator::CATCH_GET_CHILD
),
GlobFilterIterator::FILTER_VALUE,
$flags
);
}
} else {
// If the glob's base directory does not exist, return nothing
$innerIterator = new EmptyIterator();
}
parent::__construct($innerIterator);
}
}

View File

@ -3,6 +3,7 @@
namespace LanguageServer\FqnUtilities;
use phpDocumentor\Reflection\{Type, Types};
use Microsoft\PhpParser;
/**
* Returns all possible FQNs in a type
@ -28,91 +29,3 @@ function getFqnsFromType($type): array
}
return $fqns;
}
/**
* Returns parent of an FQN.
*
* getFqnParent('') === ''
* getFqnParent('\\') === ''
* getFqnParent('\A') === ''
* getFqnParent('A') === ''
* getFqnParent('\A\') === '\A' // Empty trailing name is considered a name.
*
* @return string
*/
function nameGetParent(string $name): string
{
if ($name === '') { // Special-case handling for the root namespace.
return '';
}
$parts = explode('\\', $name);
array_pop($parts);
return implode('\\', $parts);
}
/**
* Concatenates two names.
*
* nameConcat('\Foo\Bar', 'Baz') === '\Foo\Bar\Baz'
* nameConcat('\Foo\Bar\\', '\Baz') === '\Foo\Bar\Baz'
* nameConcat('\\', 'Baz') === '\Baz'
* nameConcat('', 'Baz') === 'Baz'
*
* @return string
*/
function nameConcat(string $a, string $b): string
{
if ($a === '') {
return $b;
}
$a = rtrim($a, '\\');
$b = ltrim($b, '\\');
return "$a\\$b";
}
/**
* Returns the first component of $name.
*
* nameGetFirstPart('Foo\Bar') === 'Foo'
* nameGetFirstPart('\Foo\Bar') === 'Foo'
* nameGetFirstPart('') === ''
* nameGetFirstPart('\') === ''
*/
function nameGetFirstPart(string $name): string
{
$parts = explode('\\', $name, 3);
if ($parts[0] === '' && count($parts) > 1) {
return $parts[1];
} else {
return $parts[0];
}
}
/**
* Removes the first component of $name.
*
* nameWithoutFirstPart('Foo\Bar') === 'Bar'
* nameWithoutFirstPart('\Foo\Bar') === 'Bar'
* nameWithoutFirstPart('') === ''
* nameWithoutFirstPart('\') === ''
*/
function nameWithoutFirstPart(string $name): string
{
$parts = explode('\\', $name, 3);
if ($parts[0] === '') {
array_shift($parts);
}
array_shift($parts);
return implode('\\', $parts);
}
/**
* @param string $name Name to match against
* @param string $prefix Prefix $name has to starts with
* @return bool
*/
function nameStartsWith(string $name, string $prefix): bool
{
return strlen($name) >= strlen($prefix)
&& strncmp($name, $prefix, strlen($prefix)) === 0;
}

View File

@ -99,29 +99,20 @@ abstract class AbstractAggregateIndex implements ReadableIndex
}
/**
* Returns a Generator providing an associative array [string => Definition]
* that maps fully qualified symbol names to Definitions (global or not)
* Returns an associative array [string => Definition] that maps fully qualified symbol names
* to Definitions
*
* @return \Generator yields Definition
* @return Definition[]
*/
public function getDefinitions(): \Generator
public function getDefinitions(): array
{
$defs = [];
foreach ($this->getIndexes() as $index) {
yield from $index->getDefinitions();
foreach ($index->getDefinitions() as $fqn => $def) {
$defs[$fqn] = $def;
}
}
/**
* Returns a Generator that yields all the direct child Definitions of a given FQN
*
* @param string $fqn
* @return \Generator yields Definition
*/
public function getChildDefinitionsForFqn(string $fqn): \Generator
{
foreach ($this->getIndexes() as $index) {
yield from $index->getChildDefinitionsForFqn($fqn);
}
return $defs;
}
/**
@ -141,15 +132,19 @@ abstract class AbstractAggregateIndex implements ReadableIndex
}
/**
* Returns a Generator providing all URIs in this index that reference a symbol
* Returns all URIs in this index that reference a symbol
*
* @param string $fqn The fully qualified name of the symbol
* @return \Generator yields string
* @return string[]
*/
public function getReferenceUris(string $fqn): \Generator
public function getReferenceUris(string $fqn): array
{
$refs = [];
foreach ($this->getIndexes() as $index) {
yield from $index->getReferenceUris($fqn);
foreach ($index->getReferenceUris($fqn) as $ref) {
$refs[] = $ref;
}
}
return $refs;
}
}

View File

@ -15,26 +15,14 @@ class Index implements ReadableIndex, \Serializable
use EmitterTrait;
/**
* An associative array that maps splitted fully qualified symbol names
* to definitions, eg :
* [
* 'Psr' => [
* '\Log' => [
* '\LoggerInterface' => [
* '' => $def1, // definition for 'Psr\Log\LoggerInterface' which is non-member
* '->log()' => $def2, // definition for 'Psr\Log\LoggerInterface->log()' which is a member
* ],
* ],
* ],
* ]
* An associative array that maps fully qualified symbol names to Definitions
*
* @var array
* @var Definition[]
*/
private $definitions = [];
/**
* An associative array that maps fully qualified symbol names
* to arrays of document URIs that reference the symbol
* An associative array that maps fully qualified symbol names to arrays of document URIs that reference the symbol
*
* @var string[][]
*/
@ -96,46 +84,14 @@ class Index implements ReadableIndex, \Serializable
}
/**
* Returns a Generator providing an associative array [string => Definition]
* that maps fully qualified symbol names to Definitions (global or not)
* Returns an associative array [string => Definition] that maps fully qualified symbol names
* to Definitions
*
* @return \Generator yields Definition
* @return Definition[]
*/
public function getDefinitions(): \Generator
public function getDefinitions(): array
{
yield from $this->yieldDefinitionsRecursively($this->definitions);
}
/**
* Returns a Generator that yields all the direct child Definitions of a given FQN
*
* @param string $fqn
* @return \Generator yields Definition
*/
public function getChildDefinitionsForFqn(string $fqn): \Generator
{
$parts = $this->splitFqn($fqn);
if ('' === end($parts)) {
// we want to return all the definitions in the given FQN, not only
// the one (non member) matching exactly the FQN.
array_pop($parts);
}
$result = $this->getIndexValue($parts, $this->definitions);
if (!$result) {
return;
}
foreach ($result as $name => $item) {
// Don't yield the parent
if ($name === '') {
continue;
}
if ($item instanceof Definition) {
yield $fqn.$name => $item;
} elseif (is_array($item) && isset($item[''])) {
yield $fqn.$name => $item[''];
}
}
return $this->definitions;
}
/**
@ -147,17 +103,12 @@ class Index implements ReadableIndex, \Serializable
*/
public function getDefinition(string $fqn, bool $globalFallback = false)
{
$parts = $this->splitFqn($fqn);
$result = $this->getIndexValue($parts, $this->definitions);
if ($result instanceof Definition) {
return $result;
if (isset($this->definitions[$fqn])) {
return $this->definitions[$fqn];
}
if ($globalFallback) {
$parts = explode('\\', $fqn);
$fqn = end($parts);
return $this->getDefinition($fqn);
}
}
@ -171,9 +122,7 @@ class Index implements ReadableIndex, \Serializable
*/
public function setDefinition(string $fqn, Definition $definition)
{
$parts = $this->splitFqn($fqn);
$this->indexDefinition(0, $parts, $this->definitions, $definition);
$this->definitions[$fqn] = $definition;
$this->emit('definition-added');
}
@ -186,23 +135,19 @@ class Index implements ReadableIndex, \Serializable
*/
public function removeDefinition(string $fqn)
{
$parts = $this->splitFqn($fqn);
$this->removeIndexedDefinition(0, $parts, $this->definitions, $this->definitions);
unset($this->definitions[$fqn]);
unset($this->references[$fqn]);
}
/**
* Returns a Generator providing all URIs in this index that reference a symbol
* Returns all URIs in this index that reference a symbol
*
* @param string $fqn The fully qualified name of the symbol
* @return \Generator yields string
* @return string[]
*/
public function getReferenceUris(string $fqn): \Generator
public function getReferenceUris(string $fqn): array
{
foreach ($this->references[$fqn] ?? [] as $uri) {
yield $uri;
}
return $this->references[$fqn] ?? [];
}
/**
@ -259,184 +204,22 @@ class Index implements ReadableIndex, \Serializable
public function unserialize($serialized)
{
$data = unserialize($serialized);
if (isset($data['definitions'])) {
foreach ($data['definitions'] as $fqn => $definition) {
$this->setDefinition($fqn, $definition);
}
unset($data['definitions']);
}
foreach ($data as $prop => $val) {
$this->$prop = $val;
}
}
/**
* @param string $serialized
* @return string
*/
public function serialize()
{
return serialize([
'definitions' => iterator_to_array($this->getDefinitions()),
'definitions' => $this->definitions,
'references' => $this->references,
'complete' => $this->complete,
'staticComplete' => $this->staticComplete
]);
}
/**
* Returns a Generator that yields all the Definitions in the given $storage recursively.
* The generator yields key => value pairs, e.g.
* `'Psr\Log\LoggerInterface->log()' => $definition`
*
* @param array &$storage
* @param string $prefix (optional)
* @return \Generator
*/
private function yieldDefinitionsRecursively(array &$storage, string $prefix = ''): \Generator
{
foreach ($storage as $key => $value) {
if (!is_array($value)) {
yield $prefix.$key => $value;
} else {
yield from $this->yieldDefinitionsRecursively($value, $prefix.$key);
}
}
}
/**
* Splits the given FQN into an array, eg :
* - `'Psr\Log\LoggerInterface->log'` will be `['Psr', '\Log', '\LoggerInterface', '->log()']`
* - `'\Exception->getMessage()'` will be `['\Exception', '->getMessage()']`
* - `'PHP_VERSION'` will be `['PHP_VERSION']`
*
* @param string $fqn
* @return string[]
*/
private function splitFqn(string $fqn): array
{
// split fqn at backslashes
$parts = explode('\\', $fqn);
// write back the backslash prefix to the first part if it was present
if ('' === $parts[0] && count($parts) > 1) {
$parts = array_slice($parts, 1);
$parts[0] = '\\' . $parts[0];
}
// write back the backslashes prefixes for the other parts
for ($i = 1; $i < count($parts); $i++) {
$parts[$i] = '\\' . $parts[$i];
}
// split the last part in 2 parts at the operator
$hasOperator = false;
$lastPart = end($parts);
foreach (['::', '->'] as $operator) {
$endParts = explode($operator, $lastPart);
if (count($endParts) > 1) {
$hasOperator = true;
// replace the last part by its pieces
array_pop($parts);
$parts[] = $endParts[0];
$parts[] = $operator . $endParts[1];
break;
}
}
// The end($parts) === '' holds for the root namespace.
if (!$hasOperator && end($parts) !== '') {
// add an empty part to store the non-member definition to avoid
// definition collisions in the index array, eg
// 'Psr\Log\LoggerInterface' will be stored at
// ['Psr']['\Log']['\LoggerInterface'][''] to be able to also store
// member definitions, ie 'Psr\Log\LoggerInterface->log()' will be
// stored at ['Psr']['\Log']['\LoggerInterface']['->log()']
$parts[] = '';
}
return $parts;
}
/**
* Return the values stored in this index under the given $parts array.
* It can be an index node or a Definition if the $parts are precise
* enough. Returns null when nothing is found.
*
* @param string[] $path The splitted FQN
* @param array|Definition &$storage The current level to look for $path.
* @return array|Definition|null
*/
private function getIndexValue(array $path, &$storage)
{
// Empty path returns the object itself.
if (empty($path)) {
return $storage;
}
$part = array_shift($path);
if (!isset($storage[$part])) {
return null;
}
return $this->getIndexValue($path, $storage[$part]);
}
/**
* Recursive function that stores the given Definition in the given $storage array represented
* as a tree matching the given $parts.
*
* @param int $level The current level of FQN part
* @param string[] $parts The splitted FQN
* @param array &$storage The array in which to store the $definition
* @param Definition $definition The Definition to store
*/
private function indexDefinition(int $level, array $parts, array &$storage, Definition $definition)
{
$part = $parts[$level];
if ($level + 1 === count($parts)) {
$storage[$part] = $definition;
return;
}
if (!isset($storage[$part])) {
$storage[$part] = [];
}
$this->indexDefinition($level + 1, $parts, $storage[$part], $definition);
}
/**
* Recursive function that removes the definition matching the given $parts from the given
* $storage array. The function also looks up recursively to remove the parents of the
* definition which no longer has children to avoid to let empty arrays in the index.
*
* @param int $level The current level of FQN part
* @param string[] $parts The splitted FQN
* @param array &$storage The current array in which to remove data
* @param array &$rootStorage The root storage array
*/
private function removeIndexedDefinition(int $level, array $parts, array &$storage, array &$rootStorage)
{
$part = $parts[$level];
if ($level + 1 === count($parts)) {
if (isset($storage[$part])) {
unset($storage[$part]);
if (0 === count($storage)) {
// parse again the definition tree to remove the parent
// when it has no more children
$this->removeIndexedDefinition(0, array_slice($parts, 0, $level), $rootStorage, $rootStorage);
}
}
} else {
$this->removeIndexedDefinition($level + 1, $parts, $storage[$part], $rootStorage);
}
}
}

View File

@ -30,20 +30,12 @@ interface ReadableIndex extends EmitterInterface
public function isStaticComplete(): bool;
/**
* Returns a Generator providing an associative array [string => Definition]
* that maps fully qualified symbol names to Definitions (global or not)
* Returns an associative array [string => Definition] that maps fully qualified symbol names
* to Definitions
*
* @return \Generator yields Definition
* @return Definitions[]
*/
public function getDefinitions(): \Generator;
/**
* Returns a Generator that yields all the direct child Definitions of a given FQN
*
* @param string $fqn
* @return \Generator yields Definition
*/
public function getChildDefinitionsForFqn(string $fqn): \Generator;
public function getDefinitions(): array;
/**
* Returns the Definition object by a specific FQN
@ -55,10 +47,10 @@ interface ReadableIndex extends EmitterInterface
public function getDefinition(string $fqn, bool $globalFallback = false);
/**
* Returns a Generator that yields all URIs in this index that reference a symbol
* Returns all URIs in this index that reference a symbol
*
* @param string $fqn The fully qualified name of the symbol
* @return \Generator yields string
* @return string[]
*/
public function getReferenceUris(string $fqn): \Generator;
public function getReferenceUris(string $fqn): array;
}

View File

@ -6,8 +6,10 @@ namespace LanguageServer;
use LanguageServer\Cache\Cache;
use LanguageServer\FilesFinder\FilesFinder;
use LanguageServer\Index\{DependenciesIndex, Index};
use LanguageServerProtocol\MessageType;
use LanguageServer\Protocol\Message;
use LanguageServer\Protocol\MessageType;
use Webmozart\PathUtil\Path;
use Composer\Semver\VersionParser;
use Sabre\Event\Promise;
use function Sabre\Event\coroutine;
@ -16,7 +18,7 @@ class Indexer
/**
* @var int The prefix for every cache item
*/
const CACHE_VERSION = 3;
const CACHE_VERSION = 2;
/**
* @var FilesFinder
@ -147,7 +149,7 @@ class Indexer
$packageKey = null;
$cacheKey = null;
$index = null;
foreach (array_merge($this->composerLock->packages, (array)$this->composerLock->{'packages-dev'}) as $package) {
foreach (array_merge($this->composerLock->packages, $this->composerLock->{'packages-dev'}) as $package) {
// Check if package name matches and version is absolute
// Dynamic constraints are not cached, because they can change every time
$packageVersion = ltrim($package->version, 'v');

View File

@ -3,15 +3,15 @@ declare(strict_types = 1);
namespace LanguageServer;
use LanguageServerProtocol\{
use LanguageServer\Protocol\{
ServerCapabilities,
ClientCapabilities,
TextDocumentSyncKind,
Message,
InitializeResult,
CompletionOptions,
SignatureHelpOptions
};
use LanguageServer\Message;
use LanguageServer\FilesFinder\{FilesFinder, ClientFilesFinder, FileSystemFilesFinder};
use LanguageServer\ContentRetriever\{ContentRetriever, ClientContentRetriever, FileSystemContentRetriever};
use LanguageServer\Index\{DependenciesIndex, GlobalIndex, Index, ProjectIndex, StubsIndex};
@ -165,11 +165,8 @@ class LanguageServer extends AdvancedJsonRpc\Dispatcher
* @param int|null $processId The process Id of the parent process that started the server. Is null if the process has not been started by another process. If the parent process is not alive then the server should exit (see exit notification) its process.
* @return Promise <InitializeResult>
*/
public function initialize(ClientCapabilities $capabilities, string $rootPath = null, int $processId = null, string $rootUri = null): Promise
public function initialize(ClientCapabilities $capabilities, string $rootPath = null, int $processId = null): Promise
{
if ($rootPath === null && $rootUri !== null) {
$rootPath = uriToPath($rootUri);
}
return coroutine(function () use ($capabilities, $rootPath, $processId) {
if ($capabilities->xfilesProvider) {

View File

@ -4,7 +4,7 @@ declare(strict_types = 1);
namespace LanguageServer;
use LanguageServer\Index\Index;
use LanguageServerProtocol\{
use LanguageServer\Protocol\{
Diagnostic, Position, Range
};
use Microsoft\PhpParser;
@ -63,7 +63,7 @@ class PhpDocument
/**
* Map from fully qualified name (FQN) to Node
*
* @var Node[]
* @var Node
*/
private $definitionNodes;
@ -160,9 +160,7 @@ class PhpDocument
// Register this document on the project for references
foreach ($this->referenceNodes as $fqn => $nodes) {
// Cast the key to string. If (string)'2' is set as an array index, it will read out as (int)2. We must
// deal with incorrect code, so this is a valid scenario.
$this->index->addReferenceUri((string)$fqn, $this->uri);
$this->index->addReferenceUri($fqn, $this->uri);
}
$this->sourceFileNode = $treeAnalyzer->getSourceFileNode();

View File

@ -0,0 +1,27 @@
<?php
namespace LanguageServer\Protocol;
class ClientCapabilities
{
/**
* The client supports workspace/xfiles requests
*
* @var bool|null
*/
public $xfilesProvider;
/**
* The client supports textDocument/xcontent requests
*
* @var bool|null
*/
public $xcontentProvider;
/**
* The client supports xcache/* requests
*
* @var bool|null
*/
public $xcacheProvider;
}

View File

@ -0,0 +1,17 @@
<?php
namespace LanguageServer\Protocol;
/**
* Contains additional diagnostic information about the context in which
* a code action is run.
*/
class CodeActionContext
{
/**
* An array of diagnostics.
*
* @var Diagnostic[]
*/
public $diagnostics;
}

35
src/Protocol/CodeLens.php Normal file
View File

@ -0,0 +1,35 @@
<?php
namespace LanguageServer\Protocol;
/**
* A code lens represents a command that should be shown along with
* source text, like the number of references, a way to run tests, etc.
*
* A code lens is _unresolved_ when no command is associated to it. For performance
* reasons the creation of a code lens and resolving should be done in two stages.
*/
class CodeLens
{
/**
* The range in which this code lens is valid. Should only span a single line.
*
* @var Range
*/
public $range;
/**
* The command this code lens represents.
*
* @var Command|null
*/
public $command;
/**
* A data entry field that is preserved on a code lens item between
* a code lens and a code lens resolve request.
*
* @var mixed|null
*/
public $data;
}

View File

@ -0,0 +1,16 @@
<?php
namespace LanguageServer\Protocol;
/**
* Code Lens options.
*/
class CodeLensOptions
{
/**
* Code lens has a resolve provider as well.
*
* @var bool|null
*/
public $resolveProvider;
}

32
src/Protocol/Command.php Normal file
View File

@ -0,0 +1,32 @@
<?php
namespace LanguageServer\Protocol;
/**
* Represents a reference to a command. Provides a title which will be used to represent a command in the UI and,
* optionally, an array of arguments which will be passed to the command handler function when invoked.
*/
class Command
{
/**
* Title of the command, like `save`.
*
* @var string
*/
public $title;
/**
* The identifier of the actual command handler.
*
* @var string
*/
public $command;
/**
* Arguments that the command handler should be
* invoked with.
*
* @var mixed[]|null
*/
public $arguments;
}

View File

@ -0,0 +1,30 @@
<?php
namespace LanguageServer\Protocol;
/**
* Contains additional information about the context in which a completion request is triggered.
*/
class CompletionContext
{
/**
* How the completion was triggered.
*
* @var int
*/
public $triggerKind;
/**
* The trigger character (a single character) that has trigger code complete.
* Is null if `triggerKind !== CompletionTriggerKind::TRIGGER_CHARACTER`
*
* @var string|null
*/
public $triggerCharacter;
public function __construct(int $triggerKind = null, string $triggerCharacter = null)
{
$this->triggerKind = $triggerKind;
$this->triggerCharacter = $triggerCharacter;
}
}

View File

@ -0,0 +1,164 @@
<?php
declare(strict_types = 1);
namespace LanguageServer\Protocol;
use LanguageServer\Definition;
class CompletionItem
{
/**
* The label of this completion item. By default
* also the text that is inserted when selecting
* this completion.
*
* @var string
*/
public $label;
/**
* The kind of this completion item. Based of the kind
* an icon is chosen by the editor.
*
* @var int|null
*/
public $kind;
/**
* A human-readable string with additional information
* about this item, like type or symbol information.
*
* @var string|null
*/
public $detail;
/**
* A human-readable string that represents a doc-comment.
*
* @var string|null
*/
public $documentation;
/**
* A string that shoud be used when comparing this item
* with other items. When `falsy` the label is used.
*
* @var string|null
*/
public $sortText;
/**
* A string that should be used when filtering a set of
* completion items. When `falsy` the label is used.
*
* @var string|null
*/
public $filterText;
/**
* A string that should be inserted a document when selecting
* this completion. When `falsy` the label is used.
*
* @var string|null
*/
public $insertText;
/**
* An edit which is applied to a document when selecting
* this completion. When an edit is provided the value of
* insertText is ignored.
*
* @var TextEdit|null
*/
public $textEdit;
/**
* An optional array of additional text edits that are applied when
* selecting this completion. Edits must not overlap with the main edit
* nor with themselves.
*
* @var TextEdit[]|null
*/
public $additionalTextEdits;
/**
* An optional command that is executed *after* inserting this completion. *Note* that
* additional modifications to the current document should be described with the
* additionalTextEdits-property.
*
* @var Command|null
*/
public $command;
/**
* An data entry field that is preserved on a completion item between
* a completion and a completion resolve request.
*
* @var mixed
*/
public $data;
/**
* @param string $label
* @param int|null $kind
* @param string|null $detail
* @param string|null $documentation
* @param string|null $sortText
* @param string|null $filterText
* @param string|null $insertText
* @param TextEdit|null $textEdit
* @param TextEdit[]|null $additionalTextEdits
* @param Command|null $command
* @param mixed|null $data
*/
public function __construct(
string $label = null,
int $kind = null,
string $detail = null,
string $documentation = null,
string $sortText = null,
string $filterText = null,
string $insertText = null,
TextEdit $textEdit = null,
array $additionalTextEdits = null,
Command $command = null,
$data = null
) {
$this->label = $label;
$this->kind = $kind;
$this->detail = $detail;
$this->documentation = $documentation;
$this->sortText = $sortText;
$this->filterText = $filterText;
$this->insertText = $insertText;
$this->textEdit = $textEdit;
$this->additionalTextEdits = $additionalTextEdits;
$this->command = $command;
$this->data = $data;
}
/**
* Creates a CompletionItem for a Definition
*
* @param Definition $def
* @return self
*/
public static function fromDefinition(Definition $def): self
{
$item = new CompletionItem;
$item->label = $def->symbolInformation->name;
$item->kind = CompletionItemKind::fromSymbolKind($def->symbolInformation->kind);
if ($def->type) {
$item->detail = (string)$def->type;
} else if ($def->symbolInformation->containerName) {
$item->detail = $def->symbolInformation->containerName;
}
if ($def->documentation) {
$item->documentation = $def->documentation;
}
if ($def->isStatic && $def->symbolInformation->kind === SymbolKind::PROPERTY) {
$item->insertText = '$' . $def->symbolInformation->name;
}
return $item;
}
}

View File

@ -0,0 +1,70 @@
<?php
namespace LanguageServer\Protocol;
/**
* The kind of a completion entry.
*/
abstract class CompletionItemKind
{
const TEXT = 1;
const METHOD = 2;
const FUNCTION = 3;
const CONSTRUCTOR = 4;
const FIELD = 5;
const VARIABLE = 6;
const CLASS_ = 7;
const INTERFACE = 8;
const MODULE = 9;
const PROPERTY = 10;
const UNIT = 11;
const VALUE = 12;
const ENUM = 13;
const KEYWORD = 14;
const SNIPPET = 15;
const COLOR = 16;
const FILE = 17;
const REFERENCE = 18;
/**
* Returns the CompletionItemKind for a SymbolKind
*
* @param int $kind A SymbolKind
* @return int The CompletionItemKind
*/
public static function fromSymbolKind(int $kind): int
{
switch ($kind) {
case SymbolKind::PROPERTY:
case SymbolKind::FIELD:
return self::PROPERTY;
case SymbolKind::METHOD:
return self::METHOD;
case SymbolKind::CLASS_:
return self::CLASS_;
case SymbolKind::INTERFACE:
return self::INTERFACE;
case SymbolKind::FUNCTION:
return self::FUNCTION;
case SymbolKind::NAMESPACE:
case SymbolKind::MODULE:
case SymbolKind::PACKAGE:
return self::MODULE;
case SymbolKind::FILE:
return self::FILE;
case SymbolKind::STRING:
return self::TEXT;
case SymbolKind::NUMBER:
case SymbolKind::BOOLEAN:
case SymbolKind::ARRAY:
return self::VALUE;
case SymbolKind::ENUM:
return self::ENUM;
case SymbolKind::CONSTRUCTOR:
return self::CONSTRUCTOR;
case SymbolKind::VARIABLE:
case SymbolKind::CONSTANT:
return self::VARIABLE;
}
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace LanguageServer\Protocol;
/**
* Represents a collection of completion items to be presented in
* the editor.
*/
class CompletionList
{
/**
* This list it not complete. Further typing should result in recomputing this
* list.
*
* @var bool
*/
public $isIncomplete;
/**
* The completion items.
*
* @var CompletionItem[]
*/
public $items;
/**
* @param CompletionItem[] $items The completion items.
* @param bool $isIncomplete This list it not complete. Further typing should result in recomputing this list.
*/
public function __construct(array $items = [], bool $isIncomplete = false)
{
$this->items = $items;
$this->isIncomplete = $isIncomplete;
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace LanguageServer\Protocol;
/**
* Completion options.
*/
class CompletionOptions
{
/*
* The server provides support to resolve additional information for a completion
* item.
*
* @var bool|null
*/
public $resolveProvider;
/**
* The characters that trigger completion automatically.
*
* @var string[]|null
*/
public $triggerCharacters;
}

View File

@ -0,0 +1,16 @@
<?php
namespace LanguageServer\Protocol;
class CompletionTriggerKind
{
/**
* Completion was triggered by invoking it manuall or using API.
*/
const INVOKED = 1;
/**
* Completion was triggered by a trigger character.
*/
const TRIGGER_CHARACTER = 2;
}

View File

@ -0,0 +1,31 @@
<?php
namespace LanguageServer\Protocol;
/**
* An event describing a change to a text document. If range and rangeLength are
* omitted the new text is considered to be the full content of the document.
*/
class ContentChangeEvent
{
/**
* The range of the document that changed.
*
* @var Range|null
*/
public $range;
/**
* The length of the range that got replaced.
*
* @var int|null
*/
public $rangeLength;
/**
* The new text of the document.
*
* @var string
*/
public $text;
}

View File

@ -0,0 +1,27 @@
<?php
declare(strict_types = 1);
namespace LanguageServer\Protocol;
class DependencyReference
{
/**
* @var mixed
*/
public $hints;
/**
* @var object
*/
public $attributes;
/**
* @param object $attributes
* @param mixed $hints
*/
public function __construct($attributes = null, $hints = null)
{
$this->attributes = $attributes ?? new \stdClass;
$this->hints = $hints;
}
}

View File

@ -0,0 +1,63 @@
<?php
namespace LanguageServer\Protocol;
/**
* Represents a diagnostic, such as a compiler error or warning. Diagnostic objects are only valid in the scope of a
* resource.
*/
class Diagnostic
{
/**
* The range at which the message applies.
*
* @var Range
*/
public $range;
/**
* The diagnostic's severity. Can be omitted. If omitted it is up to the
* client to interpret diagnostics as error, warning, info or hint.
*
* @var int|null
*/
public $severity;
/**
* The diagnostic's code. Can be omitted.
*
* @var int|string|null
*/
public $code;
/**
* A human-readable string describing the source of this
* diagnostic, e.g. 'typescript' or 'super lint'.
*
* @var string|null
*/
public $source;
/**
* The diagnostic's message.
*
* @var string
*/
public $message;
/**
* @param string $message The diagnostic's message
* @param Range $range The range at which the message applies
* @param int $code The diagnostic's code
* @param int $severity DiagnosticSeverity
* @param string $source A human-readable string describing the source of this diagnostic
*/
public function __construct(string $message = null, Range $range = null, int $code = null, int $severity = null, string $source = null)
{
$this->message = $message;
$this->range = $range;
$this->code = $code;
$this->severity = $severity;
$this->source = $source;
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace LanguageServer\Protocol;
abstract class DiagnosticSeverity
{
/**
* Reports an error.
*/
const ERROR = 1;
/**
* Reports a warning.
*/
const WARNING = 2;
/**
* Reports an information.
*/
const INFORMATION = 3;
/**
* Reports a hint.
*/
const HINT = 4;
}

View File

@ -0,0 +1,25 @@
<?php
namespace LanguageServer\Protocol;
/**
* A document highlight is a range inside a text document which deserves
* special attention. Usually a document highlight is visualized by changing
* the background color of its range.
*/
class DocumentHighlight
{
/**
* The range this highlight applies to.
*
* @var Range
*/
public $range;
/**
* The highlight kind, default is DocumentHighlightKind::TEXT.
*
* @var int|null
*/
public $kind;
}

View File

@ -0,0 +1,24 @@
<?php
namespace LanguageServer\Protocol;
/**
* A document highlight kind.
*/
abstract class DocumentHighlightKind
{
/**
* A textual occurrance.
*/
const TEXT = 1;
/**
* Read-access of a symbol, like reading a variable.
*/
const READ = 2;
/**
* Write-access of a symbol, like writing to a variable.
*/
const WRITE = 3;
}

View File

@ -0,0 +1,23 @@
<?php
namespace LanguageServer\Protocol;
/**
* Format document on type options
*/
class DocumentOnTypeFormattingOptions
{
/**
* A character on which formatting should be triggered, like `}`.
*
* @var string
*/
public $firstTriggerCharacter;
/**
* More trigger characters.
*
* @var string[]|null
*/
public $moreTriggerCharacter;
}

View File

@ -0,0 +1,17 @@
<?php
namespace LanguageServer\Protocol;
/**
* Enum
*/
abstract class ErrorCode
{
const PARSE_ERROR = -32700;
const INVALID_REQUEST = -32600;
const METHOD_NOT_FOUND = -32601;
const INVALID_PARAMS = -32602;
const INTERNAL_ERROR = -32603;
const SERVER_ERROR_START = -32099;
const SERVER_ERROR_END = -32000;
}

View File

@ -0,0 +1,24 @@
<?php
namespace LanguageServer\Protocol;
/**
* The file event type. Enum
*/
abstract class FileChangeType
{
/**
* The file got created.
*/
const CREATED = 1;
/**
* The file got changed.
*/
const CHANGED = 2;
/**
* The file got deleted.
*/
const DELETED = 3;
}

View File

@ -0,0 +1,33 @@
<?php
namespace LanguageServer\Protocol;
/**
* An event describing a file change.
*/
class FileEvent
{
/**
* The file's URI.
*
* @var string
*/
public $uri;
/**
* The change type.
*
* @var int
*/
public $type;
/**
* @param string $uri
* @param int $type
*/
public function __construct(string $uri, int $type)
{
$this->uri = $uri;
$this->type = $type;
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace LanguageServer\Protocol;
/**
* Value-object describing what options formatting should use.
*/
class FormattingOptions
{
/**
* Size of a tab in spaces.
*
* @var int
*/
public $tabSize;
/**
* Prefer spaces over tabs.
*
* @var bool
*/
public $insertSpaces;
// Can be extended with further properties.
}

33
src/Protocol/Hover.php Normal file
View File

@ -0,0 +1,33 @@
<?php
namespace LanguageServer\Protocol;
/**
* The result of a hover request.
*/
class Hover
{
/**
* The hover's content
*
* @var string|MarkedString|string[]|MarkedString[]
*/
public $contents;
/**
* An optional range
*
* @var Range|null
*/
public $range;
/**
* @param string|MarkedString|string[]|MarkedString[] $contents The hover's content
* @param Range $range An optional range
*/
public function __construct($contents = null, $range = null)
{
$this->contents = $contents;
$this->range = $range;
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace LanguageServer\Protocol;
class InitializeResult
{
/**
* The capabilities the language server provides.
*
* @var LanguageServer\Protocol\ServerCapabilities
*/
public $capabilities;
/**
* @param LanguageServer\Protocol\ServerCapabilities $capabilities
*/
public function __construct(ServerCapabilities $capabilities = null)
{
$this->capabilities = $capabilities ?? new ServerCapabilities();
}
}

43
src/Protocol/Location.php Normal file
View File

@ -0,0 +1,43 @@
<?php
namespace LanguageServer\Protocol;
use Microsoft\PhpParser;
use Microsoft\PhpParser\Node;
/**
* Represents a location inside a resource, such as a line inside a text file.
*/
class Location
{
/**
* @var string
*/
public $uri;
/**
* @var Range
*/
public $range;
/**
* Returns the location of the node
*
* @param Node $node
* @return self
*/
public static function fromNode($node)
{
$range = PhpParser\PositionUtilities::getRangeFromPosition($node->getStart(), $node->getWidth(), $node->getFileContents());
return new self($node->getUri(), new Range(
new Position($range->start->line, $range->start->character),
new Position($range->end->line, $range->end->character)
));
}
public function __construct(string $uri = null, Range $range = null)
{
$this->uri = $uri;
$this->range = $range;
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace LanguageServer\Protocol;
class MarkedString
{
/**
* @var string
*/
public $language;
/**
* @var string
*/
public $value;
public function __construct(string $language = null, string $value = null)
{
$this->language = $language;
$this->value = $value;
}
}

View File

@ -1,10 +1,9 @@
<?php
declare(strict_types = 1);
namespace LanguageServer;
namespace LanguageServer\Protocol;
use AdvancedJsonRpc\Message as MessageBody;
use LanguageServer\Message;
class Message
{

View File

@ -0,0 +1,13 @@
<?php
namespace LanguageServer\Protocol;
class MessageActionItem
{
/**
* A short title like 'Retry', 'Open Log' etc.
*
* @var string
*/
public $title;
}

View File

@ -0,0 +1,29 @@
<?php
namespace LanguageServer\Protocol;
/**
* Enum
*/
abstract class MessageType
{
/**
* An error message.
*/
const ERROR = 1;
/**
* A warning message.
*/
const WARNING = 2;
/**
* An information message.
*/
const INFO = 3;
/**
* A log message.
*/
const LOG = 4;
}

View File

@ -0,0 +1,25 @@
<?php
declare(strict_types = 1);
namespace LanguageServer\Protocol;
/**
* Uniquely identifies a Composer package
*/
class PackageDescriptor
{
/**
* The package name
*
* @var string
*/
public $name;
/**
* @param string $name The package name
*/
public function __construct(string $name = null)
{
$this->name = $name;
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace LanguageServer\Protocol;
/**
* Represents a parameter of a callable-signature. A parameter can
* have a label and a doc-comment.
*/
class ParameterInformation
{
/**
* The label of this signature. Will be shown in
* the UI.
*
* @var string
*/
public $label;
/**
* The human-readable doc-comment of this signature. Will be shown
* in the UI but can be omitted.
*
* @var string|null
*/
public $documentation;
/**
* Create ParameterInformation
*
* @param string $label The label of this signature. Will be shown in the UI.
* @param string $documentation The human-readable doc-comment of this signature. Will be shown in the UI but can
* be omitted.
*/
public function __construct(string $label, string $documentation = null)
{
$this->label = $label;
$this->documentation = $documentation;
}
}

65
src/Protocol/Position.php Normal file
View File

@ -0,0 +1,65 @@
<?php
namespace LanguageServer\Protocol;
/**
* Position in a text document expressed as zero-based line and character offset.
*/
class Position
{
/**
* Line position in a document (zero-based).
*
* @var int
*/
public $line;
/**
* Character offset on a line in a document (zero-based).
*
* @var int
*/
public $character;
public function __construct(int $line = null, int $character = null)
{
$this->line = $line;
$this->character = $character;
}
/**
* Compares this position to another position
* Returns
* - 0 if the positions match
* - a negative number if $this is before $position
* - a positive number otherwise
*
* @param Position $position
* @return int
*/
public function compare(Position $position): int
{
if ($this->line === $position->line && $this->character === $position->character) {
return 0;
}
if ($this->line !== $position->line) {
return $this->line - $position->line;
}
return $this->character - $position->character;
}
/**
* Returns the offset of the position in a string
*
* @param string $content
* @return int
*/
public function toOffset(string $content): int
{
$lines = explode("\n", $content);
$slice = array_slice($lines, 0, $this->line);
return array_sum(array_map('strlen', $slice)) + count($slice) + $this->character;
}
}

59
src/Protocol/Range.php Normal file
View File

@ -0,0 +1,59 @@
<?php
namespace LanguageServer\Protocol;
use Microsoft\PhpParser;
use Microsoft\PhpParser\Node;
/**
* A range in a text document expressed as (zero-based) start and end positions.
*/
class Range
{
/**
* The range's start position.
*
* @var Position
*/
public $start;
/**
* The range's end position.
*
* @var Position
*/
public $end;
/**
* Returns the range the node spans
*
* @param Node $node
* @return self
*/
public static function fromNode(Node $node)
{
$range = PhpParser\PositionUtilities::getRangeFromPosition($node->getStart(), $node->getWidth(), $node->getFileContents());
return new self(
new Position($range->start->line, $range->start->character),
new Position($range->end->line, $range->end->character)
);
}
public function __construct(Position $start = null, Position $end = null)
{
$this->start = $start;
$this->end = $end;
}
/**
* Checks if a position is within the range
*
* @param Position $position
* @return bool
*/
public function includes(Position $position): bool
{
return $this->start->compare($position) <= 0 && $this->end->compare($position) >= 0;
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace LanguageServer\Protocol;
class ReferenceContext
{
/**
* Include the declaration of the current symbol.
*
* @var bool
*/
public $includeDeclaration;
}

View File

@ -0,0 +1,36 @@
<?php
declare(strict_types = 1);
namespace LanguageServer\Protocol;
/**
* Metadata about the symbol that can be used to identify or locate its
* definition.
*/
class ReferenceInformation
{
/**
* The location in the workspace where the `symbol` is referenced.
*
* @var Location
*/
public $reference;
/**
* Metadata about the symbol that can be used to identify or locate its
* definition.
*
* @var SymbolDescriptor
*/
public $symbol;
/**
* @param Location $reference The location in the workspace where the `symbol` is referenced.
* @param SymbolDescriptor $symbol Metadata about the symbol that can be used to identify or locate its definition.
*/
public function __construct(Location $reference = null, SymbolDescriptor $symbol = null)
{
$this->reference = $reference;
$this->symbol = $symbol;
}
}

View File

@ -0,0 +1,132 @@
<?php
namespace LanguageServer\Protocol;
class ServerCapabilities
{
/**
* Defines how text documents are synced.
*
* @var int|null
*/
public $textDocumentSync;
/**
* The server provides hover support.
*
* @var bool|null
*/
public $hoverProvider;
/**
* The server provides completion support.
*
* @var CompletionOptions|null
*/
public $completionProvider;
/**
* The server provides signature help support.
*
* @var SignatureHelpOptions|null
*/
public $signatureHelpProvider;
/**
* The server provides goto definition support.
*
* @var bool|null
*/
public $definitionProvider;
/**
* The server provides find references support.
*
* @var bool|null
*/
public $referencesProvider;
/**
* The server provides document highlight support.
*
* @var bool|null
*/
public $documentHighlightProvider;
/**
* The server provides document symbol support.
*
* @var bool|null
*/
public $documentSymbolProvider;
/**
* The server provides workspace symbol support.
*
* @var bool|null
*/
public $workspaceSymbolProvider;
/**
* The server provides code actions.
*
* @var bool|null
*/
public $codeActionProvider;
/**
* The server provides code lens.
*
* @var CodeLensOptions|null
*/
public $codeLensProvider;
/**
* The server provides document formatting.
*
* @var bool|null
*/
public $documentFormattingProvider;
/**
* The server provides document range formatting.
*
* @var bool|null
*/
public $documentRangeFormattingProvider;
/**
* The server provides document formatting on typing.
*
* @var DocumentOnTypeFormattingOptions|null
*/
public $documentOnTypeFormattingProvider;
/**
* The server provides rename support.
*
* @var bool|null
*/
public $renameProvider;
/**
* The server provides workspace references exporting support.
*
* @var bool|null
*/
public $xworkspaceReferencesProvider;
/**
* The server provides extended text document definition support.
*
* @var bool|null
*/
public $xdefinitionProvider;
/**
* The server provides workspace dependencies support.
*
* @var bool|null
*/
public $dependenciesProvider;
}

View File

@ -0,0 +1,46 @@
<?php
namespace LanguageServer\Protocol;
/**
* Signature help represents the signature of something
* callable. There can be multiple signature but only one
* active and only one active parameter.
*/
class SignatureHelp
{
/**
* One or more signatures.
*
* @var SignatureInformation[]
*/
public $signatures;
/**
* The active signature.
*
* @var int|null
*/
public $activeSignature;
/**
* The active parameter of the active signature.
*
* @var int|null
*/
public $activeParameter;
/**
* Create a SignatureHelp
*
* @param SignatureInformation[] $signatures List of signature information
* @param int|null $activeSignature The active signature, zero based
* @param int|null $activeParameter The active parameter, zero based
*/
public function __construct(array $signatures = [], $activeSignature = null, int $activeParameter = null)
{
$this->signatures = $signatures;
$this->activeSignature = $activeSignature;
$this->activeParameter = $activeParameter;
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace LanguageServer\Protocol;
/**
* Signature help options.
*/
class SignatureHelpOptions
{
/**
* The characters that trigger signature help automatically.
*
* @var string[]|null
*/
public $triggerCharacters;
}

View File

@ -0,0 +1,49 @@
<?php
namespace LanguageServer\Protocol;
/**
* Represents the signature of something callable. A signature
* can have a label, like a function-name, a doc-comment, and
* a set of parameters.
*/
class SignatureInformation
{
/**
* The label of this signature. Will be shown in
* the UI.
*
* @var string
*/
public $label;
/**
* The human-readable doc-comment of this signature. Will be shown
* in the UI but can be omitted.
*
* @var string|null
*/
public $documentation;
/**
* The parameters of this signature.
*
* @var ParameterInformation[]|null
*/
public $parameters;
/**
* Create a SignatureInformation
*
* @param string $label The label of this signature. Will be shown in the UI.
* @param ParameterInformation[]|null The parameters of this signature
* @param string|null The human-readable doc-comment of this signature. Will be shown in the UI
* but can be omitted.
*/
public function __construct(string $label, array $parameters = null, string $documentation = null)
{
$this->label = $label;
$this->parameters = $parameters;
$this->documentation = $documentation;
}
}

View File

@ -0,0 +1,34 @@
<?php
declare(strict_types = 1);
namespace LanguageServer\Protocol;
/**
* Uniquely identifies a symbol
*/
class SymbolDescriptor
{
/**
* The fully qualified structural element name, a globally unique identifier for the symbol.
*
* @var string
*/
public $fqsen;
/**
* Identifies the Composer package the symbol is defined in (if any)
*
* @var PackageDescriptor|null
*/
public $package;
/**
* @param string $fqsen The fully qualified structural element name, a globally unique identifier for the symbol.
* @param PackageDescriptor $package Identifies the Composer package the symbol is defined in
*/
public function __construct(string $fqsen = null, PackageDescriptor $package = null)
{
$this->fqsen = $fqsen;
$this->package = $package;
}
}

View File

@ -1,16 +1,45 @@
<?php
namespace LanguageServer\Factory;
namespace LanguageServer\Protocol;
use LanguageServerProtocol\Location;
use LanguageServerProtocol\SymbolInformation;
use LanguageServerProtocol\SymbolKind;
use Microsoft\PhpParser;
use Microsoft\PhpParser\Node;
use Microsoft\PhpParser\ResolvedName;
use LanguageServer\Factory\LocationFactory;
use Exception;
class SymbolInformationFactory
/**
* Represents information about programming constructs like variables, classes,
* interfaces etc.
*/
class SymbolInformation
{
/**
* The name of this symbol.
*
* @var string
*/
public $name;
/**
* The kind of this symbol.
*
* @var int
*/
public $kind;
/**
* The location of this symbol.
*
* @var Location
*/
public $location;
/**
* The name of the symbol containing this symbol.
*
* @var string|null
*/
public $containerName;
/**
* Converts a Node to a SymbolInformation
*
@ -20,7 +49,7 @@ class SymbolInformationFactory
*/
public static function fromNode($node, string $fqn = null)
{
$symbol = new SymbolInformation();
$symbol = new self;
if ($node instanceof Node\Statement\ClassDeclaration) {
$symbol->kind = SymbolKind::CLASS_;
} else if ($node instanceof Node\Statement\TraitDeclaration) {
@ -70,7 +99,7 @@ class SymbolInformationFactory
$symbol->name = $node->getName();
} else if (isset($node->name)) {
if ($node->name instanceof Node\QualifiedName) {
$symbol->name = (string)ResolvedName::buildName($node->name->nameParts, $node->getFileContents());
$symbol->name = (string)PhpParser\ResolvedName::buildName($node->name->nameParts, $node->getFileContents());
} else {
$symbol->name = ltrim((string)$node->name->getText($node->getFileContents()), "$");
}
@ -80,7 +109,7 @@ class SymbolInformationFactory
return null;
}
$symbol->location = LocationFactory::fromNode($node);
$symbol->location = Location::fromNode($node);
if ($fqn !== null) {
$parts = preg_split('/(::|->|\\\\)/', $fqn);
array_pop($parts);
@ -88,4 +117,18 @@ class SymbolInformationFactory
}
return $symbol;
}
/**
* @param string $name
* @param int $kind
* @param Location $location
* @param string $containerName
*/
public function __construct($name = null, $kind = null, $location = null, $containerName = null)
{
$this->name = $name;
$this->kind = $kind;
$this->location = $location;
$this->containerName = $containerName;
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace LanguageServer\Protocol;
/**
* A symbol kind.
*/
abstract class SymbolKind
{
const FILE = 1;
const MODULE = 2;
const NAMESPACE = 3;
const PACKAGE = 4;
const CLASS_ = 5;
const METHOD = 6;
const PROPERTY = 7;
const FIELD = 8;
const CONSTRUCTOR = 9;
const ENUM = 10;
const INTERFACE = 11;
const FUNCTION = 12;
const VARIABLE = 13;
const CONSTANT = 14;
const STRING = 15;
const NUMBER = 16;
const BOOLEAN = 17;
const ARRAY = 18;
}

View File

@ -0,0 +1,32 @@
<?php
declare(strict_types = 1);
namespace LanguageServer\Protocol;
class SymbolLocationInformation
{
/**
* The location where the symbol is defined, if any.
*
* @var Location|null
*/
public $location;
/**
* Metadata about the symbol that can be used to identify or locate its
* definition.
*
* @var SymbolDescriptor
*/
public $symbol;
/**
* @param SymbolDescriptor $symbol The location where the symbol is defined, if any
* @param Location $location Metadata about the symbol that can be used to identify or locate its definition
*/
public function __construct(SymbolDescriptor $symbol = null, Location $location = null)
{
$this->symbol = $symbol;
$this->location = $location;
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace LanguageServer\Protocol;
/**
* An event describing a change to a text document. If range and rangeLength are omitted
* the new text is considered to be the full content of the document.
*/
class TextDocumentContentChangeEvent
{
/**
* The range of the document that changed.
*
* @var Range|null
*/
public $range;
/**
* The length of the range that got replaced.
*
* @var int|null
*/
public $rangeLength;
/**
* The new text of the document.
*
* @var string
*/
public $text;
}

View File

@ -0,0 +1,21 @@
<?php
namespace LanguageServer\Protocol;
class TextDocumentIdentifier
{
/**
* The text document's URI.
*
* @var string
*/
public $uri;
/**
* @param string $uri The text document's URI.
*/
public function __construct(string $uri = null)
{
$this->uri = $uri;
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace LanguageServer\Protocol;
/**
* An item to transfer a text document from the client to the server.
*/
class TextDocumentItem
{
/**
* The text document's URI.
*
* @var string
*/
public $uri;
/**
* The text document's language identifier.
*
* @var string
*/
public $languageId;
/**
* The version number of this document (it will strictly increase after each
* change, including undo/redo).
*
* @var int
*/
public $version;
/**
* The content of the opened text document.
*
* @var string
*/
public $text;
}

View File

@ -0,0 +1,25 @@
<?php
namespace LanguageServer\Protocol;
/**
* Defines how the host (editor) should sync document changes to the language server.
*/
abstract class TextDocumentSyncKind
{
/**
* Documents should not be synced at all.
*/
const NONE = 0;
/**
* Documents are synced by always sending the full content of the document.
*/
const FULL = 1;
/*
* Documents are synced by sending the full content on open. After that only
* incremental updates to the document are sent.
*/
const INCREMENTAL = 2;
}

31
src/Protocol/TextEdit.php Normal file
View File

@ -0,0 +1,31 @@
<?php
namespace LanguageServer\Protocol;
/**
* A textual edit applicable to a text document.
*/
class TextEdit
{
/**
* The range of the text document to be manipulated. To insert
* text into a document create a range where start === end.
*
* @var Range
*/
public $range;
/**
* The string to be inserted. For delete operations use an
* empty string.
*
* @var string
*/
public $newText;
public function __construct(Range $range = null, string $newText = null)
{
$this->range = $range;
$this->newText = $newText;
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace LanguageServer\Protocol;
class VersionedTextDocumentIdentifier extends TextDocumentIdentifier
{
/**
* The version number of this document.
*
* @var int
*/
public $version;
}

View File

@ -0,0 +1,16 @@
<?php
namespace LanguageServer\Protocol;
/**
* A workspace edit represents changes to many resources managed in the workspace.
*/
class WorkspaceEdit
{
/**
* Holds changes to existing resources. Associative Array from URI to TextEdit
*
* @var TextEdit[]
*/
public $changes;
}

View File

@ -3,7 +3,7 @@ declare(strict_types = 1);
namespace LanguageServer;
use LanguageServer\Message;
use LanguageServer\Protocol\Message;
use AdvancedJsonRpc\Message as MessageBody;
use Sabre\Event\{Loop, Emitter};

View File

@ -3,11 +3,12 @@ declare(strict_types = 1);
namespace LanguageServer;
use LanguageServer\Message;
use LanguageServer\Protocol\Message;
use Sabre\Event\{
Loop,
Promise
};
use RuntimeException;
class ProtocolStreamWriter implements ProtocolWriter
{

View File

@ -3,7 +3,7 @@ declare(strict_types = 1);
namespace LanguageServer;
use LanguageServer\Message;
use LanguageServer\Protocol\Message;
use Sabre\Event\Promise;
interface ProtocolWriter

View File

@ -7,9 +7,7 @@ use LanguageServer\{
CompletionProvider, SignatureHelpProvider, LanguageClient, PhpDocument, PhpDocumentLoader, DefinitionResolver
};
use LanguageServer\Index\ReadableIndex;
use LanguageServer\Factory\LocationFactory;
use LanguageServer\Factory\RangeFactory;
use LanguageServerProtocol\{
use LanguageServer\Protocol\{
FormattingOptions,
Hover,
Location,
@ -25,6 +23,7 @@ use LanguageServerProtocol\{
VersionedTextDocumentIdentifier,
CompletionContext
};
use Microsoft\PhpParser;
use Microsoft\PhpParser\Node;
use Sabre\Event\Promise;
use Sabre\Uri;
@ -110,7 +109,7 @@ class TextDocument
* The document symbol request is sent from the client to the server to list all symbols found in a given text
* document.
*
* @param \LanguageServerProtocol\TextDocumentIdentifier $textDocument
* @param \LanguageServer\Protocol\TextDocumentIdentifier $textDocument
* @return Promise <SymbolInformation[]>
*/
public function documentSymbol(TextDocumentIdentifier $textDocument): Promise
@ -129,7 +128,7 @@ class TextDocument
* document's truth is now managed by the client and the server must not try to read the document's truth using the
* document's uri.
*
* @param \LanguageServerProtocol\TextDocumentItem $textDocument The document that was opened.
* @param \LanguageServer\Protocol\TextDocumentItem $textDocument The document that was opened.
* @return void
*/
public function didOpen(TextDocumentItem $textDocument)
@ -143,8 +142,8 @@ class TextDocument
/**
* The document change notification is sent from the client to the server to signal changes to a text document.
*
* @param \LanguageServerProtocol\VersionedTextDocumentIdentifier $textDocument
* @param \LanguageServerProtocol\TextDocumentContentChangeEvent[] $contentChanges
* @param \LanguageServer\Protocol\VersionedTextDocumentIdentifier $textDocument
* @param \LanguageServer\Protocol\TextDocumentContentChangeEvent[] $contentChanges
* @return void
*/
public function didChange(VersionedTextDocumentIdentifier $textDocument, array $contentChanges)
@ -159,7 +158,7 @@ class TextDocument
* The document's truth now exists where the document's uri points to (e.g. if the document's uri is a file uri the
* truth now exists on disk).
*
* @param \LanguageServerProtocol\TextDocumentIdentifier $textDocument The document that was closed
* @param \LanguageServer\Protocol\TextDocumentIdentifier $textDocument The document that was closed
* @return void
*/
public function didClose(TextDocumentIdentifier $textDocument)
@ -210,7 +209,7 @@ class TextDocument
if ($descendantNode instanceof Node\Expression\Variable &&
$descendantNode->getName() === $node->getName()
) {
$locations[] = LocationFactory::fromNode($descendantNode);
$locations[] = Location::fromNode($descendantNode);
}
}
} else {
@ -227,16 +226,15 @@ class TextDocument
return [];
}
}
$refDocumentPromises = [];
foreach ($this->index->getReferenceUris($fqn) as $uri) {
$refDocumentPromises[] = $this->documentLoader->getOrLoad($uri);
}
$refDocuments = yield Promise\all($refDocumentPromises);
$refDocuments = yield Promise\all(array_map(
[$this->documentLoader, 'getOrLoad'],
$this->index->getReferenceUris($fqn)
));
foreach ($refDocuments as $document) {
$refs = $document->getReferenceNodesByFqn($fqn);
if ($refs !== null) {
foreach ($refs as $ref) {
$locations[] = LocationFactory::fromNode($ref);
$locations[] = Location::fromNode($ref);
}
}
}
@ -335,7 +333,7 @@ class TextDocument
}
yield waitForEvent($this->index, 'definition-added');
}
$range = RangeFactory::fromNode($node);
$range = Range::fromNode($node);
if ($def === null) {
return new Hover([], $range);
}

View File

@ -3,17 +3,18 @@ declare(strict_types = 1);
namespace LanguageServer\Server;
use LanguageServer\{LanguageClient, PhpDocumentLoader};
use LanguageServer\{LanguageClient, Project, PhpDocumentLoader};
use LanguageServer\Index\{ProjectIndex, DependenciesIndex, Index};
use LanguageServer\Factory\LocationFactory;
use LanguageServerProtocol\{
use LanguageServer\Protocol\{
FileChangeType,
FileEvent,
SymbolInformation,
SymbolDescriptor,
PackageDescriptor,
ReferenceInformation,
DependencyReference,
Location
Location,
MessageType
};
use Sabre\Event\Promise;
use function Sabre\Event\coroutine;
@ -151,7 +152,7 @@ class Workspace
$doc = yield $this->documentLoader->getOrLoad($uri);
foreach ($doc->getReferenceNodesByFqn($fqn) as $node) {
$refInfo = new ReferenceInformation;
$refInfo->reference = LocationFactory::fromNode($node);
$refInfo->reference = Location::fromNode($node);
$refInfo->symbol = $query;
$refInfos[] = $refInfo;
}
@ -170,7 +171,7 @@ class Workspace
return [];
}
$dependencyReferences = [];
foreach (array_merge($this->composerLock->packages, (array)$this->composerLock->{'packages-dev'}) as $package) {
foreach (array_merge($this->composerLock->packages, $this->composerLock->{'packages-dev'}) as $package) {
$dependencyReferences[] = new DependencyReference($package);
}
return $dependencyReferences;

View File

@ -4,10 +4,13 @@ declare(strict_types = 1);
namespace LanguageServer;
use LanguageServer\Index\ReadableIndex;
use LanguageServerProtocol\{
use LanguageServer\Protocol\{
Position,
SignatureHelp
SignatureHelp,
SignatureInformation,
ParameterInformation
};
use Microsoft\PhpParser;
use Microsoft\PhpParser\Node;
use Sabre\Event\Promise;
use function Sabre\Event\coroutine;

View File

@ -3,7 +3,7 @@ declare(strict_types = 1);
namespace LanguageServer;
use LanguageServerProtocol\{SignatureInformation, ParameterInformation};
use LanguageServer\Protocol\{SignatureInformation, ParameterInformation};
use Microsoft\PhpParser\FunctionLike;
class SignatureInformationFactory

View File

@ -1,25 +0,0 @@
<?php
declare(strict_types = 1);
namespace LanguageServer;
/**
* Simple Logger that logs to STDERR
*/
class StderrLogger extends \Psr\Log\AbstractLogger implements \Psr\Log\LoggerInterface
{
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string $message
* @param array $context
*
* @return void
*/
public function log($level, $message, array $context = array())
{
$contextStr = empty($context) ? '' : ' ' . \json_encode($context, \JSON_UNESCAPED_SLASHES);
\fwrite(\STDERR, \str_pad(\strtoupper((string)$level), 10) . $message . $contextStr . \PHP_EOL);
}
}

View File

@ -3,9 +3,10 @@ declare(strict_types = 1);
namespace LanguageServer;
use LanguageServer\Factory\RangeFactory;
use LanguageServerProtocol\{Diagnostic, DiagnosticSeverity, Range, Position};
use LanguageServer\Protocol\{Diagnostic, DiagnosticSeverity, Range, Position, TextEdit};
use LanguageServer\Index\Index;
use phpDocumentor\Reflection\DocBlockFactory;
use Sabre\Uri;
use Microsoft\PhpParser;
use Microsoft\PhpParser\Node;
use Microsoft\PhpParser\Token;
@ -101,7 +102,7 @@ class TreeAnalyzer
if ($method && $method->isStatic()) {
$this->diagnostics[] = new Diagnostic(
"\$this can not be used in static methods.",
RangeFactory::fromNode($node),
Range::fromNode($node),
null,
DiagnosticSeverity::ERROR,
'php'

View File

@ -38,7 +38,7 @@ function pathToUri(string $filepath): string
function uriToPath(string $uri)
{
$fragments = parse_url($uri);
if ($fragments === false || !isset($fragments['scheme']) || $fragments['scheme'] !== 'file') {
if ($fragments === null || !isset($fragments['scheme']) || $fragments['scheme'] !== 'file') {
throw new InvalidArgumentException("Not a valid file URI: $uri");
}
$filepath = urldecode($fragments['path']);

View File

@ -5,7 +5,7 @@ namespace LanguageServer\Tests;
use PHPUnit\Framework\TestCase;
use LanguageServer\ClientHandler;
use LanguageServer\Message;
use LanguageServer\Protocol\Message;
use AdvancedJsonRpc;
use Sabre\Event\Loop;

Some files were not shown because too many files have changed in this diff Show More