Parsimmon은 JavaScript와 Node.js를 위한 작고 우아한 파서 콤비네이터 라이브러리입니다.
기본 예제
const P = require('parsimmon');
// 소문자와 일치하는 파서 생성
const word = P.regexp(/[a-z]+/);
const result = word.parse('hello');
// => { status: true, value: 'hello' }
원자적 파서 (Atomic Parsers)
P.string('function'); // 정확한 문자열 리터럴 일치
P.regexp(/[0-9]+/); // 정규표현식 일치
P.oneOf('abc'); // 'a', 'b', 'c' 중 한 문자 일치
P.whitespace; // 하나 이상의 공백 문자
P.optWhitespace; // 0개 이상의 공백 문자
P.eof; // 입력 스트림의 끝 (EOF)
콤비네이터 (Combinators)
// 시퀀스: 모든 파서와 순서대로 일치
P.seq(P.string('('), P.number, P.string(')'));
// 대안: 첫 번째 성공한 파서와 일치
P.alt(P.string('true'), P.string('false'));
// 또는 .or() 사용:
a.or(b);
// 구분 기호로 분리된 목록
P.sepBy(P.number, P.string(',')); // 쉼표로 구분된 숫자 (0개 이상)
P.sepBy1(P.number, P.string(',')); // 쉼표로 구분된 숫자 (최소 1개)
// 반복
a.many(); // 0 or more
a.atLeast(1); // 1 or more
a.times(3); // Exactly 3 times
a.times(1, 4); // Between 1 and 4 times
// 토큰 폐기
a.skip(P.string(';')); // 'a'를 파싱하고 ';'와 일치시킨 후 'a'만 반환
출력 변환 (map)
const arithmeticExpr = P.seq(
P.digits.map(Number),
P.oneOf('+-*/').trim(P.optWhitespace),
P.digits.map(Number)
).map(([left, operator, right]) => ({
type: 'BinaryExpression',
operator,
left,
right
}));
arithmeticExpr.parse('10 + 20');