Skip to content

Commit a82f4e2

Browse files
committed
Improve code structure
- Use super constructors and super methods - Remove code duplications where possible - Fixed typos
1 parent e4614bd commit a82f4e2

File tree

7 files changed

+126
-228
lines changed

7 files changed

+126
-228
lines changed

fortls/helper_functions.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def expand_name(line: str, char_poss: int) -> str:
3838
regexs = [LOGICAL_REGEX, SQ_STRING_REGEX, DQ_STRING_REGEX, WORD_REGEX, NUMBER_REGEX]
3939
for r in regexs:
4040
for num_match in r.finditer(line):
41-
if num_match.start(0) <= char_poss and num_match.end(0) >= char_poss:
41+
if num_match.start(0) <= char_poss <= num_match.end(0):
4242
return num_match.group(0)
4343
return ""
4444

@@ -344,7 +344,7 @@ def get_keywords(keywords, keyword_info={}):
344344
def get_paren_substring(test_str):
345345
i1 = test_str.find("(")
346346
i2 = test_str.rfind(")")
347-
if i1 > -1 and i2 > i1:
347+
if -1 < i1 < i2:
348348
return test_str[i1 + 1 : i2]
349349
else:
350350
return None

fortls/intrinsics.py

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -54,17 +54,7 @@ def get_snippet(self, name_replace=None, drop_arg=-1):
5454
arg_snip = None
5555
else:
5656
arg_list = self.args.split(",")
57-
place_holders = []
58-
for i, arg in enumerate(arg_list):
59-
opt_split = arg.split("=")
60-
if len(opt_split) > 1:
61-
place_holders.append(
62-
"{1}=${{{0}:{2}}}".format(i + 1, opt_split[0], opt_split[1])
63-
)
64-
else:
65-
place_holders.append("${{{0}:{1}}}".format(i + 1, arg))
66-
arg_str = "({0})".format(", ".join(arg_list))
67-
arg_snip = "({0})".format(", ".join(place_holders))
57+
arg_str, arg_snip = self.get_placeholders(arg_list)
6858
name = self.name
6959
if name_replace is not None:
7060
name = name_replace
@@ -80,9 +70,6 @@ def get_signature(self):
8070
call_sig, _ = self.get_snippet()
8171
return call_sig, self.doc_str, arg_sigs
8272

83-
def get_documentation(self):
84-
return self.doc_str
85-
8673
def get_hover(self, long=False):
8774
return self.doc_str, False
8875

fortls/jsonrpc.py

Lines changed: 2 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -258,35 +258,11 @@ def write_rpc_notification(method, params):
258258

259259

260260
def read_rpc_messages(content):
261-
def read_header_content_length(line):
262-
if len(line) < 2 or line[-2:] != "\r\n":
263-
raise JSONRPC2ProtocolError("Line endings must be \\r\\n")
264-
if line.startswith("Content-Length: "):
265-
_, value = line.split("Content-Length: ")
266-
value = value.strip()
267-
try:
268-
return int(value)
269-
except ValueError:
270-
raise JSONRPC2ProtocolError(f"Invalid Content-Length header: {value}")
271-
272-
def receive_next():
273-
line = content.readline()
274-
if line == "":
275-
raise EOFError()
276-
length = read_header_content_length(line)
277-
# Keep reading headers until we find the sentinel line
278-
# for the JSON request.
279-
while line != "\r\n":
280-
line = content.readline()
281-
body = content.read(length)
282-
# log.debug("RECV %s", body)
283-
return json.loads(body)
284-
285-
#
261+
conn = JSONRPC2Connection(content)
286262
result_list = []
287263
while True:
288264
try:
289-
result = receive_next()
265+
result = conn._receive()
290266
except EOFError:
291267
break
292268
else:

fortls/langserver.py

Lines changed: 33 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -206,12 +206,12 @@ def serve_initialize(self, request):
206206
datefmt="%H:%M:%S",
207207
level=logging.INFO,
208208
)
209-
self.__config_logger(request)
209+
self._config_logger(request)
210210
init_debug_log = self._load_config_file()
211211
if init_debug_log:
212-
self.__config_logger(request)
213-
self.__load_intrinsics()
214-
self.__add_source_dirs()
212+
self._config_logger(request)
213+
self._load_intrinsics()
214+
self._add_source_dirs()
215215

216216
# Initialize workspace
217217
self.workspace_init()
@@ -905,7 +905,7 @@ def get_all_references(self, def_obj, type_mem, file_obj=None):
905905
ref_match = True
906906
elif var_def.parent.get_type() == CLASS_TYPE_ID:
907907
if type_mem:
908-
for inherit_def in var_def.parent.get_overriden(
908+
for inherit_def in var_def.parent.get_overridden(
909909
def_name
910910
):
911911
if def_fqsn == inherit_def.FQSN:
@@ -984,19 +984,7 @@ def serve_definition(self, request):
984984
return None
985985
# Construct link reference
986986
if var_obj.file_ast.file is not None:
987-
var_file = var_obj.file_ast.file
988-
sline, schar, echar = var_file.find_word_in_code_line(
989-
var_obj.sline - 1, var_obj.name
990-
)
991-
if schar < 0:
992-
schar = echar = 0
993-
return {
994-
"uri": path_to_uri(var_file.path),
995-
"range": {
996-
"start": {"line": sline, "character": schar},
997-
"end": {"line": sline, "character": echar},
998-
},
999-
}
987+
return self._create_ref_link(var_obj)
1000988
return None
1001989

1002990
def serve_hover(self, request: dict):
@@ -1052,7 +1040,7 @@ def create_signature_hover():
10521040
hover_array.append(create_hover(hover_str, highlight))
10531041
elif self.variable_hover and (var_type == VAR_TYPE_ID):
10541042
# Unless we have a Fortran literal include the desc in the hover msg
1055-
# See get_definition for an explanaiton about this default name
1043+
# See get_definition for an explanation about this default name
10561044
if not var_obj.desc.startswith(FORTRAN_LITERAL):
10571045
hover_str, highlight = var_obj.get_hover()
10581046
hover_array.append(create_hover(hover_str, highlight))
@@ -1095,19 +1083,7 @@ def serve_implementation(self, request):
10951083
if var_obj.parent.get_type() == CLASS_TYPE_ID:
10961084
impl_obj = var_obj.link_obj
10971085
if (impl_obj is not None) and (impl_obj.file_ast.file is not None):
1098-
impl_file = impl_obj.file_ast.file
1099-
sline, schar, echar = impl_file.find_word_in_code_line(
1100-
impl_obj.sline - 1, impl_obj.name
1101-
)
1102-
if schar < 0:
1103-
schar = echar = 0
1104-
return {
1105-
"uri": path_to_uri(impl_file.path),
1106-
"range": {
1107-
"start": {"line": sline, "character": schar},
1108-
"end": {"line": sline, "character": echar},
1109-
},
1110-
}
1086+
return self._create_ref_link(impl_obj)
11111087
return None
11121088

11131089
def serve_rename(self, request):
@@ -1379,7 +1355,7 @@ def update_workspace_file(
13791355

13801356
def workspace_init(self):
13811357

1382-
file_list = self.__get_source_files()
1358+
file_list = self._get_source_files()
13831359
# Process files
13841360
pool = Pool(processes=self.nthreads)
13851361
results = {}
@@ -1440,13 +1416,13 @@ def _load_config_file(self) -> bool | None:
14401416
config_dict = json.load(jsonfile)
14411417

14421418
# Include and Exclude directories
1443-
self.__load_config_file_dirs(config_dict)
1419+
self._load_config_file_dirs(config_dict)
14441420

14451421
# General options
1446-
self.__load_config_file_general(config_dict)
1422+
self._load_config_file_general(config_dict)
14471423

14481424
# Preprocessor options
1449-
self.__load_config_file_preproc(config_dict)
1425+
self._load_config_file_preproc(config_dict)
14501426

14511427
# Debug options
14521428
debugging: bool = config_dict.get("debug_log", self.debug_log)
@@ -1467,7 +1443,7 @@ def _load_config_file(self) -> bool | None:
14671443
self.post_messages.append([1, msg])
14681444
log.error(msg)
14691445

1470-
def __load_config_file_dirs(self, config_dict: dict) -> None:
1446+
def _load_config_file_dirs(self, config_dict: dict) -> None:
14711447
# Exclude paths (directories & files)
14721448
# with glob resolution
14731449
for path in config_dict.get("excl_paths", []):
@@ -1492,7 +1468,7 @@ def __load_config_file_dirs(self, config_dict: dict) -> None:
14921468
self.FORTRAN_SRC_EXT_REGEX = src_file_exts(self.incl_suffixes)
14931469
self.excl_suffixes = set(config_dict.get("excl_suffixes", []))
14941470

1495-
def __load_config_file_general(self, config_dict: dict) -> None:
1471+
def _load_config_file_general(self, config_dict: dict) -> None:
14961472
# General options ------------------------------------------------------
14971473
self.nthreads = config_dict.get("nthreads", self.nthreads)
14981474
self.notify_init = config_dict.get("notify_init", self.notify_init)
@@ -1541,7 +1517,7 @@ def __load_config_file_general(self, config_dict: dict) -> None:
15411517
"enable_code_actions", self.enable_code_actions
15421518
)
15431519

1544-
def __load_config_file_preproc(self, config_dict: dict) -> None:
1520+
def _load_config_file_preproc(self, config_dict: dict) -> None:
15451521
self.pp_suffixes = config_dict.get("pp_suffixes", None) # TODO: set def
15461522
self.pp_defs = config_dict.get("pp_defs", {}) # TODO: set other dif?
15471523
if isinstance(self.pp_defs, list):
@@ -1552,7 +1528,7 @@ def __load_config_file_preproc(self, config_dict: dict) -> None:
15521528
only_dirs(resolve_globs(path, self.root_path), self.post_messages)
15531529
)
15541530

1555-
def __add_source_dirs(self) -> None:
1531+
def _add_source_dirs(self) -> None:
15561532
"""Will recursively add all subdirectories that contain Fortran
15571533
source files only if the option `source_dirs` has not been specified
15581534
in the configuration file or no configuration file is present
@@ -1570,7 +1546,7 @@ def __add_source_dirs(self) -> None:
15701546
if root not in self.source_dirs and root not in self.excl_paths:
15711547
self.source_dirs.add(str(Path(root).resolve()))
15721548

1573-
def __get_source_files(self) -> list[str]:
1549+
def _get_source_files(self) -> list[str]:
15741550
"""Get all the source files present in `self.source_dirs`,
15751551
exclude any files found in `self.excl_paths`^ and ignore
15761552
any files ending with `self.excl_suffixes`.
@@ -1603,7 +1579,7 @@ def __get_source_files(self) -> list[str]:
16031579
file_list.append(p)
16041580
return file_list
16051581

1606-
def __config_logger(self, request) -> None:
1582+
def _config_logger(self, request) -> None:
16071583
"""Configures the logger to save Language Server requests/responses to a file
16081584
the logger will by default output to the main (stderr, stdout) channels.
16091585
"""
@@ -1619,7 +1595,7 @@ def __config_logger(self, request) -> None:
16191595
log.debug("REQUEST %s %s", request.get("id"), request.get("method"))
16201596
self.post_messages.append([3, "FORTLS debugging enabled"])
16211597

1622-
def __load_intrinsics(self) -> None:
1598+
def _load_intrinsics(self) -> None:
16231599
# Load intrinsics
16241600
set_keyword_ordering(True) # Always sort intrinsics
16251601
if self.lowercase_intrinsics:
@@ -1635,6 +1611,20 @@ def __load_intrinsics(self) -> None:
16351611
# Set object settings
16361612
set_keyword_ordering(self.sort_keywords)
16371613

1614+
def _create_ref_link(self, obj):
1615+
"""Create a link reference to an object"""
1616+
obj_file = obj.file_ast.file
1617+
sline, schar, echar = obj_file.find_word_in_code_line(obj.sline - 1, obj.name)
1618+
if schar < 0:
1619+
schar = echar = 0
1620+
return {
1621+
"uri": path_to_uri(obj_file.path),
1622+
"range": {
1623+
"start": {"line": sline, "character": schar},
1624+
"end": {"line": sline, "character": echar},
1625+
},
1626+
}
1627+
16381628

16391629
class JSONRPC2Error(Exception):
16401630
def __init__(self, code, message, data=None):

0 commit comments

Comments
 (0)