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

Further work on TypeScript strictNullChecks #1581

Merged
merged 56 commits into from
Mar 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
b2c0477
A cursor's RangeAndText type can be undefined
corasaurus-hex Mar 6, 2022
0e8cdd1
Account for SelectionAndText possibly being undefined
corasaurus-hex Mar 6, 2022
fca5cee
Fix types for getTokenCursor for Editable(Document|Model)
corasaurus-hex Mar 6, 2022
6a22a6a
Fix null checks for util.getDocument
corasaurus-hex Mar 6, 2022
a08278a
Rename document fetching functions as per @PEZ's request
corasaurus-hex Mar 6, 2022
28b9b4c
Rename active text editor fetch functions as per @PEZ's request
corasaurus-hex Mar 6, 2022
fb8c92f
Return undefined instead of null for provideOnTypeFormattingEdits
corasaurus-hex Mar 6, 2022
6952221
Fix some return types that can return undefined
corasaurus-hex Mar 6, 2022
eb3d264
Fix the types of various arrays
corasaurus-hex Mar 6, 2022
4ff30c6
Update a return type in cider
corasaurus-hex Mar 6, 2022
49f760a
Fix some return types and the variables they are assigned to
corasaurus-hex Mar 7, 2022
ab0ca87
Make certain arguments optional that are actually so
corasaurus-hex Mar 7, 2022
ba04613
Fix unit tests for new return values
corasaurus-hex Mar 7, 2022
e60870c
Fix linter error
corasaurus-hex Mar 7, 2022
87bc6b1
Add an entry in the CHANGELOG for PR #1581
corasaurus-hex Mar 7, 2022
e462a62
Apparently this confuses older typescript versions?
corasaurus-hex Mar 8, 2022
f44a2e5
Add an assertIsDefined function
corasaurus-hex Mar 8, 2022
db3d72c
Use assertions in the calling code for test runner results
corasaurus-hex Mar 8, 2022
0aef19e
Add/improve cider test result assertions.
corasaurus-hex Mar 8, 2022
e3a312f
Fix a couple of undefined checks in testRunner
corasaurus-hex Mar 8, 2022
8c3cd75
Add an isDefined function, so we don't have to do !isUndefinedOrNull
corasaurus-hex Mar 8, 2022
1f998eb
Fix an undefined when checking if a file is writable
corasaurus-hex Mar 8, 2022
6bed337
Set the defaults to an empty string or undefined as null is incorrect
corasaurus-hex Mar 8, 2022
6f947f2
When there are no pretty printing options, treat it as disabled
corasaurus-hex Mar 8, 2022
ebf598b
Make fetching color value more safe
corasaurus-hex Mar 8, 2022
ce80e01
Fixing more return types
corasaurus-hex Mar 8, 2022
69326a4
We expect and require there to be a project root
corasaurus-hex Mar 8, 2022
b668df2
Fix return types of these functions
corasaurus-hex Mar 8, 2022
bf9745f
Fix cases for which ns can be missing
corasaurus-hex Mar 8, 2022
da288fe
Fix types for editQueue
corasaurus-hex Mar 8, 2022
1baaed1
Assert that output window has a namespace, since it should have one
corasaurus-hex Mar 8, 2022
72c3398
Set token to undefined instead of null
corasaurus-hex Mar 8, 2022
2ddf9de
Handle undefined checks in repl-history
corasaurus-hex Mar 8, 2022
70c441b
model.getTokenCursor already throws an error so simplify this fn
corasaurus-hex Mar 13, 2022
8ca6e29
Simplify now that this does not return undefined
corasaurus-hex Mar 13, 2022
208e7eb
Use the built-in function for checking undefined
corasaurus-hex Mar 13, 2022
98da60f
Let's not muddy this with unused functions
corasaurus-hex Mar 13, 2022
586c4f4
Allow undefined for documents
corasaurus-hex Mar 13, 2022
76f0394
Restore old behavior because what to do here is not clear
corasaurus-hex Mar 13, 2022
90648ad
Refactor findLocalProjectRoot to have types
corasaurus-hex Mar 13, 2022
fbec889
Improve getting the color value to be better for types
corasaurus-hex Mar 13, 2022
a0e494c
Restore old behavior
corasaurus-hex Mar 13, 2022
6a28b9a
Restore old behavior since we're just satisfying the compiler
corasaurus-hex Mar 13, 2022
a470f35
Restore original behavior
corasaurus-hex Mar 13, 2022
2172d8b
Fix types to match reality
corasaurus-hex Mar 13, 2022
deae353
Restore old types as vscode requires these
corasaurus-hex Mar 13, 2022
03dad0a
Formalize the type for Completions
corasaurus-hex Mar 13, 2022
114724e
Assert window has an active text editor
corasaurus-hex Mar 13, 2022
2469257
Allow another undefined argument
corasaurus-hex Mar 13, 2022
9a84049
Add type assertions within a very long const
corasaurus-hex Mar 13, 2022
38ec4f3
Handle when some values are undefined
corasaurus-hex Mar 13, 2022
01eeb88
Handle when pretty printing options are undefined
corasaurus-hex Mar 13, 2022
f1ff9db
Add type for document to make it easier to type check
corasaurus-hex Mar 13, 2022
4c02278
disable additional eslint rule for these type assertions
corasaurus-hex Mar 13, 2022
0168a98
Update the changelog to reflect changes
corasaurus-hex Mar 13, 2022
3e84015
Merge branch 'dev' into cora/further-ts-null-checks
PEZ Mar 17, 2022
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
Changes to Calva.

## [Unreleased]
- Maintenance: [Update more TypeScript code to be compatible with strictNullChecks.](https://github.com/BetterThanTomorrow/calva/pull/1581)

## [2.0.254] - 2022-03-16
- [Add commands for starting and stopping clojure-lsp](https://github.com/BetterThanTomorrow/calva/pull/1592)
Expand Down
2 changes: 1 addition & 1 deletion src/analytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export default class Analytics {
);
}

private userID(): string {
private userID(): string | undefined {
const KEY = 'userLogID';
if (this.store.get(KEY) == undefined) {
const newID = uuid.uuid();
Expand Down
14 changes: 7 additions & 7 deletions src/calva-fmt/src/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
getIndent,
getDocumentOffset,
MirroredDocument,
mustGetDocument,
getDocument,
} from '../../doc-mirror/index';
import {
formatTextAtRange,
Expand All @@ -21,10 +21,10 @@ export async function indentPosition(
position: vscode.Position,
document: vscode.TextDocument
) {
const editor = util.mustGetActiveTextEditor();
const editor = util.getActiveTextEditor();
const pos = new vscode.Position(position.line, 0);
const indent = getIndent(
mustGetDocument(document).model.lineInputModel,
getDocument(document).model.lineInputModel,
getDocumentOffset(document, position),
await config.getConfig()
);
Expand Down Expand Up @@ -54,9 +54,9 @@ export async function indentPosition(
export async function formatRangeEdits(
document: vscode.TextDocument,
range: vscode.Range
): Promise<vscode.TextEdit[]> {
): Promise<vscode.TextEdit[] | undefined> {
const text: string = document.getText(range);
const mirroredDoc: MirroredDocument = mustGetDocument(document);
const mirroredDoc: MirroredDocument = getDocument(document);
const startIndex = document.offsetAt(range.start);
const endIndex = document.offsetAt(range.end);
const cursor = mirroredDoc.getTokenCursor(startIndex);
Expand Down Expand Up @@ -91,7 +91,7 @@ export async function formatPositionInfo(
const doc: vscode.TextDocument = editor.document;
const pos: vscode.Position = editor.selection.active;
const index = doc.offsetAt(pos);
const mirroredDoc: MirroredDocument = mustGetDocument(doc);
const mirroredDoc: MirroredDocument = getDocument(doc);
const cursor = mirroredDoc.getTokenCursor(index);
const formatDepth = extraConfig['format-depth']
? extraConfig['format-depth']
Expand Down Expand Up @@ -240,7 +240,7 @@ async function _formatRange(
allText: string,
range: number[],
eol: string
): Promise<string> {
): Promise<string | undefined> {
const d = {
'range-text': rangeText,
'all-text': allText,
Expand Down
15 changes: 7 additions & 8 deletions src/calva-fmt/src/providers/ontype_formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class FormatOnTypeEditProvider
_position: vscode.Position,
ch: string,
_options
): Promise<vscode.TextEdit[]> {
): Promise<vscode.TextEdit[] | undefined> {
let keyMap = vscode.workspace
.getConfiguration()
.get('calva.paredit.defaultKeyMap');
Expand All @@ -24,21 +24,20 @@ export class FormatOnTypeEditProvider
keyMap === 'strict' &&
getConfig().strictPreventUnmatchedClosingBracket
) {
const mDoc: EditableDocument =
docMirror.mustGetDocument(document);
const mDoc: EditableDocument = docMirror.getDocument(document);
const tokenCursor = mDoc.getTokenCursor();
if (tokenCursor.withinComment()) {
return null;
return undefined;
}
return paredit.backspace(mDoc).then((fulfilled) => {
paredit.close(mDoc, ch);
return null;
return undefined;
});
} else {
return null;
return undefined;
}
}
const editor = util.mustGetActiveTextEditor();
const editor = util.getActiveTextEditor();

const pos = editor.selection.active;
if (
Expand All @@ -61,6 +60,6 @@ export class FormatOnTypeEditProvider
}
}

return null;
return undefined;
}
}
12 changes: 6 additions & 6 deletions src/clojuredocs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export function printTextToRichCommentCommand(args: { [x: string]: string }) {

function printTextToRichComment(text: string, position?: number) {
const doc = util.getDocument({});
const mirrorDoc = docMirror.mustGetDocument(doc);
const mirrorDoc = docMirror.getDocument(doc);
paredit.addRichComment(
mirrorDoc,
position ? position : mirrorDoc.selection.active,
Expand All @@ -74,10 +74,10 @@ function printTextToRichComment(text: string, position?: number) {
export async function getExamplesHover(
document: vscode.TextDocument,
position: vscode.Position
): Promise<vscode.MarkdownString> {
): Promise<vscode.MarkdownString | undefined> {
const docs = await clojureDocsLookup(document, position);
if (!docs) {
return null;
return undefined;
}
return getHoverForDocs(
docs,
Expand Down Expand Up @@ -183,7 +183,7 @@ async function clojureDocsLookup(
p?: vscode.Position
): Promise<DocsEntry> {
const doc = d ? d : util.getDocument({});
const position = p ? p : util.mustGetActiveTextEditor().selection.active;
const position = p ? p : util.getActiveTextEditor().selection.active;
const symbol = util.getWordAtPosition(doc, position);
const ns = namespace.getNamespace(doc);
const session = replSession.getSession(util.getFileType(doc));
Expand Down Expand Up @@ -237,7 +237,7 @@ function rawDocs2DocsEntry(
docsResult: any,
symbol: string,
ns: string
): DocsEntry {
): DocsEntry | undefined {
const docs = docsResult.clojuredocs;
if (docs) {
return {
Expand All @@ -262,6 +262,6 @@ function rawDocs2DocsEntry(
};
} else {
// console.log(`No results for ${ns}/${symbol} from ${docsResult.fromServer}`);
return null;
return undefined;
}
}
18 changes: 9 additions & 9 deletions src/connector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ type connectFn = (
session: NReplSession,
name: string,
checkSuccess: checkConnectedFn
) => Promise<boolean>;
) => Promise<boolean | undefined>;

async function evalConnectCode(
newCljsSession: NReplSession,
Expand All @@ -249,8 +249,8 @@ async function evalConnectCode(
errorProcessors: processOutputFn[] = []
): Promise<boolean> {
const chan = state.connectionLogChannel();
const err = [],
out = [],
const err: string[] = [],
out: string[] = [],
result = newCljsSession.eval(code, 'user', {
stdout: (x) => {
out.push(util.stripAnsi(x));
Expand Down Expand Up @@ -290,15 +290,17 @@ export interface ReplType {

let translatedReplType: ReplType;

async function figwheelOrShadowBuilds(cljsTypeName: string): Promise<string[]> {
async function figwheelOrShadowBuilds(
cljsTypeName: string
): Promise<string[] | undefined> {
if (cljsTypeName.includes('Figwheel Main')) {
return await getFigwheelMainBuilds();
} else if (cljsTypeName.includes('shadow-cljs')) {
return await projectTypes.shadowBuilds();
}
}

function updateInitCode(build: string, initCode): string {
function updateInitCode(build: string, initCode): string | undefined {
if (build && typeof initCode === 'object') {
if (['node-repl', 'browser-repl'].includes(build)) {
return initCode.repl.replace('%REPL%', build);
Expand All @@ -308,7 +310,7 @@ function updateInitCode(build: string, initCode): string {
} else if (build && typeof initCode === 'string') {
return initCode.replace('%BUILD%', `"${build}"`);
}
return null;
return undefined;
}

function createCLJSReplType(
Expand Down Expand Up @@ -836,9 +838,7 @@ export default {
}
setStateValue('cljc', newSession);
if (
outputWindow.isResultsDoc(
util.mustGetActiveTextEditor().document
)
outputWindow.isResultsDoc(util.getActiveTextEditor().document)
) {
outputWindow.setSession(newSession, undefined);
replSession.updateReplSessionType();
Expand Down
9 changes: 8 additions & 1 deletion src/cursor-doc/model.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Scanner, Token, ScannerState } from './clojure-lexer';
import { LispTokenCursor } from './token-cursor';
import { deepEqual as equal } from '../util/object';
import { isUndefined } from 'lodash';

let scanner: Scanner;

Expand Down Expand Up @@ -291,7 +292,7 @@ export class LineInputModel implements EditableModel {
const st = this.getRowCol(Math.min(start, end));
const en = this.getRowCol(Math.max(start, end));

const lines = [];
const lines: string[] = [];
if (st[0] == en[0]) {
lines[0] = this.lines[st[0]].text.substring(st[1], en[1]);
} else {
Expand Down Expand Up @@ -581,6 +582,8 @@ export class LineInputModel implements EditableModel {
lastIndex = i;
}
return new LispTokenCursor(this, row, line.tokens.length - 1);
} else {
throw new Error('Unable to get token cursor for LineInputModel!');
}
}
}
Expand Down Expand Up @@ -609,6 +612,10 @@ export class StringDocument implements EditableDocument {
selectionStack: ModelEditSelection[] = [];

getTokenCursor(offset?: number, previous?: boolean): LispTokenCursor {
if (isUndefined(offset)) {
throw new Error('Expected a cursor for StringDocument!');
}

return this.model.getTokenCursor(offset);
}

Expand Down
4 changes: 2 additions & 2 deletions src/cursor-doc/paredit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -807,10 +807,10 @@ export function backspace(
start: number = doc.selection.anchor,
end: number = doc.selection.active
): Thenable<boolean> {
const cursor = doc.getTokenCursor(start);
if (start != end) {
return doc.backspace();
} else {
const cursor = doc.getTokenCursor(start);
const nextToken = cursor.getToken();
const p = start;
const prevToken =
Expand Down Expand Up @@ -857,10 +857,10 @@ export function deleteForward(
start: number = doc.selectionLeft,
end: number = doc.selectionRight
) {
const cursor = doc.getTokenCursor(start);
if (start != end) {
void doc.delete();
} else {
const cursor = doc.getTokenCursor(start);
const prevToken = cursor.getPrevToken();
const nextToken = cursor.getToken();
const p = start;
Expand Down
2 changes: 1 addition & 1 deletion src/custom-snippets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ async function evaluateCustomCodeSnippetCommand(codeOrKey?: string) {
}

async function evaluateCodeOrKey(codeOrKey?: string) {
const editor = util.mustGetActiveTextEditor();
const editor = util.getActiveTextEditor();
const currentLine = editor.selection.active.line;
const currentColumn = editor.selection.active.character;
const currentFilename = editor.document.fileName;
Expand Down
2 changes: 1 addition & 1 deletion src/debugger/calva-debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ class CalvaDebugSession extends LoggingDebugSession {
new Position(positionLine, positionColumn)
);
const tokenCursor = docMirror
.mustGetDocument(document)
.getDocument(document)
.getTokenCursor(offset);

try {
Expand Down
4 changes: 2 additions & 2 deletions src/debugger/decorations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ function triggerUpdateAndRenderDecorations() {
timeout = undefined;
}
if (enabled) {
const editor = util.getActiveTextEditor();
const editor = util.tryToGetActiveTextEditor();
if (editor) {
timeout = setTimeout(() => {
const cljSession = replSession.getSession('clj');
Expand All @@ -166,7 +166,7 @@ function activate() {
});

vscode.workspace.onDidChangeTextDocument((event) => {
const activeEditor = util.getActiveTextEditor();
const activeEditor = util.tryToGetActiveTextEditor();
if (
activeEditor &&
event.document === activeEditor.document &&
Expand Down
Loading