From 832c626b6904bba8683dcdba1c27579c9903af8f Mon Sep 17 00:00:00 2001 From: azu Date: Thu, 10 Nov 2022 10:44:30 +0900 Subject: [PATCH] fix: support nested context (#15) * fix: support nested context * test: add test * CI: update node versions --- .github/workflows/test.yml | 2 +- src/parser/PairMaker.js | 33 ++++++++++++++++++-- test/textlint-rule-no-unmatched-pair-test.js | 2 ++ 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 170443f..b35a187 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,7 +6,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - node-version: [12, 14] + node-version: [ 16, 18 ] steps: - name: checkout uses: actions/checkout@v2 diff --git a/src/parser/PairMaker.js b/src/parser/PairMaker.js index 895bd8d..7eb221c 100644 --- a/src/parser/PairMaker.js +++ b/src/parser/PairMaker.js @@ -69,17 +69,44 @@ const PAIR_MARKS = [ } ]; +// create entries +// [start.key, mark] +// [end.key, mark] +const PAIR_MARKS_ENTRIES = PAIR_MARKS.map(mark => { + return [ + [mark.start, mark], + [mark.end, mark] + ]; +}).flat(1); + +/** + * Optimized Map + * @type Map + */ +const PAIR_MARKS_KEY_Map = new Map(PAIR_MARKS_ENTRIES); +const matchPair = (string) => { + return PAIR_MARKS_KEY_Map.get(string); +} // For readme // console.log(PAIR_MARKS.map(pair => `- ${pair.key}: \`${pair.start}\` and \`${pair.end}\``).join("\n")); export class PairMaker { + /** + * @param {import("./SourceCode").SourceCode} sourceCode + * @returns + */ mark(sourceCode) { const string = sourceCode.read(); if (!string) { return; } - // if current is in a context, should not start other context. - // PairMaker does not support nest context by design. - if (sourceCode.isInContext()) { + + const matchedPair = matchPair(string) + if (!matchedPair){ + return; + } + // support nested pair + // {"{test}"} + if (sourceCode.isInContext(matchedPair)) { // check that string is end mark? const pair = PAIR_MARKS.find(pair => pair.end === string); if (pair) { diff --git a/test/textlint-rule-no-unmatched-pair-test.js b/test/textlint-rule-no-unmatched-pair-test.js index 550189c..d181507 100644 --- a/test/textlint-rule-no-unmatched-pair-test.js +++ b/test/textlint-rule-no-unmatched-pair-test.js @@ -7,6 +7,8 @@ const rule = require("../src/textlint-rule-no-unmatched-pair.js"); // ruleName, rule, { valid, invalid } tester.run("textlint-rule-no-unmatched-pair", rule, { valid: [ + `{"{ABC}"}`, + 'test {"{ABC`{"{ABC}"}`}"} ok.', "これは(秘密)です。", `John said "Hello World!".`, "`(` is ok.", "文字列リテラルには3種類ありますが、まずは`\"`(ダブルクオート)と`'`(シングルクオート)について見ていきます。",