UNPKG

depends-txt

Version:
63 lines 2.28 kB
import { Directive, Event, Severity } from './events.js'; import { peekable } from './peekable.js'; import { Token, tokenize } from './tokenize.js'; export class Parser { #tokens; #directive = Directive.Hard; #word = 0; constructor(input) { this.#tokens = peekable(tokenize(input)); } next() { const result = this.#tokens.next(); if (result.done ?? false) { return { value: undefined, done: true }; } const { type, value, position } = result.value; switch (type) { case Token.Word: ++this.#word; if (this.#word === 1 && isDirective(value) && this.#tokens.peekNth(0).value?.type === Token.WhiteSpace && this.#tokens.peekNth(1).value?.type === Token.Word) { this.#directive = value; return { value: { type: Event.Directive, value, position } }; } if (this.#directive === Directive.Package && this.#word !== 2) { return { value: this.#tooManyArguments(result.value) }; } return { value: { type: Event.Name, value, position } }; case Token.NewLine: this.#directive = Directive.Hard; this.#word = 0; break; default: } return { value: { type, value, position } }; } // eslint-disable-next-line @typescript-eslint/prefer-readonly-parameter-types #tooManyArguments(token) { const { value, position } = token; const message = { ruleId: 'too-many-arguments', reason: 'the package directive must have exactly one argument, ' + `but ${this.#word} found`, place: structuredClone(position), fatal: Severity.Error, }; return { type: Event.Error, value, position, data: { message } }; } [Symbol.iterator]() { return this; } get directive() { return this.#directive; } } function isDirective(input) { return input === Directive.Hard || input === Directive.Soft || input === Directive.Package; } //# sourceMappingURL=parser.js.map