Commit 916154ca authored by eckhart's avatar eckhart
Browse files

- examples/json/jsonCompiler.py: JSON-LSP ausgebaut (läuft noch nicht :-( )

parent a590f711
......@@ -28,6 +28,7 @@ from .error import *
from .log import *
from .parse import *
from .preprocess import *
from .server import *
from .stringview import *
from .syntaxtree import *
from .testing import *
......@@ -43,6 +44,7 @@ __all__ = (compile.__all__ +
log.__all__ +
parse.__all__ +
preprocess.__all__ +
server.__all__ +
stringview.__all__ +
syntaxtree.__all__ +
testing.__all__ +
......
......@@ -48,7 +48,7 @@ from concurrent.futures import Executor, ThreadPoolExecutor, ProcessPoolExecutor
from concurrent.futures.process import BrokenProcessPool
from functools import wraps, partial
import json
from multiprocessing import Process, Manager, Queue, Value, Array
from multiprocessing import Process, Queue, Value, Array
import sys
import time
from typing import Callable, Coroutine, Optional, Union, Dict, List, Tuple, Sequence, Set, Any, \
......@@ -130,6 +130,7 @@ USE_DEFAULT_HOST = ''
USE_DEFAULT_PORT = -1
STOP_SERVER_REQUEST = b"__STOP_SERVER__"
STOP_SERVER_REQUEST_STR = STOP_SERVER_REQUEST.decode()
IDENTIFY_REQUEST = "identify()"
......@@ -203,7 +204,7 @@ class Server:
func = cast(Callable, rpc_functions)
self.rpc_table = {func.__name__: func}
self.default = func.__name__
assert STOP_SERVER_REQUEST.decode() not in self.rpc_table
assert STOP_SERVER_REQUEST_STR not in self.rpc_table
if IDENTIFY_REQUEST.strip('()') not in self.rpc_table:
self.rpc_table[IDENTIFY_REQUEST.strip('()')] = identify_server
......@@ -312,7 +313,7 @@ class Server:
response = ('Illegal response type %s of reponse object %s. '
'Only bytes and str allowed!'
% (str(type(response)), str(response))).encode()
if self.use_jsonrpc_header:
if self.use_jsonrpc_header and response.startswith(b'{'):
response = JSONRPC_HEADER.format(length=len(response)).encode() + response
append_log(self.log_file, 'RESPONSE: ', response.decode(), '\n\n', echo=self.echo_log)
writer.write(response)
......@@ -386,7 +387,8 @@ class Server:
# i = max(data.find(b'\n\n'), data.find(b'\r\n\r\n')) + 2
while i > 0 and data[i] in (b'{', b'['):
i -= 1
data = data[i:]
if i > 0:
data = data[i:]
if oversized:
rpc_error = -32600, "Invaild Request: Source code too large! Only %i MB allowed" \
% (self.max_source_size // (1024 ** 2))
......@@ -410,7 +412,7 @@ class Server:
' "%s" found.' % obj.get('jsonrpc', b'unknown')
elif 'method' not in obj:
rpc_error = -32600, 'Invalid Request: No method specified.'
elif obj['method'] == STOP_SERVER_REQUEST.decode():
elif obj['method'] == STOP_SERVER_REQUEST_STR:
result = self.stop_response
kill_switch = True
elif obj['method'] not in self.rpc_table:
......@@ -420,6 +422,8 @@ class Server:
method = self.rpc_table[method_name]
params = obj['params'] if 'params' in obj else ()
await run(method_name, method, params)
if method_name == 'exit':
kill_switch = True
try:
try:
......@@ -672,8 +676,6 @@ class LanguageServerProtocol:
self.serverCapabilities = capabilities # type: Dict[str, bool]
self.clientCapabilities = {} # type: Dict[str, bool]
self.server_object = None # type: Server
def initialize(self, **kw):
self.processId = kw['processId']
self.rootUri = kw['rootUri']
......@@ -708,14 +710,13 @@ class LanguageServerProtocol:
def rpc_shutdown(self, *args, **kwargs):
return None
@lsp_rpc
def rpc_exit(self, *args, **kwargs):
self.server_object.terminate_server()
return None
def create_language_server(lsp: LanguageServerProtocol) -> Server:
"""Creates a Language Server for the given Language Server Protocol-object."""
server = Server(lsp.rpc_table, lsp.cpu_bound, lsp.blocking)
lsp.server_object = server
return server
# stringview.py - a string class where slices are views not copies as
# with the standard Python strings.
#
# stringview.pxd - declarations for the cython Python to C compiler
# stringview.pxd - declarations for the cython Python to C compiler
# to speed up handling of StringViews.
#
# Copyright 2016 by Eckhart Arnold (arnold@badw.de)
......
......@@ -111,7 +111,7 @@ def run_server(host, port):
print('PermissionError: Could not write temporary config file: ' + config_filename)
print('Starting server on %s:%i' % (host, port))
DSL_server = create_language_server(LanguageServerProtocol({'default': compile_src}))
DSL_server = create_language_server(LanguageServerProtocol(additional_rpcs={'default': compile_src}))
DSL_server.run_server(host, port)
......
......@@ -6,7 +6,7 @@
import os
import sys
LOGGING = False
LOGGING = ''
scriptpath = os.path.dirname(__file__)
dhparserdir = os.path.abspath(os.path.join(scriptpath, '{reldhparserdir}'))
......
......@@ -212,7 +212,77 @@ def compile_src(source, log_dir=''):
return result_tuple
class JSONLSP(LanguageServerProtocol):
class JsonLSP(LanguageServerProtocol):
def __init__(self):
super().__init__(capabilities={
"testDocumentSync": {
'openClode': False,
'change': 0, # 0 = no sync, 1 = full sync, 2 = incremental sync
'willSave': True,
'willSaveWaitUntil': False,
'save': {
"includeText": False
}
},
"hoverProvider": True,
# "completionProvier": {
# 'resolveProvider': False,
# # 'triggerCharacters': ''
# },
# "signatureHelpProvider": {
# # 'triggerCharacters': ''
# },
"definitionProvider": True,
"typeDefinitionProvider": False,
# "typeDefinitionProvider": {
# # 'id': ''
# 'documentSelector': [
# {
# "language": '',
# "scheme": '',
# "pattern": ''
# }
# ]
# },
"implementationDefinitionProvider": False,
"referencesProvider": True,
"documentHighlightProvider": False,
"documentSymbolProvider": True,
"workspaceSymbolProvider": True,
"codeActionProvider": False,
# "codeActionProvider": {
# 'codeActionKinds': ['']
# },
# "codeLensProvider": {
# 'resolveProvider': False,
# },
"documentFormattingProvider": False,
"documentRangeFormattingProvider": False,
# "documentOnTypeFormattingProvider": {
# 'firstTriggerCharacter': '',
# # 'moreTriggerCharacter': ''
# },
"renameProvider": False,
# "renameProvider": {
# 'prepareProvider': False
# },
# "documentLinkProvider": {
# 'resolveProvider': False
# },
"colorProvider": False,
"foldingRangeProvider": False,
"declarationProvider": False,
# "executeCommandProvider": {
# 'commands': ['']
# },
# "workspace": {
# 'workspaceFolders': {
# 'supported': False,
# 'changeNotifications': '' # string id or bool
# }
# }
}, additional_rpcs={'default': compile_src})
@lsp_rpc
def rpc_textDocument_hover(self, **kwargs):
print(kwargs)
......@@ -221,10 +291,6 @@ class JSONLSP(LanguageServerProtocol):
def rpc_textDocument_definition(self, **kwargs):
print(kwargs)
@lsp_rpc
def rpc_textDocument_xdefinition(self, **kwargs):
print(kwargs)
@lsp_rpc
def rpc_textDocument_references(self, **kwargs):
print(kwargs)
......@@ -233,22 +299,10 @@ class JSONLSP(LanguageServerProtocol):
def rpc_textDocument_documentSymbol(self, **kwargs):
print(kwargs)
@lsp_rpc
def rpc_workspace_xreferences(self, **kwargs):
print(kwargs)
@lsp_rpc
def rpc_workspace_symbol(self, **kwargs):
print(kwargs)
@lsp_rpc
def rpc_workspace_xpackages(self, **kwargs):
print(kwargs)
@lsp_rpc
def rpc_workspace_xdependencies(self, **kwargs):
print(kwargs)
@lsp_rpc
def rpc_S_cancelRequest(self, **kwargs):
print(kwargs)
......
......@@ -95,12 +95,12 @@ def json_rpc(func, params=[], ID=None) -> str:
def run_server(host, port):
try:
from jsonCompiler import compile_src
from jsonCompiler import JsonLSP
except ModuleNotFoundError:
from tst_json_grammar import recompile_grammar
recompile_grammar(os.path.join(scriptpath, 'json.ebnf'), force=False)
from jsonCompiler import compile_src
from DHParser.server import LanguageServerProtocol, create_language_server
from DHParser.server import create_language_server
config_filename = get_config_filename()
try:
with open(config_filename, 'w') as f:
......@@ -109,7 +109,7 @@ def run_server(host, port):
print('PermissionError: Could not write temporary config file: ' + config_filename)
print('Starting server on %s:%i' % (host, port))
DSL_server = create_language_server(LanguageServerProtocol({'default': compile_src}))
DSL_server = create_language_server(JsonLSP())
DSL_server.run_server(host, port)
......
......@@ -16,6 +16,5 @@ Client-module for Visual Studio Code to connect jsonServer.py as a language-serv
- Select `Launch Client` from the drop down.
- Run the launch config.
- If you want to debug the server as well use the launch configuration `Attach to Server`
- In the [Extension Development Host] instance of VSCode, open a document in 'plain text' language mode.
- Type `j` or `t` to see `Javascript` and `TypeScript` completion.
- Enter text content such as `AAA aaa BBB`. The extension will emit diagnostics for all words in all-uppercase.
- In the [Extension Development Host] instance of VSCode, open a document in 'jsonc' language mode.
......@@ -311,7 +311,12 @@ class TestLanguageServer:
{'processId': 0,
'rootUri': 'file://~/tmp',
'capabilities': {}}))
res = json.loads(response)
# print(response)
i = response.find('"jsonrpc"') - 1
while i > 0 and response[i] in ('{', '['):
i -= 1
res = json.loads(response[i:])
# print(response, res)
assert 'result' in res and 'capabilities' in res['result']
......
......@@ -104,7 +104,7 @@ class TestLoggingAndLoading:
assert not os.path.exists("TESTLOGS"), \
"Log dir should be created lazily!"
dirname = log_dir()
print(type(dirname), dirname)
# print(type(dirname), dirname)
assert os.path.basename(dirname) == "TESTLOGS"
assert is_logging(), "is_logging() should return True, if logging is on"
save_log_dir = suspend_logging()
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment