Skip to content

Commit

Permalink
Parser: prettyIndex context lines
Browse files Browse the repository at this point in the history
  • Loading branch information
ivanjermakov committed Jun 10, 2023
1 parent ce2f775 commit 275d0c4
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 17 deletions.
8 changes: 2 additions & 6 deletions src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,6 @@ export const prettySyntaxError = (error: SyntaxError): string => {
export const prettySourceMessage = (message: string, index: number, source: Source): string => {
const location = indexToLocation(index, source)
const locationStr = `${location ? `${source.filename}:${prettyLocation(location)}` : '<unknwon location>'}`
const indent = ' '.repeat(4)
return `\
${prettyIndex(index, source)}
${message}
${indent}at ${locationStr}
`
const locationMsg = `${' '.repeat(2)}at ${locationStr}`
return [message, locationMsg, '\n' + prettyIndex(index, source, 1) + '\n'].join('\n')
}
23 changes: 12 additions & 11 deletions src/location.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { isNewline } from './lexer/lexer'
import { Source } from './source'
import { range } from './util/array'

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

/**
* TODO: context lines parameter
*/
export const prettyIndex = (index: number, source: Source): string => {
export const prettyIndex = (index: number, source: Source, context: number = 0): string => {
const start = indexToLocation(index, source)
if (!start) return '<outside of a file>'
const highlight = ' '.repeat(6 + start.column) + '^'
const linesBefore = range(0, context).map(i => start.line + i - context).map(i => prettyLine(i, source))
const linesAfter = range(0, context).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')
}

export const prettyLine = (lineIndex: number, source: Source): string => {
const lines = source.str.split('\n')
const line = lines[start.line]
const highlight = ' '.repeat(start.column) + '^'
const lineNum = `${(start.line + 1).toString()} | `.padStart(6)
return `\
${lineNum}${line}
${' '.repeat(lineNum.length)}${highlight}`
const line = lines[lineIndex]
const lineNum = `${(lineIndex + 1).toString()} | `.padStart(6)
return lineNum + line
}

export const prettyLocation = (location: Location): string => `${location.line + 1}:${location.column + 1}`
1 change: 1 addition & 0 deletions src/util/array.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const range = (from: number, to: number): number[] => new Array(to - from).fill(0).map((_, i) => i + from)

0 comments on commit 275d0c4

Please sign in to comment.