refactor: move findCaretTokenIndex file to parser/common/utils

This commit is contained in:
hayden
2023-12-12 19:39:28 +08:00
committed by Hayden
parent 96b0376510
commit eb5b0a5550
2 changed files with 2 additions and 2 deletions

View File

@ -9,7 +9,7 @@ import {
} from 'antlr4ts';
import { ParseTreeWalker, ParseTreeListener } from 'antlr4ts/tree';
import { CandidatesCollection, CodeCompletionCore } from 'antlr4-c3';
import { findCaretTokenIndex } from '../../utils/findCaretTokenIndex';
import { findCaretTokenIndex } from './utils/findCaretTokenIndex';
import {
CaretPosition,
Suggestions,

View File

@ -0,0 +1,34 @@
import { Token } from 'antlr4ts';
import { CaretPosition } from '../basic-parser-types';
/**
* find token index via caret position (cursor position)
* @param caretPosition
* @param allTokens all the tokens
* @returns caretTokenIndex
*/
export function findCaretTokenIndex(caretPosition: CaretPosition, allTokens: Token[]) {
const { lineNumber: caretLine, column: caretCol } = caretPosition;
let left = 0;
let right = allTokens.length - 1;
while (left <= right) {
const mid = left + ((right - left) >> 1);
const token = allTokens[mid];
if (
token.line > caretLine ||
(token.line === caretLine && token.charPositionInLine + 1 >= caretCol)
) {
right = mid - 1;
} else if (
token.line < caretLine ||
(token.line === caretLine &&
token.charPositionInLine + token.text.length + 1 < caretCol)
) {
left = mid + 1;
} else {
return allTokens[mid].tokenIndex;
}
}
return null;
}