Skip to content

Commit

Permalink
Simplify pretty error
Browse files Browse the repository at this point in the history
  • Loading branch information
ivanjermakov committed Jun 18, 2023
1 parent 864b35c commit 9b3985e
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 11 deletions.
6 changes: 3 additions & 3 deletions src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ export interface SyntaxError {
}

export const prettyLexerError = (token: ParseToken): string => {
return red(`lexer error: ${token.kind} token \`${token.value}\``)
return prettyError(`lexer error: ${token.kind} token \`${token.value}\``)
}

export const prettySyntaxError = (error: SyntaxError): string => {
const msg = error.message ?? `expected \`${error.expected.join(', ')}\``
return red(`syntax error: ${msg}, got \`${error.got.kind}\``)
return prettyError(`syntax error: ${msg}, got \`${error.got.kind}\``)
}

export const prettyError = (message: string): string => {
Expand All @@ -25,5 +25,5 @@ export const prettyError = (message: string): string => {
export const prettySourceMessage = (message: string, location: Location, source: Source): string => {
const locationStr = `${location ? `${source.filename}:${locationToString(location)}` : '<unknwon location>'}`
const locationMsg = `${' '.repeat(2)}at ${locationStr}`
return [message, locationMsg, '\n' + prettyLineAt(location, source, 1) + '\n'].join('\n')
return [message, locationMsg, '\n' + prettyLineAt(location, source)].join('\n')
}
10 changes: 2 additions & 8 deletions src/location.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { isNewline } from './lexer/lexer'
import { Source } from './source'
import { range } from './util/array'

export interface LocationRange {
start: number
Expand Down Expand Up @@ -29,15 +28,10 @@ export const indexToLocation = (index: number, source: Source): Location | undef
return undefined
}

export const prettyLineAt = (start: Location, source: Source, context: number = 0): string => {
export const prettyLineAt = (start: Location, source: Source): string => {
if (!start) return '<outside of a file>'
const highlight = ' '.repeat(6 + start.column) + '^'
const linesBefore = range(0, Math.min(context, start.line)).map(i => start.line + i - context).map(i => prettyLine(i, source))
const totalLines = source.str.split('\n').filter(l => l.length === 0).length
const linesAfterCount = Math.min(context, Math.max(0, totalLines - 1 - start.line))
const linesAfter = range(0, linesAfterCount).map(i => start.line + i + context).map(i => prettyLine(i, source))

return [linesBefore.join('\n'), prettyLine(start.line, source), highlight, linesAfter.join('\n')].join('\n')
return [prettyLine(start.line, source), highlight].join('\n')
}

export const prettyLine = (lineIndex: number, source: Source): string => {
Expand Down

0 comments on commit 9b3985e

Please sign in to comment.