Skip to content
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

Make arguments to engine optional #2477

Merged
merged 25 commits into from
Jul 12, 2024
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions packages/common/src/ide/types/LanguageDefinitionsProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Disposable } from "@cursorless/common";

export interface LanguageDefinitionsProvider {
/**
* Listen for changes to language definitions
*/
onChanges(listener: () => void): Disposable;

/**
* Read a query definition. The query name is the name of one of our `.scm` files.
*/
readQuery(name: string): Promise<string | undefined>;
AndreasArvidsson marked this conversation as resolved.
Show resolved Hide resolved
}
1 change: 1 addition & 0 deletions packages/common/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export * from "./ide/types/QuickPickOptions";
export * from "./ide/types/events.types";
export * from "./ide/types/Paths";
export * from "./ide/types/CommandHistoryStorage";
export * from "./ide/types/LanguageDefinitionsProvider";
export * from "./ide/types/FileSystem.types";
export * from "./types/RangeExpansionBehavior";
export * from "./types/InputBoxOptions";
Expand Down
2 changes: 1 addition & 1 deletion packages/cursorless-engine/src/CommandHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export class CommandHistory implements CommandRunnerDecorator {
constructor(
private ide: IDE,
private storage: CommandHistoryStorage,
private commandServerApi: CommandServerApi | null,
private commandServerApi: CommandServerApi | undefined,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is no longer ever undefined right?

Suggested change
private commandServerApi: CommandServerApi | undefined,
private commandServerApi: CommandServerApi,

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately not. This is constructed in the extension file and does not get the disabled default implementation from the engine

) {}

wrapCommandRunner(
Expand Down
85 changes: 6 additions & 79 deletions packages/cursorless-engine/src/core/Debug.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import { Disposable, TextEditorSelectionChangeEvent } from "@cursorless/common";
import type { SyntaxNode, TreeCursor } from "web-tree-sitter";
import { ide } from "../singletons/ide.singleton";
import { TreeSitter } from "../typings/TreeSitter";
import type { Disposable, IDE } from "@cursorless/common";

/**
* Debug logger
Expand All @@ -11,14 +8,13 @@ export class Debug {
private disposableSelection?: Disposable;
active: boolean;
AndreasArvidsson marked this conversation as resolved.
Show resolved Hide resolved

constructor(private treeSitter: TreeSitter) {
ide().disposeOnExit(this);
constructor(private ide: IDE) {
ide.disposeOnExit(this);

this.evaluateSetting = this.evaluateSetting.bind(this);
this.logBranchTypes = this.logBranchTypes.bind(this);
this.active = true;

switch (ide().runMode) {
switch (ide.runMode) {
// Development mode. Always enable.
case "development":
this.enableDebugLog();
Expand All @@ -31,7 +27,7 @@ export class Debug {
case "production":
this.evaluateSetting();
this.disposableConfiguration =
ide().configuration.onDidChangeConfiguration(this.evaluateSetting);
ide.configuration.onDidChangeConfiguration(this.evaluateSetting);
break;
}
}
Expand All @@ -53,9 +49,6 @@ export class Debug {

private enableDebugLog() {
this.active = true;
this.disposableSelection = ide().onDidChangeTextEditorSelection(
this.logBranchTypes,
);
}

private disableDebugLog() {
Expand All @@ -67,77 +60,11 @@ export class Debug {
}

private evaluateSetting() {
const debugEnabled = ide().configuration.getOwnConfiguration("debug");
const debugEnabled = this.ide.configuration.getOwnConfiguration("debug");
if (debugEnabled) {
this.enableDebugLog();
} else {
this.disableDebugLog();
}
}

private logBranchTypes(event: TextEditorSelectionChangeEvent) {
let node: SyntaxNode;
try {
node = this.treeSitter.getNodeAtLocation(
ide().activeTextEditor!.document,
event.selections[0],
);
} catch (error) {
return;
}

const ancestors: SyntaxNode[] = [node];
while (node.parent != null) {
ancestors.unshift(node.parent);
node = node.parent;
}

const cursor = node.tree.walk();
this.printCursorLocationInfo(ancestors, cursor, 0);
}

private printCursorLocationInfo(
nodes: SyntaxNode[],
cursor: TreeCursor,
index: number,
) {
const field = cursor.currentFieldName;
const fieldText = field != null ? `${field}: ` : "";
const indent = " ".repeat(index);
const nodeIsLast = index === nodes.length - 1;
const { nodeIsNamed } = cursor;
let text = `${indent}${fieldText}`;

if (nodeIsNamed) {
text += `(${cursor.nodeType}`;
if (nodeIsLast) {
text += ")";
}
} else {
text += `"${cursor.nodeType}"`;
}

console.log(text);

if (
!nodeIsLast &&
this.cursorGoToChildWithId(cursor, nodes[index + 1].id)
) {
this.printCursorLocationInfo(nodes, cursor, index + 1);
}

if (nodeIsNamed && !nodeIsLast) {
console.log(`${indent})`);
}
}

private cursorGoToChildWithId(cursor: TreeCursor, id: number): boolean {
cursor.gotoFirstChild();
while (cursor.currentNode.id !== id) {
if (!cursor.gotoNextSibling()) {
return false;
}
}
return true;
}
}
4 changes: 2 additions & 2 deletions packages/cursorless-engine/src/core/HatTokenMapImpl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export class HatTokenMapImpl implements HatTokenMap {
rangeUpdater: RangeUpdater,
private debug: Debug,
hats: Hats,
private commandServerApi: CommandServerApi | null,
private commandServerApi: CommandServerApi,
) {
ide().disposeOnExit(this);
this.activeMap = new IndividualHatMap(rangeUpdater);
Expand Down Expand Up @@ -130,7 +130,7 @@ export class HatTokenMapImpl implements HatTokenMap {
}

private async maybeTakePrePhraseSnapshot() {
const phraseStartSignal = this.commandServerApi?.signals?.prePhrase;
const phraseStartSignal = this.commandServerApi.signals.prePhrase;

if (phraseStartSignal != null) {
const newSignalVersion = await phraseStartSignal.getVersion();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class CommandRunnerImpl implements CommandRunner {
private noAutomaticTokenExpansion: boolean | undefined;

constructor(
private commandServerApi: CommandServerApi | null,
private commandServerApi: CommandServerApi,
private debug: Debug,
private storedTargets: StoredTargetMap,
private pipelineRunner: TargetPipelineRunner,
Expand Down
4 changes: 2 additions & 2 deletions packages/cursorless-engine/src/core/getCommandFallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ import {
import type { ActionReturnValue } from "../actions/actions.types";

export async function getCommandFallback(
commandServerApi: CommandServerApi | null,
commandServerApi: CommandServerApi,
runAction: (actionDescriptor: ActionDescriptor) => Promise<ActionReturnValue>,
command: CommandComplete,
): Promise<Fallback | null> {
const focusedElementType = await commandServerApi?.getFocusedElementType();
const focusedElementType = await commandServerApi.getFocusedElementType();

if (focusedElementType == null || focusedElementType === "textEditor") {
return null;
Expand Down
75 changes: 46 additions & 29 deletions packages/cursorless-engine/src/cursorlessEngine.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import {
Command,
CommandServerApi,
FileSystem,
Hats,
IDE,
ScopeProvider,
ensureCommandShape,
type LanguageDefinitionsProvider,
} from "@cursorless/common";
import { KeyboardTargetUpdater } from "./KeyboardTargetUpdater";
import {
Expand All @@ -17,10 +17,17 @@ import { HatTokenMapImpl } from "./core/HatTokenMapImpl";
import type { Snippets } from "./core/Snippets";
import { StoredTargetMap } from "./core/StoredTargets";
import { RangeUpdater } from "./core/updateSelections/RangeUpdater";
import { DisabledCommandServerApi } from "./disabledComponents/DisabledCommandServerApi";
import { DisabledHatTokenMap } from "./disabledComponents/DisabledHatTokenMap";
import { DisabledLanguageDefinitions } from "./disabledComponents/DisabledLanguageDefinitions";
import { DisabledSnippets } from "./disabledComponents/DisabledSnippets";
import { DisabledTalonSpokenForms } from "./disabledComponents/DisabledTalonSpokenForms";
import { DisabledTreeSitter } from "./disabledComponents/DisabledTreeSitter";
import { CustomSpokenFormGeneratorImpl } from "./generateSpokenForm/CustomSpokenFormGeneratorImpl";
import { LanguageDefinitions } from "./languages/LanguageDefinitions";
import {
LanguageDefinitions,
LanguageDefinitionsImpl,
} from "./languages/LanguageDefinitions";
import { ModifierStageFactoryImpl } from "./processTargets/ModifierStageFactoryImpl";
import { ScopeHandlerFactoryImpl } from "./processTargets/modifiers/scopeHandlers";
import { runCommand } from "./runCommand";
Expand All @@ -34,40 +41,51 @@ import { type TalonSpokenForms } from "./scopeProviders/TalonSpokenForms";
import { injectIde } from "./singletons/ide.singleton";
import { TreeSitter } from "./typings/TreeSitter";

export async function createCursorlessEngine(
treeSitter: TreeSitter,
ide: IDE,
hats: Hats,
commandServerApi: CommandServerApi | null,
fileSystem: FileSystem,
talonSpokenForms: TalonSpokenForms | undefined,
snippets: Snippets = new DisabledSnippets(),
): Promise<CursorlessEngine> {
injectIde(ide);
interface Props {
ide: IDE;
hats?: Hats;
languageDefinitionsProvider?: LanguageDefinitionsProvider;
treeSitter?: TreeSitter;
commandServerApi?: CommandServerApi;
talonSpokenForms?: TalonSpokenForms;
snippets?: Snippets;
}

const debug = new Debug(treeSitter);
export async function createCursorlessEngine({
ide,
hats,
languageDefinitionsProvider,
treeSitter = new DisabledTreeSitter(),
commandServerApi = new DisabledCommandServerApi(),
talonSpokenForms = new DisabledTalonSpokenForms(),
snippets = new DisabledSnippets(),
}: Props): Promise<CursorlessEngine> {
injectIde(ide);

const debug = new Debug(ide);
const rangeUpdater = new RangeUpdater();

const hatTokenMap = new HatTokenMapImpl(
rangeUpdater,
debug,
hats,
commandServerApi,
);
hatTokenMap.allocateHats();

const storedTargets = new StoredTargetMap();

const keyboardTargetUpdater = new KeyboardTargetUpdater(storedTargets);

const languageDefinitions = new LanguageDefinitions(fileSystem, treeSitter);
await languageDefinitions.init();

const customSpokenFormGenerator = new CustomSpokenFormGeneratorImpl(
talonSpokenForms ?? new DisabledTalonSpokenForms(),
talonSpokenForms,
);

const hatTokenMap =
hats != null
? new HatTokenMapImpl(rangeUpdater, debug, hats, commandServerApi)
: new DisabledHatTokenMap();
void hatTokenMap.allocateHats();

const languageDefinitions =
languageDefinitionsProvider != null
? new LanguageDefinitionsImpl(
ide,
languageDefinitionsProvider,
treeSitter,
)
: new DisabledLanguageDefinitions();
await languageDefinitions.init();

ide.disposeOnExit(
rangeUpdater,
languageDefinitions,
Expand All @@ -77,7 +95,6 @@ export async function createCursorlessEngine(
);

const commandRunnerDecorators: CommandRunnerDecorator[] = [];

let previousCommand: Command | undefined = undefined;

const runCommandClosure = (command: Command) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { CommandServerApi } from "@cursorless/common";

export class DisabledCommandServerApi implements CommandServerApi {
getFocusedElementType() {
return Promise.resolve(undefined);
}

readonly signals = {
prePhrase: {
getVersion() {
return Promise.resolve(null);
},
},
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { HatTokenMap } from "@cursorless/common";

export class DisabledHatTokenMap implements HatTokenMap {
async allocateHats() {
// Do nothing
}

async getReadableMap() {
return {
getEntries() {
return [];
},
getToken() {
throw new Error("Hat map is disabled");
},
};
}

dispose() {
// Do nothing
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { TextDocument, Range, Listener } from "@cursorless/common";
import type { SyntaxNode } from "web-tree-sitter";
import type { LanguageDefinition } from "../languages/LanguageDefinition";
import type { LanguageDefinitions } from "../languages/LanguageDefinitions";

export class DisabledLanguageDefinitions implements LanguageDefinitions {
init(): Promise<void> {
return Promise.resolve();
}

onDidChangeDefinition(_listener: Listener) {
return { dispose: () => {} };
}

loadLanguage(_languageId: string): Promise<void> {
return Promise.resolve();
}

get(_languageId: string): LanguageDefinition | undefined {
return undefined;
}

getNodeAtLocation(
_document: TextDocument,
_range: Range,
): SyntaxNode | undefined {
return undefined;
}

dispose(): void {
// Do nothing
}
}
Loading
Loading