Skip to content

Commit

Permalink
Refactoring: Strict TypeScript Fix #1208 (#1209)
Browse files Browse the repository at this point in the history
* Enable strict ckecks in tsconfig.json

* Refactoring for strict TS

* strict-ts lineCache.ts

* Strict ts linterConfig.ts

* strict ts preview.ts and some refactoring

* Strict ts languageService.ts and use ES6 imports

* Add catchAsError utility

* Strict ts completions.ts

* Strict ts rstudioapi.ts

* Strict ts rTerminal.ts

* Strict ts selection.ts

* Begin work on strict ts session.ts

* Strict ts tasks.ts

* Strict ts workspaceViewer.ts

* Help related code

* Strict ts rmarkdown

* Strict ts liveShare

* Fix some propagated undefined

* Strict ts tests, add types for glob

* Strict ts httpgd

* Strict ts session.ts

* Finish up strict ts

* Fix lint

* Small changes

* Small fix

* Adjust wrong config default values

Co-authored-by: ManuelHentschel <53863351+ManuelHentschel@users.noreply.github.com>
  • Loading branch information
nx10 and ManuelHentschel authored Oct 8, 2022
1 parent ad20fdc commit 9c9d266
Show file tree
Hide file tree
Showing 39 changed files with 766 additions and 504 deletions.
10 changes: 3 additions & 7 deletions html/help/script.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,3 @@
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/no-explicit-any */

declare function acquireVsCodeApi(): VsCode;

const vscode = acquireVsCodeApi();
Expand All @@ -20,8 +14,10 @@ window.onmousedown = (ev) => {


// handle requests from vscode ui
window.addEventListener('message', (ev) => {
window.addEventListener('message', (ev: MessageEvent) => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const message = ev.data;
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if(message.command === 'getScrollY'){
vscode.postMessage({
message: 'getScrollY',
Expand Down
7 changes: 5 additions & 2 deletions html/help/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
"DOM"
],
"sourceMap": false,
"strictNullChecks": true,
"rootDir": "."
"rootDir": ".",
"strict": true,
"noImplicitAny": true,
"noImplicitThis": true,
"noFallthroughCasesInSwitch": true
}
}
3 changes: 1 addition & 2 deletions html/httpgd/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ const largePlotDiv = document.querySelector('#largePlot') as HTMLDivElement;
const largeSvg = largePlotDiv.querySelector('svg') as SVGElement;
const cssLink = document.querySelector('link.overwrites') as HTMLLinkElement;
const smallPlotDiv = document.querySelector('#smallPlots') as HTMLDivElement;
const placeholderDiv = document.querySelector('#placeholder') as HTMLDivElement;


function getSmallPlots(): HTMLAnchorElement[] {
Expand Down Expand Up @@ -172,7 +171,7 @@ function togglePreviewPlotLayout(newStyle: PreviewPlotLayout): void {
smallPlotDiv.classList.add(newStyle);
}

function toggleFullWindowMode(useFullWindow): void {
function toggleFullWindowMode(useFullWindow: boolean): void {
isFullWindow = useFullWindow;
if(useFullWindow){
document.body.classList.add('fullWindow');
Expand Down
7 changes: 5 additions & 2 deletions html/httpgd/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
"DOM"
],
"sourceMap": false,
"strictNullChecks": true,
"rootDir": "."
"rootDir": ".",
"strict": true,
"noImplicitAny": true,
"noImplicitThis": true,
"noFallthroughCasesInSwitch": true
}
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -1915,6 +1915,7 @@
"@types/ejs": "^3.0.6",
"@types/express": "^4.17.12",
"@types/fs-extra": "^9.0.11",
"@types/glob": "^8.0.0",
"@types/js-yaml": "^4.0.2",
"@types/mocha": "^8.2.2",
"@types/node": "^16.11.7",
Expand Down
22 changes: 11 additions & 11 deletions src/completions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const roxygenTagCompletionItems = [


export class HoverProvider implements vscode.HoverProvider {
provideHover(document: vscode.TextDocument, position: vscode.Position): vscode.Hover {
provideHover(document: vscode.TextDocument, position: vscode.Position): vscode.Hover | null {
if(!session.workspaceData?.globalenv){
return null;
}
Expand All @@ -56,7 +56,7 @@ export class HoverProvider implements vscode.HoverProvider {
}

export class HelpLinkHoverProvider implements vscode.HoverProvider {
async provideHover(document: vscode.TextDocument, position: vscode.Position): Promise<vscode.Hover> {
async provideHover(document: vscode.TextDocument, position: vscode.Position): Promise<vscode.Hover | null> {
if(!config().get<boolean>('helpPanel.enableHoverLinks')){
return null;
}
Expand Down Expand Up @@ -114,7 +114,7 @@ export class LiveCompletionItemProvider implements vscode.CompletionItemProvider
token: vscode.CancellationToken,
completionContext: vscode.CompletionContext
): vscode.CompletionItem[] {
const items = [];
const items: vscode.CompletionItem[] = [];
if (token.isCancellationRequested || !session.workspaceData?.globalenv) {
return items;
}
Expand Down Expand Up @@ -148,7 +148,7 @@ export class LiveCompletionItemProvider implements vscode.CompletionItemProvider
const symbol = document.getText(symbolRange);
const doc = new vscode.MarkdownString('Element of `' + symbol + '`');
const obj = session.workspaceData.globalenv[symbol];
let names: string[];
let names: string[] | undefined;
if (obj !== undefined) {
if (completionContext.triggerCharacter === '$') {
names = obj.names;
Expand Down Expand Up @@ -187,14 +187,14 @@ function getCompletionItems(names: string[], kind: vscode.CompletionItemKind, de
});
}

function getBracketCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken) {
function getBracketCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): vscode.CompletionItem[] {
const items: vscode.CompletionItem[] = [];
let range = new vscode.Range(new vscode.Position(position.line, 0), position);
let range: vscode.Range | undefined = new vscode.Range(new vscode.Position(position.line, 0), position);
let expectOpenBrackets = 0;
let symbol: string;
let symbol: string | undefined = undefined;

while (range) {
if (token.isCancellationRequested) { return; }
if (token.isCancellationRequested) { return []; }
const text = document.getText(range);
for (let i = text.length - 1; i >= 0; i -= 1) {
const chr = text.charAt(i);
Expand All @@ -212,7 +212,7 @@ function getBracketCompletionItems(document: vscode.TextDocument, position: vsco
}
}
}
if (range?.start.line > 0) {
if (range?.start?.line !== undefined && range.start.line > 0) {
range = document.lineAt(range.start.line - 1).range; // check previous line
} else {
range = undefined;
Expand All @@ -229,10 +229,10 @@ function getBracketCompletionItems(document: vscode.TextDocument, position: vsco
return items;
}

function getPipelineCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken) {
function getPipelineCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): vscode.CompletionItem[] {
const items: vscode.CompletionItem[] = [];
const range = extendSelection(position.line, (x) => document.lineAt(x).text, document.lineCount);
let symbol: string;
let symbol: string | undefined = undefined;

for (let i = range.startLine; i <= range.endLine; i++) {
if (token.isCancellationRequested) {
Expand Down
17 changes: 6 additions & 11 deletions src/cppProperties.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
'use strict';

import { randomBytes } from 'crypto';
import * as fs from 'fs';
import * as path from 'path';
import { window } from 'vscode';
import { getRpath, getCurrentWorkspaceFolder, executeRCommand } from './util';
import { getRpath, getCurrentWorkspaceFolder, executeRCommand, createTempDir } from './util';
import { execSync } from 'child_process';
import { extensionContext } from './extension';

Expand Down Expand Up @@ -38,6 +37,9 @@ function platformChoose<A, B, C>(win32: A, darwin: B, other: C): A | B | C {
// See: https://code.visualstudio.com/docs/cpp/c-cpp-properties-schema-reference
async function generateCppPropertiesProc(workspaceFolder: string) {
const rPath = await getRpath();
if (!rPath) {
return;
}

// Collect information from running the compiler
const configureFile = platformChoose('configure.win', 'configure', 'configure');
Expand All @@ -64,10 +66,10 @@ async function generateCppPropertiesProc(workspaceFolder: string) {
const compileStdCpp = extractCompilerStd(compileOutputCpp);
const compileStdC = extractCompilerStd(compileOutputC);
const compileCall = extractCompilerCall(compileOutputCpp);
const compilerPath = await executeRCommand(`cat(Sys.which("${compileCall}"))`, workspaceFolder, (e: Error) => {
const compilerPath = compileCall ? await executeRCommand(`cat(Sys.which("${compileCall}"))`, workspaceFolder, (e: Error) => {
void window.showErrorMessage(e.message);
return '';
});
}) : '';

const intelliSensePlatform = platformChoose('windows', 'macos', 'linux');
const intelliSenseComp = compileCall ? (compileCall.includes('clang') ? 'clang' : 'gcc') : 'gcc';
Expand Down Expand Up @@ -175,13 +177,6 @@ function extractCompilerCall(compileOutput: string): string | undefined {
return m?.[1];
}

function createTempDir(root: string): string {
let tempDir: string;
while (fs.existsSync(tempDir = path.join(root, `___temp_${randomBytes(8).toString('hex')}`))) { /* Name clash */ }
fs.mkdirSync(tempDir);
return tempDir;
}

function collectCompilerOutput(rPath: string, workspaceFolder: string, testExtension: 'cpp' | 'c') {

const makevarsFiles = ['Makevars', 'Makevars.win', 'Makevars.ucrt'];
Expand Down
37 changes: 18 additions & 19 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const tmpDir = (): string => util.getDir(path.join(homeExtDir(), 'tmp'));
export let rWorkspace: workspaceViewer.WorkspaceDataProvider | undefined = undefined;
export let globalRHelp: rHelp.RHelp | undefined = undefined;
export let extensionContext: vscode.ExtensionContext;
export let enableSessionWatcher: boolean = undefined;
export let enableSessionWatcher: boolean | undefined = undefined;
export let globalHttpgdManager: httpgdViewer.HttpgdManager | undefined = undefined;
export let rmdPreviewManager: rmarkdown.RMarkdownPreviewManager | undefined = undefined;
export let rmdKnitManager: rmarkdown.RMarkdownKnitManager | undefined = undefined;
Expand Down Expand Up @@ -80,10 +80,10 @@ export async function activate(context: vscode.ExtensionContext): Promise<apiImp
'r.runSourcewithEcho': () => { void rTerminal.runSource(true); },

// rmd related
'r.knitRmd': () => { void rmdKnitManager.knitRmd(false, undefined); },
'r.knitRmdToPdf': () => { void rmdKnitManager.knitRmd(false, 'pdf_document'); },
'r.knitRmdToHtml': () => { void rmdKnitManager.knitRmd(false, 'html_document'); },
'r.knitRmdToAll': () => { void rmdKnitManager.knitRmd(false, 'all'); },
'r.knitRmd': () => { void rmdKnitManager?.knitRmd(false, undefined); },
'r.knitRmdToPdf': () => { void rmdKnitManager?.knitRmd(false, 'pdf_document'); },
'r.knitRmdToHtml': () => { void rmdKnitManager?.knitRmd(false, 'html_document'); },
'r.knitRmdToAll': () => { void rmdKnitManager?.knitRmd(false, 'all'); },
'r.selectCurrentChunk': rmarkdown.selectCurrentChunk,
'r.runCurrentChunk': rmarkdown.runCurrentChunk,
'r.runPreviousChunk': rmarkdown.runPreviousChunk,
Expand All @@ -97,15 +97,15 @@ export async function activate(context: vscode.ExtensionContext): Promise<apiImp
'r.runChunks': rTerminal.runChunksInTerm,

'r.rmarkdown.newDraft': () => rmarkdown.newDraft(),
'r.rmarkdown.setKnitDirectory': () => rmdKnitManager.setKnitDir(),
'r.rmarkdown.showPreviewToSide': () => rmdPreviewManager.previewRmd(vscode.ViewColumn.Beside),
'r.rmarkdown.showPreview': (uri: vscode.Uri) => rmdPreviewManager.previewRmd(vscode.ViewColumn.Active, uri),
'r.rmarkdown.preview.refresh': () => rmdPreviewManager.updatePreview(),
'r.rmarkdown.preview.openExternal': () => void rmdPreviewManager.openExternalBrowser(),
'r.rmarkdown.preview.showSource': () => rmdPreviewManager.showSource(),
'r.rmarkdown.preview.toggleStyle': () => rmdPreviewManager.toggleTheme(),
'r.rmarkdown.preview.enableAutoRefresh': () => rmdPreviewManager.enableAutoRefresh(),
'r.rmarkdown.preview.disableAutoRefresh': () => rmdPreviewManager.disableAutoRefresh(),
'r.rmarkdown.setKnitDirectory': () => rmdKnitManager?.setKnitDir(),
'r.rmarkdown.showPreviewToSide': () => rmdPreviewManager?.previewRmd(vscode.ViewColumn.Beside),
'r.rmarkdown.showPreview': (uri: vscode.Uri) => rmdPreviewManager?.previewRmd(vscode.ViewColumn.Active, uri),
'r.rmarkdown.preview.refresh': () => rmdPreviewManager?.updatePreview(),
'r.rmarkdown.preview.openExternal': () => void rmdPreviewManager?.openExternalBrowser(),
'r.rmarkdown.preview.showSource': () => rmdPreviewManager?.showSource(),
'r.rmarkdown.preview.toggleStyle': () => rmdPreviewManager?.toggleTheme(),
'r.rmarkdown.preview.enableAutoRefresh': () => rmdPreviewManager?.enableAutoRefresh(),
'r.rmarkdown.preview.disableAutoRefresh': () => rmdPreviewManager?.disableAutoRefresh(),

// file creation (under file submenu)
'r.rmarkdown.newFileDraft': () => rmarkdown.newDraft(),
Expand Down Expand Up @@ -133,8 +133,8 @@ export async function activate(context: vscode.ExtensionContext): Promise<apiImp

// workspace viewer
'r.workspaceViewer.refreshEntry': () => rWorkspace?.refresh(),
'r.workspaceViewer.view': (node: workspaceViewer.GlobalEnvItem) => workspaceViewer.viewItem(node.label),
'r.workspaceViewer.remove': (node: workspaceViewer.GlobalEnvItem) => workspaceViewer.removeItem(node.label),
'r.workspaceViewer.view': (node: workspaceViewer.GlobalEnvItem) => node.label && workspaceViewer.viewItem(node.label),
'r.workspaceViewer.remove': (node: workspaceViewer.GlobalEnvItem) => node.label && workspaceViewer.removeItem(node.label),
'r.workspaceViewer.clear': workspaceViewer.clearWorkspace,
'r.workspaceViewer.load': workspaceViewer.loadWorkspace,
'r.workspaceViewer.save': workspaceViewer.saveWorkspace,
Expand All @@ -145,9 +145,8 @@ export async function activate(context: vscode.ExtensionContext): Promise<apiImp

// (help related commands are registered in rHelp.initializeHelp)
};
for (const key in commands) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
context.subscriptions.push(vscode.commands.registerCommand(key, commands[key]));
for (const [key, value] of Object.entries(commands)) {
context.subscriptions.push(vscode.commands.registerCommand(key, value));
}


Expand Down
6 changes: 3 additions & 3 deletions src/helpViewer/helpProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import * as cp from 'child_process';

import * as rHelp from '.';
import { extensionContext } from '../extension';
import { DisposableProcess, getRLibPaths, spawn, spawnAsync } from '../util';
import { catchAsError, DisposableProcess, getRLibPaths, spawn, spawnAsync } from '../util';

export interface RHelpProviderOptions {
// path of the R executable
Expand Down Expand Up @@ -298,14 +298,14 @@ export class AliasProvider {
}
const re = new RegExp(`${lim}(.*)${lim}`, 'ms');
const match = re.exec(result.stdout);
if (match.length !== 2) {
if (match?.length !== 2) {
throw new Error('Could not parse R output.');
}
const json = match[1];
return <AllPackageAliases>JSON.parse(json) || {};
} catch (e) {
console.log(e);
void window.showErrorMessage((<{ message: string }>e).message);
void window.showErrorMessage(catchAsError(e).message);
}
}
}
18 changes: 15 additions & 3 deletions src/helpViewer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ export interface CodeClickConfig {
'Shift+Click': CodeClickAction,
}
const CODE_CLICKS: (keyof CodeClickConfig)[] = ['Click', 'Ctrl+Click', 'Shift+Click'];
export const codeClickConfigDefault = {
'Click': 'Copy',
'Ctrl+Click': 'Run',
'Shift+Click': 'Ignore',
};

// Initialization function that is called once when activating the extension
export async function initializeHelp(
Expand All @@ -39,6 +44,9 @@ export async function initializeHelp(

// get the "vanilla" R path from config
const rPath = await getRpath();
if(!rPath){
return undefined;
}

// get the current working directory from vscode
const cwd = vscode.workspace.workspaceFolders?.length
Expand Down Expand Up @@ -207,6 +215,7 @@ export class RHelp implements api.HelpPanel, vscode.WebviewPanelSerializer<strin
private helpPanelOptions: HelpOptions

constructor(options: HelpOptions) {
this.rPath = options.rPath;
this.webviewScriptFile = vscode.Uri.file(options.webviewScriptPath);
this.webviewStyleFile = vscode.Uri.file(options.webviewStylePath);
const pkgListener = () => {
Expand Down Expand Up @@ -510,7 +519,7 @@ export class RHelp implements api.HelpPanel, vscode.WebviewPanelSerializer<strin
? await this.helpProvider.getHelpFileFromRequestPath(
requestPath,
)
: await rGuestService.requestHelpContent(requestPath);
: await rGuestService?.requestHelpContent(requestPath);
this.cachedHelpFiles.set(requestPath, helpFile);
}

Expand Down Expand Up @@ -579,18 +588,21 @@ function pimpMyHelp(helpFile: HelpFile): HelpFile {

// Split code examples at empty lines:
const codeClickConfig = config().get<CodeClickConfig>('helpPanel.clickCodeExamples');
const isEnabled = CODE_CLICKS.some(k => codeClickConfig[k] !== 'Ignore');
const isEnabled = CODE_CLICKS.some(k => codeClickConfig?.[k] !== 'Ignore');
if(isEnabled){
$('body').addClass('preClickable');
const codeSections = $('pre');
codeSections.each((i, section) => {
const innerHtml = $(section).html();
if(!innerHtml){
return;
}
const newPres = innerHtml.split('\n\n').map(s => s && `<pre>${s}</pre>`);
const newHtml = '<div class="preDiv">' + newPres.join('\n') + '</div>';
$(section).replaceWith(newHtml);
});
}
if(codeClickConfig.Click !== 'Ignore'){
if(codeClickConfig?.Click !== 'Ignore'){
$('body').addClass('preHoverPointer');
}

Expand Down
Loading

0 comments on commit 9c9d266

Please sign in to comment.