Skip to content

Commit

Permalink
Fix #4449 Add a warning message when bibtex parser failed
Browse files Browse the repository at this point in the history
  • Loading branch information
James-Yu committed Oct 26, 2024
1 parent c5eb270 commit a3746b9
Show file tree
Hide file tree
Showing 7 changed files with 32 additions and 16 deletions.
5 changes: 2 additions & 3 deletions src/completion/completer/citation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as vscode from 'vscode'
import * as fs from 'fs'
import { bibtexParser } from 'latex-utensils'
import { lw } from '../../lw'
import type { CitationField, CitationItem, CompletionArgs, CompletionItem, CompletionProvider } from '../../types'
Expand Down Expand Up @@ -245,9 +244,9 @@ async function parseBibFile(fileName: string) {
return
}
const newEntry: CitationItem[] = []
const bibtex = fs.readFileSync(fileName).toString()
const bibtex = await lw.file.read(fileName)
logger.log(`Parse BibTeX AST from ${fileName} .`)
const ast = await lw.parser.parse.bib(bibtex)
const ast = await lw.parser.parse.bib(vscode.Uri.file(fileName), bibtex ?? '')
if (ast === undefined) {
logger.log(`Parsed 0 bib entries from ${fileName}.`)
lw.event.fire(lw.event.FileParsed, fileName)
Expand Down
5 changes: 4 additions & 1 deletion src/core/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,10 @@ export async function devParseBib() {
if (vscode.window.activeTextEditor === undefined) {
return
}
const ast = await lw.parser.parse.bib(vscode.window.activeTextEditor.document.getText())
const ast = await lw.parser.parse.bib(
vscode.window.activeTextEditor.document.uri,
vscode.window.activeTextEditor.document.getText()
)
return vscode.workspace.openTextDocument({content: JSON.stringify(ast, null, 2), language: 'json'}).then(doc => vscode.window.showTextDocument(doc))
}

Expand Down
2 changes: 1 addition & 1 deletion src/lint/bibtex-formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ async function formatDocument(document: vscode.TextDocument, sort: boolean, alig
const columnOffset = range ? range.start.character : 0

logger.log('Parse active BibTeX document for AST.')
const ast = await lw.parser.parse.bib(document.getText(range))
const ast = await lw.parser.parse.bib(document.uri, document.getText(range))
if (ast === undefined) {
return []
}
Expand Down
2 changes: 1 addition & 1 deletion src/outline/structure/bibtex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export async function buildBibTeX(document: vscode.TextDocument): Promise<TeXEle
return []
}
logger.log('Parse active BibTeX document for AST.')
const ast = await lw.parser.parse.bib(document.getText())
const ast = await lw.parser.parse.bib(document.uri, document.getText())
if (ast === undefined) {
return []
}
Expand Down
20 changes: 16 additions & 4 deletions src/parse/parser.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as vscode from 'vscode'
import * as path from 'path'
import * as workerpool from 'workerpool'
import type * as Ast from '@unified-latex/unified-latex-types'
Expand All @@ -12,6 +13,7 @@ import { latexLogParser } from './parser/latexlog'
import { toString } from '../../../resources/unified.js'

const logger = lw.log('Parser')
const bibDiagnostics = vscode.languages.createDiagnosticCollection('BibTeX')

export const parser = {
bib,
Expand Down Expand Up @@ -42,12 +44,22 @@ async function reset() {
return (await proxy).reset(getMacroDefs(), getEnvDefs())
}

async function bib(s: string, options?: bibtexParser.ParserOptions): Promise<bibtexParser.BibtexAst | undefined> {
const ast = await (await proxy).parseBibTeX(s, options)
if (ast instanceof Error) {
logger.logError('Error when parsing bib file.', ast)
async function bib(uri: vscode.Uri, s: string): Promise<bibtexParser.BibtexAst | undefined> {
const ast = await (await proxy).parseBibTeX(s)
if (typeof ast === 'string') {
const err = JSON.parse(ast) as bibtexParser.SyntaxError
logger.log(`Error when parsing bib file: found ${err.found} from ${err.location.start.line}:${err.location.start.column} to ${err.location.end.line}:${err.location.end.column}.`)
bibDiagnostics.set(uri, [new vscode.Diagnostic(
new vscode.Range(
new vscode.Position(err.location.start.line - 1, err.location.start.column - 1),
new vscode.Position(err.location.end.line - 1, err.location.end.column - 1)
),
`A BibTeX parsing error occurred. "${err.found}" is unexpected here. No BibTeX entries will be available.`,
vscode.DiagnosticSeverity.Warning
)])
return undefined
} else {
bibDiagnostics.set(uri, [])
return ast
}
}
Expand Down
9 changes: 5 additions & 4 deletions src/parse/parser/unified.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type * as Ast from '@unified-latex/unified-latex-types'
// import { getParser } from '@unified-latex/unified-latex-util-parse'
// import { attachMacroArgs } from '@unified-latex/unified-latex-util-arguments'
import { bibtexParser } from 'latex-utensils'
import type { SyntaxError } from 'latex-utensils/out/types/src/pegjs/pegjs_types.js'

Check failure on line 6 in src/parse/parser/unified.ts

View workflow job for this annotation

GitHub Actions / linux

'SyntaxError' is declared but its value is never read.

Check failure on line 6 in src/parse/parser/unified.ts

View workflow job for this annotation

GitHub Actions / linux

'SyntaxError' is declared but its value is never read.

Check failure on line 6 in src/parse/parser/unified.ts

View workflow job for this annotation

GitHub Actions / windows

'SyntaxError' is declared but its value is never read.

Check failure on line 6 in src/parse/parser/unified.ts

View workflow job for this annotation

GitHub Actions / macosx

'SyntaxError' is declared but its value is never read.

// @ts-expect-error Load unified.js from /out/src/...
import { getParser, attachMacroArgs } from '../../../../resources/unified.js'
Expand All @@ -26,12 +27,12 @@ function reset(macros: Ast.MacroInfoRecord, environments: Ast.EnvInfoRecord) {
unifiedParser = getParser({ macros, environments, flags: { autodetectExpl3AndAtLetter: true } })
}

function parseBibTeX(s: string, options?: bibtexParser.ParserOptions): bibtexParser.BibtexAst | Error | undefined {
function parseBibTeX(s: string): bibtexParser.BibtexAst | string | undefined {
try {
return bibtexParser.parse(s, options)
return bibtexParser.parse(s)
} catch (err) {
if (err instanceof Error) {
return err
if (bibtexParser.isSyntaxError(err)) {
return JSON.stringify(err)
}
return undefined
}
Expand Down
5 changes: 3 additions & 2 deletions test/units/11_parser_tex.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import * as vscode from 'vscode'
import * as path from 'path'
import * as sinon from 'sinon'
import { lw } from '../../src/lw'
Expand Down Expand Up @@ -26,7 +27,7 @@ describe(path.basename(__filename).split('.')[0] + ':', () => {

describe('lw.parser->bib', () => {
it('should parse BibTeX content', async () => {
const ast = await parser.bib('@article{key, author = "author"}')
const ast = await parser.bib(vscode.Uri.file('/main.bib'), '@article{key, author = "author"}')

assert.ok(ast)
assert.strictEqual(ast.content[0].entryType, 'article')
Expand All @@ -37,7 +38,7 @@ describe(path.basename(__filename).split('.')[0] + ':', () => {
})

it('should log error when parsing BibTeX content fails', async () => {
const ast = await parser.bib('@article{key, author = "author",')
const ast = await parser.bib(vscode.Uri.file('/main.bib'), '@article{key, author = "author",')

assert.strictEqual(ast, undefined)
assert.hasLog('Error when parsing bib file.')
Expand Down

0 comments on commit a3746b9

Please sign in to comment.