From 225b90bc3c540e8b8614a5d20aad611701545b5d Mon Sep 17 00:00:00 2001 From: Bronley Plumb Date: Wed, 5 Jul 2023 13:49:44 -0400 Subject: [PATCH] Prevent crashing when diagnostic is missing range. (#832) --- src/DiagnosticCollection.spec.ts | 13 ++++++++++++- src/DiagnosticCollection.ts | 12 ++++++++---- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/DiagnosticCollection.spec.ts b/src/DiagnosticCollection.spec.ts index 82a03ca03..2a4d09c1f 100644 --- a/src/DiagnosticCollection.spec.ts +++ b/src/DiagnosticCollection.spec.ts @@ -33,6 +33,14 @@ describe('DiagnosticCollection', () => { expect(actual).to.eql(expected); } + it('does not crash for diagnostics with missing locations', () => { + const [d1] = addDiagnostics('file1.brs', ['I have no location']); + delete d1.range; + testPatch({ + 'file1.brs': ['I have no location'] + }); + }); + it('returns full list of diagnostics on first call, and nothing on second call', () => { addDiagnostics('file1.brs', ['message1', 'message2']); addDiagnostics('file2.brs', ['message3', 'message4']); @@ -96,8 +104,9 @@ describe('DiagnosticCollection', () => { } function addDiagnostics(srcPath: string, messages: string[]) { + const newDiagnostics = []; for (const message of messages) { - diagnostics.push({ + newDiagnostics.push({ file: { srcPath: srcPath } as BscFile, @@ -107,5 +116,7 @@ describe('DiagnosticCollection', () => { message: message }); } + diagnostics.push(...newDiagnostics); + return newDiagnostics as typeof diagnostics; } }); diff --git a/src/DiagnosticCollection.ts b/src/DiagnosticCollection.ts index d8724b9ca..98d067024 100644 --- a/src/DiagnosticCollection.ts +++ b/src/DiagnosticCollection.ts @@ -1,5 +1,6 @@ import type { BsDiagnostic } from './interfaces'; import type { Project } from './LanguageServer'; +import { util } from './util'; export class DiagnosticCollection { private previousDiagnosticsByFile = {} as Record; @@ -36,13 +37,16 @@ export class DiagnosticCollection { } const diagnosticMap = result[srcPath]; + //fall back to a default range if missing + const range = diagnostic?.range ?? util.createRange(0, 0, 0, 0); + diagnostic.key = srcPath.toLowerCase() + '-' + diagnostic.code + '-' + - diagnostic.range.start.line + '-' + - diagnostic.range.start.character + '-' + - diagnostic.range.end.line + '-' + - diagnostic.range.end.character + + range.start.line + '-' + + range.start.character + '-' + + range.end.line + '-' + + range.end.character + diagnostic.message; //don't include duplicates