| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | */ |
| 7 | |
| 8 | import * as t from '@babel/types'; |
| 9 | import {type Position} from 'vscode-languageserver/node'; |
| 10 | |
| 11 | export type Range = [Position, Position]; |
| 12 | |
| 13 | export function isPositionWithinRange( |
| 14 | position: Position, |
| 15 | [start, end]: Range, |
| 16 | ): boolean { |
| 17 | return position.line >= start.line && position.line <= end.line; |
| 18 | } |
| 19 | |
| 20 | export function isRangeWithinRange(aRange: Range, bRange: Range): boolean { |
| 21 | const startComparison = comparePositions(aRange[0], bRange[0]); |
| 22 | const endComparison = comparePositions(aRange[1], bRange[1]); |
| 23 | return startComparison >= 0 && endComparison <= 0; |
| 24 | } |
| 25 | |
| 26 | function comparePositions(a: Position, b: Position): number { |
| 27 | const lineComparison = a.line - b.line; |
| 28 | if (lineComparison === 0) { |
| 29 | return a.character - b.character; |
| 30 | } else { |
| 31 | return lineComparison; |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | export function sourceLocationToRange( |
| 36 | loc: t.SourceLocation, |
| 37 | ): [Position, Position] { |
| 38 | return [ |
| 39 | {line: loc.start.line - 1, character: loc.start.column}, |
| 40 | {line: loc.end.line - 1, character: loc.end.column}, |
| 41 | ]; |
| 42 | } |