{ } qjs-modules

lexer

Source: quickjs-lexer.c — module exports Lexer, Token (and Location, see location)

A configurable, rule-based tokenizer. Rules are regex-driven and grouped into named states; the lexer yields Token objects.

Lexer

new Lexer(input[, fileName, mode])   // length 1

Scanning methods

MethodArgsDescription
peek()0Returns the next token id without consuming.
peekToken()0Returns the next Token without consuming.
next()0Consumes and returns the next token id.
nextToken()0Consumes and returns the next Token.
lex()0Performs one lexing step.
setInput(input, fileName)1Replaces the input being scanned.
skipBytes(n) / skipChars(n)0Advance the cursor by bytes / chars.
skipToken()0Discards the next token.
skipUntil(predicate)1Skips until a condition holds.
back()0Pushes the last token back.
currentLine()0Returns the text of the current line.
tokenClass(id)1Returns the class/name for a token id.

Rule & state management

MethodArgsDescription
define(name, pattern)2Defines a named sub-pattern.
addRule(name, pattern)2Adds a token rule.
getRule(id)1Looks up a rule.
pushState(state)1Enters a lexer state (alias begin).
popState()0Leaves the current state (alias end).
topState()0Returns the active state.

Properties

PropertyKindDescription
sizegetterInput size in bytes.
charPosgetter/setterCursor position in characters.
bytePosgetterCursor position in bytes.
locgetterCurrent Location.
eofgetterWhether the end of input is reached.
modegetter/setterLexer mode flags.
seqgetterToken sequence counter.
byteLength / charLengthgetterRemaining input length.
stategetter/setterActive state.
statesgetterAll defined states.
stateDepth / stateStackgetterState-stack inspection.
inputgetterThe input text.
lexemegetterThe most recent lexeme.
fileNamegetter/setterSource file name.
ruleNames / rulesgetterDefined rule names / rules.
tokensgetterCollected tokens.

[Symbol.iterator] yields tokens, so a Lexer can drive for…of.

Static functions

FunctionArgsDescription
escape(str)1Escapes regex/lexer metacharacters.
unescape(str)1Reverses escape.
toString(value)1String form helper.
fromFile(path)1Creates a lexer reading from a file.

Token

new Token(...)   // length 1
PropertyKindDescription
charLength / byteLengthgetterLexeme length in chars / bytes.
charRange / byteRangegetter[start, end] ranges.
charPos / bytePosgetterStart offsets.
locgetter/setterLocation of the token.
idgetterNumeric token id.
seqgetterSequence number.
typegetterToken type/rule name (enumerable).
lexergetterOwning lexer.
rulegetterThe matched rule.
lexemegetterThe matched text (enumerable).

Methods: toString(), [Symbol.toPrimitive]().