From 6289e0e06e5a4bae51a397cd5e6aeab6b1bf9aa9 Mon Sep 17 00:00:00 2001 From: fxy060608 Date: Sat, 2 Apr 2022 14:42:36 +0800 Subject: [PATCH] fix(mp): ignore javascript keywords when generate identifier (#3397) --- .../__tests__/identifier.spec.ts | 5 +- packages/uni-mp-compiler/src/identifier.ts | 74 ++++++++++++++++++- 2 files changed, 75 insertions(+), 4 deletions(-) diff --git a/packages/uni-mp-compiler/__tests__/identifier.spec.ts b/packages/uni-mp-compiler/__tests__/identifier.spec.ts index 3366e567e..d76e9c9aa 100644 --- a/packages/uni-mp-compiler/__tests__/identifier.spec.ts +++ b/packages/uni-mp-compiler/__tests__/identifier.spec.ts @@ -9,10 +9,11 @@ describe('identifier', () => { } expect(ids.next()).toBe('ab') expect(ids.next()).toBe('ac') + // do if in 已被忽略 for (let i = 0; i < 52 * 52 - 2; i++) { ids.next() } - expect(ids.next()).toBe('acc') - expect(ids.next()).toBe('acd') + expect(ids.next()).toBe('acf') + expect(ids.next()).toBe('acg') }) }) diff --git a/packages/uni-mp-compiler/src/identifier.ts b/packages/uni-mp-compiler/src/identifier.ts index a15c1a88f..387931ad2 100644 --- a/packages/uni-mp-compiler/src/identifier.ts +++ b/packages/uni-mp-compiler/src/identifier.ts @@ -3,13 +3,17 @@ export default class IdentifierGenerator { private _chars: string = 'abcdefghijklmnopqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' private _nextIds: number[] = [0] - next() { + next(): string { const r = [] for (const char of this._nextIds) { r.unshift(this._chars[char]) } this._increment() - return r.join('') + const id = r.join('') + if (keywords.includes(id)) { + return this.next() + } + return id } _increment() { @@ -30,3 +34,69 @@ export default class IdentifierGenerator { } } } +const keywords = [ + 'abstract', + 'arguments', + 'await', + 'boolean', + 'break', + 'byte', + 'case', + 'catch', + 'char', + 'class', + 'const', + 'continue', + 'debugger', + 'default', + 'delete', + 'do', + 'double', + 'else', + 'enum', + 'eval', + 'export', + 'extends', + 'false', + 'final', + 'finally', + 'float', + 'for', + 'function', + 'goto', + 'if', + 'implements', + 'import', + 'in', + 'instanceof', + 'int', + 'interface', + 'let', + 'long', + 'native', + 'new', + 'null', + 'package', + 'private', + 'protected', + 'public', + 'return', + 'short', + 'static', + 'super', + 'switch', + 'synchronized', + 'this', + 'throw', + 'throws', + 'transient', + 'true', + 'try', + 'typeof', + 'var', + 'void', + 'volatile', + 'while', + 'with', + 'yield', +] -- GitLab