-
-
Notifications
You must be signed in to change notification settings - Fork 88
Introduce tree-sitter queries for syntactic scopes #629
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
3b7ccef
Introduce tree-sitter queries for syntactic scopes
pokey f8dd20d
Initial working version
pokey 5cbe3da
Cleanup
pokey df2736f
remove another test file for now
pokey 04ab57f
revert target descriptor change
pokey 2c0ac1b
fixes
pokey d968704
more cleanup
pokey 17f3867
Fix tests
pokey 4e34531
Add test
pokey 2c25fa9
More tests
pokey 04e3e7f
docstring
pokey 0fb7cfb
Add missing test
pokey 70031d2
remove test
pokey 26669cd
renames
pokey 8ef5935
more tests
pokey b68bd04
more tests
pokey 2632601
test
pokey c697971
docs
pokey 0542e8f
more tests
pokey e0523e2
Remove experimental query files
pokey ecdb2ce
Test cleanup
pokey 6c8058f
`ruby/scopeTypes.scm` => `ruby.scm`
pokey 631aa40
Remove test case
pokey 38d35f7
More cleanup
pokey ecaf27f
PR feedback
pokey File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
69 changes: 69 additions & 0 deletions
69
packages/cursorless-engine/src/languages/LanguageDefinition.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
import { ScopeType, SimpleScopeType } from "@cursorless/common"; | ||
import { Query } from "web-tree-sitter"; | ||
import { ide } from "../singletons/ide.singleton"; | ||
import { join } from "path"; | ||
import { TreeSitterScopeHandler } from "../processTargets/modifiers/scopeHandlers"; | ||
import { TreeSitter } from "../typings/TreeSitter"; | ||
import { existsSync, readFileSync } from "fs"; | ||
import { LanguageId } from "./constants"; | ||
|
||
/** | ||
* Represents a language definition for a single language, including the | ||
* tree-sitter query used to extract scopes for the given language | ||
*/ | ||
export class LanguageDefinition { | ||
private constructor( | ||
private treeSitter: TreeSitter, | ||
/** | ||
* The tree-sitter query used to extract scopes for the given language. | ||
* Note that this query contains patterns for all scope types that the | ||
* language supports using new-style tree-sitter queries | ||
*/ | ||
private query: Query, | ||
) {} | ||
|
||
/** | ||
* Construct a language definition for the given language id, if the language | ||
* has a new-style query definition, or return undefined if the language doesn't | ||
* | ||
* @param treeSitter The tree-sitter instance to use for parsing | ||
* @param languageId The language id for which to create a language definition | ||
* @returns A language definition for the given language id, or undefined if the given language | ||
* id doesn't have a new-style query definition | ||
*/ | ||
static create( | ||
treeSitter: TreeSitter, | ||
languageId: LanguageId, | ||
): LanguageDefinition | undefined { | ||
const queryPath = join(ide().assetsRoot, "queries", `${languageId}.scm`); | ||
|
||
if (!existsSync(queryPath)) { | ||
return undefined; | ||
} | ||
|
||
const rawLanguageQueryString = readFileSync(queryPath, "utf8"); | ||
|
||
return new LanguageDefinition( | ||
treeSitter, | ||
treeSitter.getLanguage(languageId)!.query(rawLanguageQueryString), | ||
); | ||
} | ||
|
||
/** | ||
* @param scopeType The scope type for which to get a scope handler | ||
* @returns A scope handler for the given scope type and language id, or | ||
* undefined if the given scope type / language id combination is still using | ||
* legacy pathways | ||
*/ | ||
getScopeHandler(scopeType: ScopeType) { | ||
if (!this.query.captureNames.includes(scopeType.type)) { | ||
return undefined; | ||
} | ||
|
||
return new TreeSitterScopeHandler( | ||
this.treeSitter, | ||
this.query, | ||
scopeType as SimpleScopeType, | ||
); | ||
} | ||
} |
54 changes: 54 additions & 0 deletions
54
packages/cursorless-engine/src/languages/LanguageDefinitions.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
import { TreeSitter } from ".."; | ||
import { LanguageDefinition } from "./LanguageDefinition"; | ||
import { LanguageId } from "./constants"; | ||
|
||
/** | ||
* Sentinel value to indicate that a language doesn't have | ||
* a new-style query definition file | ||
*/ | ||
const LANGUAGE_UNDEFINED = Symbol("LANGUAGE_UNDEFINED"); | ||
|
||
/** | ||
* Keeps a map from language ids to {@link LanguageDefinition} instances, | ||
* constructing them as necessary | ||
*/ | ||
export class LanguageDefinitions { | ||
/** | ||
* Maps from language id to {@link LanguageDefinition} or | ||
* {@link LANGUAGE_UNDEFINED} if language doesn't have new-style definitions. | ||
* We use a sentinel value instead of undefined so that we can distinguish | ||
* between a situation where we haven't yet checked whether a language has a | ||
* new-style query definition and a situation where we've checked and found | ||
* that it doesn't. The former case is represented by `undefined` (due to the | ||
* semantics of {@link Map.get}), while the latter is represented by the | ||
* sentinel value. | ||
*/ | ||
private languageDefinitions: Map< | ||
string, | ||
LanguageDefinition | typeof LANGUAGE_UNDEFINED | ||
> = new Map(); | ||
|
||
constructor(private treeSitter: TreeSitter) {} | ||
|
||
/** | ||
* Get a language definition for the given language id, if the language | ||
* has a new-style query definition, or return undefined if the language doesn't | ||
* | ||
* @param languageId The language id for which to get a language definition | ||
* @returns A language definition for the given language id, or undefined if | ||
* the given language id doesn't have a new-style query definition | ||
*/ | ||
get(languageId: string): LanguageDefinition | undefined { | ||
let definition = this.languageDefinitions.get(languageId); | ||
|
||
if (definition == null) { | ||
definition = | ||
LanguageDefinition.create(this.treeSitter, languageId as LanguageId) ?? | ||
LANGUAGE_UNDEFINED; | ||
|
||
this.languageDefinitions.set(languageId, definition); | ||
} | ||
|
||
return definition === LANGUAGE_UNDEFINED ? undefined : definition; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
141 changes: 141 additions & 0 deletions
141
...es/cursorless-engine/src/processTargets/modifiers/scopeHandlers/TreeSitterScopeHandler.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,141 @@ | ||
import { | ||
Direction, | ||
Position, | ||
ScopeType, | ||
SimpleScopeType, | ||
TextDocument, | ||
TextEditor, | ||
} from "@cursorless/common"; | ||
|
||
import { Point, Query, QueryMatch } from "web-tree-sitter"; | ||
import { TreeSitter } from "../../.."; | ||
import { getNodeRange } from "../../../util/nodeSelectors"; | ||
import ScopeTypeTarget from "../../targets/ScopeTypeTarget"; | ||
import BaseScopeHandler from "./BaseScopeHandler"; | ||
import { compareTargetScopes } from "./compareTargetScopes"; | ||
import { TargetScope } from "./scope.types"; | ||
import { ScopeIteratorRequirements } from "./scopeHandler.types"; | ||
|
||
/** | ||
* Handles scopes that are implemented using tree-sitter. | ||
*/ | ||
export class TreeSitterScopeHandler extends BaseScopeHandler { | ||
protected isHierarchical: boolean = true; | ||
|
||
constructor( | ||
private treeSitter: TreeSitter, | ||
private query: Query, | ||
public scopeType: SimpleScopeType, | ||
) { | ||
super(); | ||
} | ||
|
||
public get iterationScopeType(): ScopeType { | ||
throw Error("Not implemented"); | ||
} | ||
|
||
*generateScopeCandidates( | ||
editor: TextEditor, | ||
position: Position, | ||
direction: Direction, | ||
hints: ScopeIteratorRequirements, | ||
): Iterable<TargetScope> { | ||
const { document } = editor; | ||
|
||
/** Narrow the range within which tree-sitter searches, for performance */ | ||
const { start, end } = getQueryRange(document, position, direction, hints); | ||
|
||
yield* this.query | ||
.matches( | ||
this.treeSitter.getTree(document).rootNode, | ||
positionToPoint(start), | ||
positionToPoint(end), | ||
) | ||
.filter(({ captures }) => | ||
captures.some((capture) => capture.name === this.scopeType.type), | ||
) | ||
.map((match) => this.matchToScope(editor, match)) | ||
.sort((a, b) => compareTargetScopes(direction, position, a, b)); | ||
} | ||
|
||
private matchToScope(editor: TextEditor, match: QueryMatch): TargetScope { | ||
const contentRange = getNodeRange( | ||
match.captures.find((capture) => capture.name === this.scopeType.type)! | ||
.node, | ||
); | ||
|
||
return { | ||
editor, | ||
// FIXME: Actually get domain | ||
domain: contentRange, | ||
getTarget: (isReversed) => | ||
new ScopeTypeTarget({ | ||
scopeTypeType: this.scopeType.type, | ||
editor, | ||
isReversed, | ||
contentRange, | ||
// FIXME: Actually get removalRange | ||
removalRange: contentRange, | ||
// FIXME: Other fields here | ||
}), | ||
}; | ||
} | ||
} | ||
|
||
/** | ||
* Constructs a range to pass to {@link Query.matches} to find scopes. Note | ||
* that {@link Query.matches} will only return scopes that have non-empty | ||
* intersection with this range. Also note that the base | ||
* {@link BaseScopeHandler.generateScopes} will filter out any extra scopes | ||
* that we yield, so we don't need to be totally precise. | ||
* | ||
* @returns Range to pass to {@link Query.matches} | ||
*/ | ||
function getQueryRange( | ||
document: TextDocument, | ||
position: Position, | ||
direction: Direction, | ||
{ containment, distalPosition }: ScopeIteratorRequirements, | ||
) { | ||
const offset = document.offsetAt(position); | ||
const distalOffset = | ||
distalPosition == null ? null : document.offsetAt(distalPosition); | ||
|
||
if (containment === "required") { | ||
// If containment is required, we smear the position left and right by one | ||
// character so that we have a non-empty intersection with any scope that | ||
// touches position | ||
return { | ||
start: document.positionAt(offset - 1), | ||
end: document.positionAt(offset + 1), | ||
}; | ||
} | ||
|
||
// If containment is disallowed, we can shift the position forward by a character to avoid | ||
// matching scopes that touch position. Otherwise, we shift the position backward by a | ||
// character to ensure we get scopes that touch position. | ||
const proximalShift = containment === "disallowed" ? 1 : -1; | ||
|
||
// FIXME: Don't go all the way to end of document when there is no distalPosition? | ||
// Seems wasteful to query all the way to end of document for something like "next funk" | ||
// Might be better to start smaller and exponentially grow | ||
return direction === "forward" | ||
? { | ||
start: document.positionAt(offset + proximalShift), | ||
end: | ||
distalOffset == null | ||
? document.range.end | ||
: document.positionAt(distalOffset + 1), | ||
} | ||
: { | ||
start: | ||
distalOffset == null | ||
? document.range.start | ||
: document.positionAt(distalOffset - 1), | ||
end: document.positionAt(offset - proximalShift), | ||
}; | ||
} | ||
|
||
function positionToPoint(start: Position): Point | undefined { | ||
return { row: start.line, column: start.character }; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.