microsoft/typespec
Publicmirrored from https://github.com/microsoft/typespecAvailable
packages/compiler/scripts/regen-nonascii.js
78lines · modecode
| 1 | // Regenerate the table used to scan non-ASCII identifiers. |
| 2 | |
| 3 | import assert from "assert"; |
| 4 | import { writeFileSync } from "fs"; |
| 5 | import { resolve } from "path"; |
| 6 | import { fileURLToPath } from "url"; |
| 7 | |
| 8 | const disallowedProperties = [ |
| 9 | "General_Category=Control", |
| 10 | "General_Category=Private_Use", |
| 11 | "General_Category=Surrogate", |
| 12 | "Noncharacter_Code_Point", |
| 13 | "Pattern_White_Space", |
| 14 | "Unassigned", |
| 15 | ]; |
| 16 | |
| 17 | const disallowedCodePoints = [ |
| 18 | 0xfffd, // REPLACEMENT CHARACTER |
| 19 | ]; |
| 20 | |
| 21 | const MIN_NONASCII_CODEPOINT = 0x80; |
| 22 | const MAX_UNICODE_CODEPOINT = 0x10ffff; |
| 23 | |
| 24 | const disallowedRegex = new RegExp( |
| 25 | `[${disallowedProperties.map((p) => `\\p{${p}}`).join("")}]`, |
| 26 | "u", |
| 27 | ); |
| 28 | |
| 29 | const map = computeMap(); |
| 30 | |
| 31 | function isDisallowed(codePoint) { |
| 32 | return ( |
| 33 | disallowedCodePoints.includes(codePoint) || |
| 34 | disallowedRegex.test(String.fromCodePoint(codePoint)) |
| 35 | ); |
| 36 | } |
| 37 | |
| 38 | function formatPairs(array) { |
| 39 | let s = ""; |
| 40 | for (let i = 0; i < array.length; i += 2) { |
| 41 | s += ` 0x${array[i].toString(16)}, 0x${array[i + 1].toString(16)},\n`; |
| 42 | } |
| 43 | return s.slice(0, -1); |
| 44 | } |
| 45 | |
| 46 | function computeMap() { |
| 47 | const map = []; |
| 48 | let active = false; |
| 49 | for (let i = MIN_NONASCII_CODEPOINT; i <= MAX_UNICODE_CODEPOINT; i++) { |
| 50 | const allowed = !isDisallowed(i); |
| 51 | if (allowed !== active) { |
| 52 | map.push(active ? i - 1 : i); |
| 53 | active = !active; |
| 54 | } |
| 55 | } |
| 56 | assert(!active, "MAX_UNICODE_CODEPOINT should not be allowed."); |
| 57 | return map; |
| 58 | } |
| 59 | |
| 60 | const src = `// |
| 61 | // Generated by scripts/regen-nonascii.js |
| 62 | // on node ${process.version} with unicode ${process.versions.unicode}. |
| 63 | // |
| 64 | |
| 65 | /** |
| 66 | * @internal |
| 67 | * |
| 68 | * Map of non-ascii characters that are valid in an identifier. Each pair of |
| 69 | * numbers represents an inclusive range of code points. |
| 70 | */ |
| 71 | //prettier-ignore |
| 72 | export const nonAsciiIdentifierMap: readonly number[] = [ |
| 73 | ${formatPairs(map)} |
| 74 | ]; |
| 75 | `; |
| 76 | |
| 77 | const file = resolve(fileURLToPath(import.meta.url), "../../src/core/nonascii.ts"); |
| 78 | writeFileSync(file, src); |
| 79 | |