Add new query for getting available variables (#52)

* Add new query for getting available variables

* use array for findAllPreviousVariables
This commit is contained in:
Kurt Hutten
2023-03-10 08:35:30 +11:00
committed by GitHub
parent d729ae3990
commit 2bb987b3b5
3 changed files with 102 additions and 4 deletions

View File

@ -1,6 +1,7 @@
import { PathToNode } from './executor'
import { PathToNode, ProgramMemory } from './executor'
import { Range } from '../useStore'
import { Program } from './abstractSyntaxTree'
import { splitPathAtLastIndex } from './modifyAst'
export function getNodeFromPath<T>(
node: Program,
@ -133,3 +134,43 @@ export function getNodePathFromSourceRange(
}
return path
}
interface PrevVariable<T> {
key: string
value: T
}
export function findAllPreviousVariables(
ast: Program,
programMemory: ProgramMemory,
sourceRange: Range,
type: 'number' | 'string' = 'number'
): {
variables: PrevVariable<typeof type extends 'number' ? number : string>[]
bodyPath: PathToNode
insertIndex: number
} {
const path = getNodePathFromSourceRange(ast, sourceRange)
const { path: pathToDec } = getNodeFromPath(ast, path, 'VariableDeclaration')
const { index: insertIndex, path: bodyPath } = splitPathAtLastIndex(pathToDec)
const { node: bodyItems } = getNodeFromPath<Program['body']>(ast, bodyPath)
const variables: PrevVariable<any>[] = []
bodyItems.forEach((item) => {
if (item.type !== 'VariableDeclaration' || item.end > sourceRange[0]) return
const varName = item.declarations[0].id.name
const varValue = programMemory?.root[varName]
if (typeof varValue?.value !== type) return
variables.push({
key: varName,
value: varValue.value,
})
})
return {
insertIndex,
bodyPath: bodyPath,
variables,
}
}