Skip to content

Commit 20fbc65

Browse files
committed
Refactor, add comments, and improve error messages
1 parent 7baca89 commit 20fbc65

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

scanner.js

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,13 @@ var ids = require('spdx-license-ids')
22
var exceptions = require('spdx-exceptions')
33

44
module.exports = function () {
5+
// Parse the input string all at once.
6+
// Store the array of tokens.
57
this.setInput = function (string) {
68
this.tokens = lex(string)
79
}
10+
11+
// Set the state for the Jison parser on each shift.
812
this.lex = function () {
913
var token = this.tokens.shift()
1014
this.yylineno = 1
@@ -24,18 +28,19 @@ var LICENSEREF = /^LicenseRef-([0-9A-Za-z-+.]+)$/
2428
var INVALID_CHARACTER = /[^ 0-9A-Za-z.+\-()]/
2529
var SINGLE_CHARACTER_TOKENS = ['(', ')', ':', '+']
2630

31+
// Polyfill ECMAScript 2016 Array.prototype.includes.
2732
var includes = Array.prototype.includes
28-
? function (array, element) {
29-
return array.includes(element)
30-
}
31-
: function (array, element) {
32-
return array.indexOf(element) !== -1
33-
}
33+
? function (array, element) { return array.includes(element) }
34+
: function (array, element) { return array.indexOf(element) !== -1 }
3435

3536
function lex (argument) {
36-
if (INVALID_CHARACTER.test(argument)) {
37-
throw new Error('Invalid character')
37+
// If there are invalid characters, catch them ahead of time.
38+
var match = INVALID_CHARACTER.exec(argument)
39+
if (match) {
40+
throw new Error('Invalid character at offset ' + match.index)
3841
}
42+
// Iterate through the argument string, buffering
43+
// non-space characters and building tokens.
3944
var tokens = []
4045
var characterBuffer = ''
4146
var startedBuffering = null
@@ -60,6 +65,7 @@ function lex (argument) {
6065
}
6166
}
6267
pushBuffered()
68+
// Add an end-of-string token.
6369
tokens.push({
6470
type: 'EOS',
6571
string: '',
@@ -70,12 +76,14 @@ function lex (argument) {
7076

7177
function pushBuffered () {
7278
if (characterBuffer) {
79+
// Create a token for the buffered characters.
7380
tokens.push({
7481
type: tokenTypeForString(characterBuffer, startedBuffering),
7582
string: characterBuffer,
7683
start: startedBuffering,
7784
end: startedBuffering + characterBuffer.length
7885
})
86+
// Reset the buffer.
7987
characterBuffer = ''
8088
startedBuffering = null
8189
}

0 commit comments

Comments
 (0)