|
1 | 1 | package liquidjava.utils; |
2 | 2 |
|
| 3 | +import java.nio.file.Files; |
3 | 4 | import java.util.List; |
4 | 5 | import java.util.Map; |
5 | | -import java.util.Scanner; |
6 | 6 | import java.util.Set; |
7 | 7 | import java.util.stream.Stream; |
8 | 8 |
|
@@ -121,40 +121,30 @@ public static SourcePosition getRealPosition(CtElement element) { |
121 | 121 | public static String getExpressionFromPosition(SourcePosition position) { |
122 | 122 | if (position == null || position.getFile() == null) |
123 | 123 | return null; |
124 | | - int startLine = position.getLine(); |
125 | | - int endLine = position.getEndLine(); |
126 | | - try (Scanner scanner = new Scanner(position.getFile())) { |
| 124 | + try { |
| 125 | + List<String> lines = Files.readAllLines(position.getFile().toPath()); |
127 | 126 | StringBuilder sb = new StringBuilder(); |
128 | | - int currentLine = 1; |
129 | | - while (scanner.hasNextLine()) { |
130 | | - String line = scanner.nextLine(); |
131 | | - if (currentLine >= startLine && currentLine <= endLine) { |
132 | | - // First line starts at the element's column; continuation lines are taken whole. |
133 | | - String piece = ((currentLine == startLine) ? line.substring(position.getColumn() - 2) : line) |
134 | | - .trim(); |
135 | | - if (sb.length() > 0) |
136 | | - sb.append(' '); |
137 | | - sb.append(piece); |
138 | | - if (currentLine >= endLine || endsStatement(piece)) |
139 | | - break; |
140 | | - } |
141 | | - currentLine++; |
| 127 | + for (int n = position.getLine(); n <= position.getEndLine() && n <= lines.size(); n++) { |
| 128 | + // First line starts at the element's column; continuation lines are taken whole. |
| 129 | + String piece = (n == position.getLine() ? lines.get(n - 1).substring(position.getColumn() - 2) |
| 130 | + : lines.get(n - 1)).trim(); |
| 131 | + if (sb.length() > 0) |
| 132 | + sb.append(' '); |
| 133 | + sb.append(piece); |
| 134 | + if (endsStatement(piece)) |
| 135 | + break; |
142 | 136 | } |
143 | 137 | return sb.length() == 0 ? null : sb.toString(); |
144 | 138 | } catch (Exception e) { |
145 | | - // ignore |
| 139 | + return null; // unreadable file / out-of-range column → no snippet |
146 | 140 | } |
147 | | - return null; |
148 | 141 | } |
149 | 142 |
|
150 | 143 | /** |
151 | 144 | * A trimmed source line ends a statement / opens a block when its last char is {@code ;}, <code>{</code> or |
152 | 145 | * <code>}</code> — used to bound multi-line snippet extraction. |
153 | 146 | */ |
154 | 147 | private static boolean endsStatement(String trimmedLine) { |
155 | | - if (trimmedLine.isEmpty()) |
156 | | - return false; |
157 | | - char last = trimmedLine.charAt(trimmedLine.length() - 1); |
158 | | - return last == ';' || last == '{' || last == '}'; |
| 148 | + return !trimmedLine.isEmpty() && "{};".indexOf(trimmedLine.charAt(trimmedLine.length() - 1)) >= 0; |
159 | 149 | } |
160 | 150 | } |
0 commit comments