Skip to content

Commit

Permalink
Report parse errors instead of throwing an exception
Browse files Browse the repository at this point in the history
  • Loading branch information
Thomas Scholtes committed Aug 7, 2020
1 parent 285a83f commit acc957c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 9 deletions.
31 changes: 22 additions & 9 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,34 @@ function parseInput(inputStr) {
// first we try to parse the string as we normally do
return parser.parse(inputStr, { loc: true, range: true })
} catch (e) {
try {
// using 'loc' may throw when inputStr is empty or only has comments
return parser.parse(inputStr, {})
} catch (error) {
// if the parser fails in both scenarios (with and without 'loc')
// we throw the error, as we may be facing an invalid Solidity file
throw new Error(error)
}
// using 'loc' may throw when inputStr is empty or only has comments
return parser.parse(inputStr, {})
}
}

function processStr(inputStr, config = {}, fileName = '') {
config = applyExtends(config)

const ast = parseInput(inputStr)
let ast
try {
ast = parseInput(inputStr)
} catch (e) {
if (e instanceof parser.ParserError) {
const reporter = new Reporter([], config)
for (const error of e.errors) {
reporter.addReport(
error.line,
error.column,
Reporter.SEVERITY.ERROR,
`Parse error: ${error.message}`
)
}
return reporter
} else {
throw e
}
}

const tokens = parser.tokenize(inputStr, { loc: true })
const reporter = new Reporter(tokens, config)
const listener = new TreeListener(checkers(reporter, config, inputStr, tokens, fileName))
Expand Down
15 changes: 15 additions & 0 deletions test/parse-error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const assert = require('assert')
const { assertErrorCount } = require('./common/asserts')
const linter = require('./../lib/index')

describe('Parse error', () => {
it('should report parse errors', () => {
const report = linter.processStr('contract Foo {', {})

assertErrorCount(report, 1)
const error = report.reports[0]
assert.equal(error.line, 1)
assert.equal(error.column, 14)
assert.ok(error.message.startsWith("Parse error: mismatched input '<EOF>'"))
})
})

0 comments on commit acc957c

Please sign in to comment.