|
| 1 | +/* |
| 2 | + * This file is a part of BSL Language Server. |
| 3 | + * |
| 4 | + * Copyright (c) 2018-2026 |
| 5 | + * Alexey Sosnoviy <[email protected]>, Nikita Fedkin <[email protected]> and contributors |
| 6 | + * |
| 7 | + * SPDX-License-Identifier: LGPL-3.0-or-later |
| 8 | + * |
| 9 | + * BSL Language Server is free software; you can redistribute it and/or |
| 10 | + * modify it under the terms of the GNU Lesser General Public |
| 11 | + * License as published by the Free Software Foundation; either |
| 12 | + * version 3.0 of the License, or (at your option) any later version. |
| 13 | + * |
| 14 | + * BSL Language Server is distributed in the hope that it will be useful, |
| 15 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 16 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 17 | + * Lesser General Public License for more details. |
| 18 | + * |
| 19 | + * You should have received a copy of the GNU Lesser General Public |
| 20 | + * License along with BSL Language Server. |
| 21 | + */ |
| 22 | +package com.github._1c_syntax.bsl.languageserver.inlayhints; |
| 23 | + |
| 24 | +import com.github._1c_syntax.bsl.languageserver.context.DocumentContext; |
| 25 | +import com.github._1c_syntax.bsl.languageserver.references.model.Reference; |
| 26 | +import com.github._1c_syntax.bsl.languageserver.utils.Ranges; |
| 27 | +import com.github._1c_syntax.bsl.languageserver.utils.Trees; |
| 28 | +import com.github._1c_syntax.bsl.parser.BSLParser; |
| 29 | +import org.antlr.v4.runtime.ParserRuleContext; |
| 30 | +import org.eclipse.lsp4j.Range; |
| 31 | + |
| 32 | +import java.util.HashMap; |
| 33 | +import java.util.Map; |
| 34 | +import java.util.Optional; |
| 35 | + |
| 36 | +/** |
| 37 | + * Индекс {@code doCall}-узлов документа по диапазону имени вызываемого метода. |
| 38 | + * <p> |
| 39 | + * Строится одним обходом AST документа и позволяет резолвить вызов по ссылке |
| 40 | + * на метод за {@code O(1)} вместо повторного обхода AST на каждую ссылку. |
| 41 | + * Ключом служит {@link Reference#selectionRange()} ссылки, совпадающий с |
| 42 | + * диапазоном имени вызываемого метода (для конструктора — с диапазоном имени типа). |
| 43 | + */ |
| 44 | +final class DoCallRangeIndex { |
| 45 | + |
| 46 | + private final Map<String, BSLParser.DoCallContext> doCallsByMethodNameRange; |
| 47 | + |
| 48 | + private DoCallRangeIndex(Map<String, BSLParser.DoCallContext> doCallsByMethodNameRange) { |
| 49 | + this.doCallsByMethodNameRange = doCallsByMethodNameRange; |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Строит индекс по AST документа. |
| 54 | + * <p> |
| 55 | + * Все {@code doCall}-узлы документа собираются в карту по диапазону имени |
| 56 | + * вызываемого метода (для конструктора — по диапазону имени типа). Этот диапазон |
| 57 | + * совпадает с {@link Reference#selectionRange()} соответствующей ссылки. |
| 58 | + * |
| 59 | + * @param documentContext контекст документа, AST которого обходится |
| 60 | + * @return индекс вызовов документа; пустой, если вызовов нет |
| 61 | + */ |
| 62 | + static DoCallRangeIndex of(DocumentContext documentContext) { |
| 63 | + var ast = documentContext.getAst(); |
| 64 | + var doCalls = Trees.findAllRuleNodes(ast, BSLParser.RULE_doCall); |
| 65 | + Map<String, BSLParser.DoCallContext> result = HashMap.newHashMap(doCalls.size()); |
| 66 | + for (var node : doCalls) { |
| 67 | + var doCall = (BSLParser.DoCallContext) node; |
| 68 | + var doCallParent = doCall.getParent(); |
| 69 | + if (doCallParent == null) { |
| 70 | + continue; |
| 71 | + } |
| 72 | + methodNameRange(doCallParent) |
| 73 | + .ifPresent(methodNameRange -> result.putIfAbsent(rangeKey(methodNameRange), doCall)); |
| 74 | + } |
| 75 | + return new DoCallRangeIndex(result); |
| 76 | + } |
| 77 | + |
| 78 | + /** |
| 79 | + * Возвращает {@code doCall}-узел, соответствующий ссылке на метод. |
| 80 | + * |
| 81 | + * @param reference ссылка на вызываемый метод; используется её {@link Reference#selectionRange()} |
| 82 | + * @return узел вызова либо {@link Optional#empty()}, если в документе нет вызова с таким диапазоном |
| 83 | + */ |
| 84 | + Optional<BSLParser.DoCallContext> doCallFor(Reference reference) { |
| 85 | + return Optional.ofNullable(doCallsByMethodNameRange.get(rangeKey(reference.selectionRange()))); |
| 86 | + } |
| 87 | + |
| 88 | + /** |
| 89 | + * Строковый ключ карты вызовов по диапазону имени метода. |
| 90 | + * <p> |
| 91 | + * Используется вместо {@link Range} из lsp4j, который не реализует |
| 92 | + * {@link Comparable}: {@link String} реализует {@link Comparable} и не зависит |
| 93 | + * от деталей {@link Range#hashCode()}, что устраняет риск деградации хэш-карты |
| 94 | + * при коллизиях ключей. |
| 95 | + * |
| 96 | + * @param range диапазон имени метода/типа |
| 97 | + * @return ключ вида {@code "startLine:startChar:endLine:endChar"} |
| 98 | + */ |
| 99 | + private static String rangeKey(Range range) { |
| 100 | + var start = range.getStart(); |
| 101 | + var end = range.getEnd(); |
| 102 | + return start.getLine() + ":" + start.getCharacter() + ":" + end.getLine() + ":" + end.getCharacter(); |
| 103 | + } |
| 104 | + |
| 105 | + /** |
| 106 | + * Диапазон имени вызываемого метода для родителя {@code doCall}-узла — |
| 107 | + * именно его {@link com.github._1c_syntax.bsl.languageserver.references.ReferenceIndex} |
| 108 | + * хранит в {@link Reference#selectionRange()}. |
| 109 | + * |
| 110 | + * @param doCallParent родительский узел вызова (methodCall, globalMethodCall или newExpression) |
| 111 | + * @return диапазон имени метода/типа либо {@link Optional#empty()}, |
| 112 | + * если узел не является вызовом метода |
| 113 | + */ |
| 114 | + private static Optional<Range> methodNameRange(ParserRuleContext doCallParent) { |
| 115 | + if (doCallParent instanceof BSLParser.MethodCallContext methodCallContext) { |
| 116 | + var methodName = methodCallContext.methodName(); |
| 117 | + return methodName == null ? Optional.empty() : Optional.of(Ranges.create(methodName)); |
| 118 | + } else if (doCallParent instanceof BSLParser.GlobalMethodCallContext globalMethodCallContext) { |
| 119 | + var methodName = globalMethodCallContext.methodName(); |
| 120 | + return methodName == null ? Optional.empty() : Optional.of(Ranges.create(methodName)); |
| 121 | + } else if (doCallParent instanceof BSLParser.NewExpressionContext newExpressionContext) { |
| 122 | + var typeName = newExpressionContext.typeName(); |
| 123 | + if (typeName != null && typeName.IDENTIFIER() != null) { |
| 124 | + return Optional.of(Ranges.create(typeName.IDENTIFIER())); |
| 125 | + } |
| 126 | + return Optional.empty(); |
| 127 | + } else { |
| 128 | + return Optional.empty(); |
| 129 | + } |
| 130 | + } |
| 131 | +} |
0 commit comments