message-compiler.mjs 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528
  1. /*!
  2. * message-compiler v9.5.0
  3. * (c) 2023 kazuya kawaguchi
  4. * Released under the MIT License.
  5. */
  6. import { format, assign, join, isString } from '@intlify/shared';
  7. const LOCATION_STUB = {
  8. start: { line: 1, column: 1, offset: 0 },
  9. end: { line: 1, column: 1, offset: 0 }
  10. };
  11. function createPosition(line, column, offset) {
  12. return { line, column, offset };
  13. }
  14. function createLocation(start, end, source) {
  15. const loc = { start, end };
  16. if (source != null) {
  17. loc.source = source;
  18. }
  19. return loc;
  20. }
  21. const CompileErrorCodes = {
  22. // tokenizer error codes
  23. EXPECTED_TOKEN: 1,
  24. INVALID_TOKEN_IN_PLACEHOLDER: 2,
  25. UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER: 3,
  26. UNKNOWN_ESCAPE_SEQUENCE: 4,
  27. INVALID_UNICODE_ESCAPE_SEQUENCE: 5,
  28. UNBALANCED_CLOSING_BRACE: 6,
  29. UNTERMINATED_CLOSING_BRACE: 7,
  30. EMPTY_PLACEHOLDER: 8,
  31. NOT_ALLOW_NEST_PLACEHOLDER: 9,
  32. INVALID_LINKED_FORMAT: 10,
  33. // parser error codes
  34. MUST_HAVE_MESSAGES_IN_PLURAL: 11,
  35. UNEXPECTED_EMPTY_LINKED_MODIFIER: 12,
  36. UNEXPECTED_EMPTY_LINKED_KEY: 13,
  37. UNEXPECTED_LEXICAL_ANALYSIS: 14,
  38. // generator error codes
  39. UNHANDLED_CODEGEN_NODE_TYPE: 15,
  40. // minifier error codes
  41. UNHANDLED_MINIFIER_NODE_TYPE: 16,
  42. // Special value for higher-order compilers to pick up the last code
  43. // to avoid collision of error codes. This should always be kept as the last
  44. // item.
  45. __EXTEND_POINT__: 17
  46. };
  47. /** @internal */
  48. const errorMessages = {
  49. // tokenizer error messages
  50. [CompileErrorCodes.EXPECTED_TOKEN]: `Expected token: '{0}'`,
  51. [CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER]: `Invalid token in placeholder: '{0}'`,
  52. [CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER]: `Unterminated single quote in placeholder`,
  53. [CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE]: `Unknown escape sequence: \\{0}`,
  54. [CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE]: `Invalid unicode escape sequence: {0}`,
  55. [CompileErrorCodes.UNBALANCED_CLOSING_BRACE]: `Unbalanced closing brace`,
  56. [CompileErrorCodes.UNTERMINATED_CLOSING_BRACE]: `Unterminated closing brace`,
  57. [CompileErrorCodes.EMPTY_PLACEHOLDER]: `Empty placeholder`,
  58. [CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER]: `Not allowed nest placeholder`,
  59. [CompileErrorCodes.INVALID_LINKED_FORMAT]: `Invalid linked format`,
  60. // parser error messages
  61. [CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL]: `Plural must have messages`,
  62. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER]: `Unexpected empty linked modifier`,
  63. [CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY]: `Unexpected empty linked key`,
  64. [CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS]: `Unexpected lexical analysis in token: '{0}'`,
  65. // generator error messages
  66. [CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE]: `unhandled codegen node type: '{0}'`,
  67. // minimizer error messages
  68. [CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE]: `unhandled mimifier node type: '{0}'`
  69. };
  70. function createCompileError(code, loc, options = {}) {
  71. const { domain, messages, args } = options;
  72. const msg = (process.env.NODE_ENV !== 'production')
  73. ? format((messages || errorMessages)[code] || '', ...(args || []))
  74. : code;
  75. const error = new SyntaxError(String(msg));
  76. error.code = code;
  77. if (loc) {
  78. error.location = loc;
  79. }
  80. error.domain = domain;
  81. return error;
  82. }
  83. /** @internal */
  84. function defaultOnError(error) {
  85. throw error;
  86. }
  87. const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
  88. const detectHtmlTag = (source) => RE_HTML_TAG.test(source);
  89. const CHAR_SP = ' ';
  90. const CHAR_CR = '\r';
  91. const CHAR_LF = '\n';
  92. const CHAR_LS = String.fromCharCode(0x2028);
  93. const CHAR_PS = String.fromCharCode(0x2029);
  94. function createScanner(str) {
  95. const _buf = str;
  96. let _index = 0;
  97. let _line = 1;
  98. let _column = 1;
  99. let _peekOffset = 0;
  100. const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
  101. const isLF = (index) => _buf[index] === CHAR_LF;
  102. const isPS = (index) => _buf[index] === CHAR_PS;
  103. const isLS = (index) => _buf[index] === CHAR_LS;
  104. const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
  105. const index = () => _index;
  106. const line = () => _line;
  107. const column = () => _column;
  108. const peekOffset = () => _peekOffset;
  109. const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
  110. const currentChar = () => charAt(_index);
  111. const currentPeek = () => charAt(_index + _peekOffset);
  112. function next() {
  113. _peekOffset = 0;
  114. if (isLineEnd(_index)) {
  115. _line++;
  116. _column = 0;
  117. }
  118. if (isCRLF(_index)) {
  119. _index++;
  120. }
  121. _index++;
  122. _column++;
  123. return _buf[_index];
  124. }
  125. function peek() {
  126. if (isCRLF(_index + _peekOffset)) {
  127. _peekOffset++;
  128. }
  129. _peekOffset++;
  130. return _buf[_index + _peekOffset];
  131. }
  132. function reset() {
  133. _index = 0;
  134. _line = 1;
  135. _column = 1;
  136. _peekOffset = 0;
  137. }
  138. function resetPeek(offset = 0) {
  139. _peekOffset = offset;
  140. }
  141. function skipToPeek() {
  142. const target = _index + _peekOffset;
  143. // eslint-disable-next-line no-unmodified-loop-condition
  144. while (target !== _index) {
  145. next();
  146. }
  147. _peekOffset = 0;
  148. }
  149. return {
  150. index,
  151. line,
  152. column,
  153. peekOffset,
  154. charAt,
  155. currentChar,
  156. currentPeek,
  157. next,
  158. peek,
  159. reset,
  160. resetPeek,
  161. skipToPeek
  162. };
  163. }
  164. const EOF = undefined;
  165. const DOT = '.';
  166. const LITERAL_DELIMITER = "'";
  167. const ERROR_DOMAIN$3 = 'tokenizer';
  168. function createTokenizer(source, options = {}) {
  169. const location = options.location !== false;
  170. const _scnr = createScanner(source);
  171. const currentOffset = () => _scnr.index();
  172. const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
  173. const _initLoc = currentPosition();
  174. const _initOffset = currentOffset();
  175. const _context = {
  176. currentType: 14 /* TokenTypes.EOF */,
  177. offset: _initOffset,
  178. startLoc: _initLoc,
  179. endLoc: _initLoc,
  180. lastType: 14 /* TokenTypes.EOF */,
  181. lastOffset: _initOffset,
  182. lastStartLoc: _initLoc,
  183. lastEndLoc: _initLoc,
  184. braceNest: 0,
  185. inLinked: false,
  186. text: ''
  187. };
  188. const context = () => _context;
  189. const { onError } = options;
  190. function emitError(code, pos, offset, ...args) {
  191. const ctx = context();
  192. pos.column += offset;
  193. pos.offset += offset;
  194. if (onError) {
  195. const loc = location ? createLocation(ctx.startLoc, pos) : null;
  196. const err = createCompileError(code, loc, {
  197. domain: ERROR_DOMAIN$3,
  198. args
  199. });
  200. onError(err);
  201. }
  202. }
  203. function getToken(context, type, value) {
  204. context.endLoc = currentPosition();
  205. context.currentType = type;
  206. const token = { type };
  207. if (location) {
  208. token.loc = createLocation(context.startLoc, context.endLoc);
  209. }
  210. if (value != null) {
  211. token.value = value;
  212. }
  213. return token;
  214. }
  215. const getEndToken = (context) => getToken(context, 14 /* TokenTypes.EOF */);
  216. function eat(scnr, ch) {
  217. if (scnr.currentChar() === ch) {
  218. scnr.next();
  219. return ch;
  220. }
  221. else {
  222. emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
  223. return '';
  224. }
  225. }
  226. function peekSpaces(scnr) {
  227. let buf = '';
  228. while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
  229. buf += scnr.currentPeek();
  230. scnr.peek();
  231. }
  232. return buf;
  233. }
  234. function skipSpaces(scnr) {
  235. const buf = peekSpaces(scnr);
  236. scnr.skipToPeek();
  237. return buf;
  238. }
  239. function isIdentifierStart(ch) {
  240. if (ch === EOF) {
  241. return false;
  242. }
  243. const cc = ch.charCodeAt(0);
  244. return ((cc >= 97 && cc <= 122) || // a-z
  245. (cc >= 65 && cc <= 90) || // A-Z
  246. cc === 95 // _
  247. );
  248. }
  249. function isNumberStart(ch) {
  250. if (ch === EOF) {
  251. return false;
  252. }
  253. const cc = ch.charCodeAt(0);
  254. return cc >= 48 && cc <= 57; // 0-9
  255. }
  256. function isNamedIdentifierStart(scnr, context) {
  257. const { currentType } = context;
  258. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  259. return false;
  260. }
  261. peekSpaces(scnr);
  262. const ret = isIdentifierStart(scnr.currentPeek());
  263. scnr.resetPeek();
  264. return ret;
  265. }
  266. function isListIdentifierStart(scnr, context) {
  267. const { currentType } = context;
  268. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  269. return false;
  270. }
  271. peekSpaces(scnr);
  272. const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
  273. const ret = isNumberStart(ch);
  274. scnr.resetPeek();
  275. return ret;
  276. }
  277. function isLiteralStart(scnr, context) {
  278. const { currentType } = context;
  279. if (currentType !== 2 /* TokenTypes.BraceLeft */) {
  280. return false;
  281. }
  282. peekSpaces(scnr);
  283. const ret = scnr.currentPeek() === LITERAL_DELIMITER;
  284. scnr.resetPeek();
  285. return ret;
  286. }
  287. function isLinkedDotStart(scnr, context) {
  288. const { currentType } = context;
  289. if (currentType !== 8 /* TokenTypes.LinkedAlias */) {
  290. return false;
  291. }
  292. peekSpaces(scnr);
  293. const ret = scnr.currentPeek() === "." /* TokenChars.LinkedDot */;
  294. scnr.resetPeek();
  295. return ret;
  296. }
  297. function isLinkedModifierStart(scnr, context) {
  298. const { currentType } = context;
  299. if (currentType !== 9 /* TokenTypes.LinkedDot */) {
  300. return false;
  301. }
  302. peekSpaces(scnr);
  303. const ret = isIdentifierStart(scnr.currentPeek());
  304. scnr.resetPeek();
  305. return ret;
  306. }
  307. function isLinkedDelimiterStart(scnr, context) {
  308. const { currentType } = context;
  309. if (!(currentType === 8 /* TokenTypes.LinkedAlias */ ||
  310. currentType === 12 /* TokenTypes.LinkedModifier */)) {
  311. return false;
  312. }
  313. peekSpaces(scnr);
  314. const ret = scnr.currentPeek() === ":" /* TokenChars.LinkedDelimiter */;
  315. scnr.resetPeek();
  316. return ret;
  317. }
  318. function isLinkedReferStart(scnr, context) {
  319. const { currentType } = context;
  320. if (currentType !== 10 /* TokenTypes.LinkedDelimiter */) {
  321. return false;
  322. }
  323. const fn = () => {
  324. const ch = scnr.currentPeek();
  325. if (ch === "{" /* TokenChars.BraceLeft */) {
  326. return isIdentifierStart(scnr.peek());
  327. }
  328. else if (ch === "@" /* TokenChars.LinkedAlias */ ||
  329. ch === "%" /* TokenChars.Modulo */ ||
  330. ch === "|" /* TokenChars.Pipe */ ||
  331. ch === ":" /* TokenChars.LinkedDelimiter */ ||
  332. ch === "." /* TokenChars.LinkedDot */ ||
  333. ch === CHAR_SP ||
  334. !ch) {
  335. return false;
  336. }
  337. else if (ch === CHAR_LF) {
  338. scnr.peek();
  339. return fn();
  340. }
  341. else {
  342. // other characters
  343. return isIdentifierStart(ch);
  344. }
  345. };
  346. const ret = fn();
  347. scnr.resetPeek();
  348. return ret;
  349. }
  350. function isPluralStart(scnr) {
  351. peekSpaces(scnr);
  352. const ret = scnr.currentPeek() === "|" /* TokenChars.Pipe */;
  353. scnr.resetPeek();
  354. return ret;
  355. }
  356. function detectModuloStart(scnr) {
  357. const spaces = peekSpaces(scnr);
  358. const ret = scnr.currentPeek() === "%" /* TokenChars.Modulo */ &&
  359. scnr.peek() === "{" /* TokenChars.BraceLeft */;
  360. scnr.resetPeek();
  361. return {
  362. isModulo: ret,
  363. hasSpace: spaces.length > 0
  364. };
  365. }
  366. function isTextStart(scnr, reset = true) {
  367. const fn = (hasSpace = false, prev = '', detectModulo = false) => {
  368. const ch = scnr.currentPeek();
  369. if (ch === "{" /* TokenChars.BraceLeft */) {
  370. return prev === "%" /* TokenChars.Modulo */ ? false : hasSpace;
  371. }
  372. else if (ch === "@" /* TokenChars.LinkedAlias */ || !ch) {
  373. return prev === "%" /* TokenChars.Modulo */ ? true : hasSpace;
  374. }
  375. else if (ch === "%" /* TokenChars.Modulo */) {
  376. scnr.peek();
  377. return fn(hasSpace, "%" /* TokenChars.Modulo */, true);
  378. }
  379. else if (ch === "|" /* TokenChars.Pipe */) {
  380. return prev === "%" /* TokenChars.Modulo */ || detectModulo
  381. ? true
  382. : !(prev === CHAR_SP || prev === CHAR_LF);
  383. }
  384. else if (ch === CHAR_SP) {
  385. scnr.peek();
  386. return fn(true, CHAR_SP, detectModulo);
  387. }
  388. else if (ch === CHAR_LF) {
  389. scnr.peek();
  390. return fn(true, CHAR_LF, detectModulo);
  391. }
  392. else {
  393. return true;
  394. }
  395. };
  396. const ret = fn();
  397. reset && scnr.resetPeek();
  398. return ret;
  399. }
  400. function takeChar(scnr, fn) {
  401. const ch = scnr.currentChar();
  402. if (ch === EOF) {
  403. return EOF;
  404. }
  405. if (fn(ch)) {
  406. scnr.next();
  407. return ch;
  408. }
  409. return null;
  410. }
  411. function takeIdentifierChar(scnr) {
  412. const closure = (ch) => {
  413. const cc = ch.charCodeAt(0);
  414. return ((cc >= 97 && cc <= 122) || // a-z
  415. (cc >= 65 && cc <= 90) || // A-Z
  416. (cc >= 48 && cc <= 57) || // 0-9
  417. cc === 95 || // _
  418. cc === 36 // $
  419. );
  420. };
  421. return takeChar(scnr, closure);
  422. }
  423. function takeDigit(scnr) {
  424. const closure = (ch) => {
  425. const cc = ch.charCodeAt(0);
  426. return cc >= 48 && cc <= 57; // 0-9
  427. };
  428. return takeChar(scnr, closure);
  429. }
  430. function takeHexDigit(scnr) {
  431. const closure = (ch) => {
  432. const cc = ch.charCodeAt(0);
  433. return ((cc >= 48 && cc <= 57) || // 0-9
  434. (cc >= 65 && cc <= 70) || // A-F
  435. (cc >= 97 && cc <= 102)); // a-f
  436. };
  437. return takeChar(scnr, closure);
  438. }
  439. function getDigits(scnr) {
  440. let ch = '';
  441. let num = '';
  442. while ((ch = takeDigit(scnr))) {
  443. num += ch;
  444. }
  445. return num;
  446. }
  447. function readModulo(scnr) {
  448. skipSpaces(scnr);
  449. const ch = scnr.currentChar();
  450. if (ch !== "%" /* TokenChars.Modulo */) {
  451. emitError(CompileErrorCodes.EXPECTED_TOKEN, currentPosition(), 0, ch);
  452. }
  453. scnr.next();
  454. return "%" /* TokenChars.Modulo */;
  455. }
  456. function readText(scnr) {
  457. let buf = '';
  458. while (true) {
  459. const ch = scnr.currentChar();
  460. if (ch === "{" /* TokenChars.BraceLeft */ ||
  461. ch === "}" /* TokenChars.BraceRight */ ||
  462. ch === "@" /* TokenChars.LinkedAlias */ ||
  463. ch === "|" /* TokenChars.Pipe */ ||
  464. !ch) {
  465. break;
  466. }
  467. else if (ch === "%" /* TokenChars.Modulo */) {
  468. if (isTextStart(scnr)) {
  469. buf += ch;
  470. scnr.next();
  471. }
  472. else {
  473. break;
  474. }
  475. }
  476. else if (ch === CHAR_SP || ch === CHAR_LF) {
  477. if (isTextStart(scnr)) {
  478. buf += ch;
  479. scnr.next();
  480. }
  481. else if (isPluralStart(scnr)) {
  482. break;
  483. }
  484. else {
  485. buf += ch;
  486. scnr.next();
  487. }
  488. }
  489. else {
  490. buf += ch;
  491. scnr.next();
  492. }
  493. }
  494. return buf;
  495. }
  496. function readNamedIdentifier(scnr) {
  497. skipSpaces(scnr);
  498. let ch = '';
  499. let name = '';
  500. while ((ch = takeIdentifierChar(scnr))) {
  501. name += ch;
  502. }
  503. if (scnr.currentChar() === EOF) {
  504. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  505. }
  506. return name;
  507. }
  508. function readListIdentifier(scnr) {
  509. skipSpaces(scnr);
  510. let value = '';
  511. if (scnr.currentChar() === '-') {
  512. scnr.next();
  513. value += `-${getDigits(scnr)}`;
  514. }
  515. else {
  516. value += getDigits(scnr);
  517. }
  518. if (scnr.currentChar() === EOF) {
  519. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  520. }
  521. return value;
  522. }
  523. function readLiteral(scnr) {
  524. skipSpaces(scnr);
  525. eat(scnr, `\'`);
  526. let ch = '';
  527. let literal = '';
  528. const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF;
  529. while ((ch = takeChar(scnr, fn))) {
  530. if (ch === '\\') {
  531. literal += readEscapeSequence(scnr);
  532. }
  533. else {
  534. literal += ch;
  535. }
  536. }
  537. const current = scnr.currentChar();
  538. if (current === CHAR_LF || current === EOF) {
  539. emitError(CompileErrorCodes.UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER, currentPosition(), 0);
  540. // TODO: Is it correct really?
  541. if (current === CHAR_LF) {
  542. scnr.next();
  543. eat(scnr, `\'`);
  544. }
  545. return literal;
  546. }
  547. eat(scnr, `\'`);
  548. return literal;
  549. }
  550. function readEscapeSequence(scnr) {
  551. const ch = scnr.currentChar();
  552. switch (ch) {
  553. case '\\':
  554. case `\'`:
  555. scnr.next();
  556. return `\\${ch}`;
  557. case 'u':
  558. return readUnicodeEscapeSequence(scnr, ch, 4);
  559. case 'U':
  560. return readUnicodeEscapeSequence(scnr, ch, 6);
  561. default:
  562. emitError(CompileErrorCodes.UNKNOWN_ESCAPE_SEQUENCE, currentPosition(), 0, ch);
  563. return '';
  564. }
  565. }
  566. function readUnicodeEscapeSequence(scnr, unicode, digits) {
  567. eat(scnr, unicode);
  568. let sequence = '';
  569. for (let i = 0; i < digits; i++) {
  570. const ch = takeHexDigit(scnr);
  571. if (!ch) {
  572. emitError(CompileErrorCodes.INVALID_UNICODE_ESCAPE_SEQUENCE, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
  573. break;
  574. }
  575. sequence += ch;
  576. }
  577. return `\\${unicode}${sequence}`;
  578. }
  579. function readInvalidIdentifier(scnr) {
  580. skipSpaces(scnr);
  581. let ch = '';
  582. let identifiers = '';
  583. const closure = (ch) => ch !== "{" /* TokenChars.BraceLeft */ &&
  584. ch !== "}" /* TokenChars.BraceRight */ &&
  585. ch !== CHAR_SP &&
  586. ch !== CHAR_LF;
  587. while ((ch = takeChar(scnr, closure))) {
  588. identifiers += ch;
  589. }
  590. return identifiers;
  591. }
  592. function readLinkedModifier(scnr) {
  593. let ch = '';
  594. let name = '';
  595. while ((ch = takeIdentifierChar(scnr))) {
  596. name += ch;
  597. }
  598. return name;
  599. }
  600. function readLinkedRefer(scnr) {
  601. const fn = (detect = false, buf) => {
  602. const ch = scnr.currentChar();
  603. if (ch === "{" /* TokenChars.BraceLeft */ ||
  604. ch === "%" /* TokenChars.Modulo */ ||
  605. ch === "@" /* TokenChars.LinkedAlias */ ||
  606. ch === "|" /* TokenChars.Pipe */ ||
  607. ch === "(" /* TokenChars.ParenLeft */ ||
  608. ch === ")" /* TokenChars.ParenRight */ ||
  609. !ch) {
  610. return buf;
  611. }
  612. else if (ch === CHAR_SP) {
  613. return buf;
  614. }
  615. else if (ch === CHAR_LF || ch === DOT) {
  616. buf += ch;
  617. scnr.next();
  618. return fn(detect, buf);
  619. }
  620. else {
  621. buf += ch;
  622. scnr.next();
  623. return fn(true, buf);
  624. }
  625. };
  626. return fn(false, '');
  627. }
  628. function readPlural(scnr) {
  629. skipSpaces(scnr);
  630. const plural = eat(scnr, "|" /* TokenChars.Pipe */);
  631. skipSpaces(scnr);
  632. return plural;
  633. }
  634. // TODO: We need refactoring of token parsing ...
  635. function readTokenInPlaceholder(scnr, context) {
  636. let token = null;
  637. const ch = scnr.currentChar();
  638. switch (ch) {
  639. case "{" /* TokenChars.BraceLeft */:
  640. if (context.braceNest >= 1) {
  641. emitError(CompileErrorCodes.NOT_ALLOW_NEST_PLACEHOLDER, currentPosition(), 0);
  642. }
  643. scnr.next();
  644. token = getToken(context, 2 /* TokenTypes.BraceLeft */, "{" /* TokenChars.BraceLeft */);
  645. skipSpaces(scnr);
  646. context.braceNest++;
  647. return token;
  648. case "}" /* TokenChars.BraceRight */:
  649. if (context.braceNest > 0 &&
  650. context.currentType === 2 /* TokenTypes.BraceLeft */) {
  651. emitError(CompileErrorCodes.EMPTY_PLACEHOLDER, currentPosition(), 0);
  652. }
  653. scnr.next();
  654. token = getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
  655. context.braceNest--;
  656. context.braceNest > 0 && skipSpaces(scnr);
  657. if (context.inLinked && context.braceNest === 0) {
  658. context.inLinked = false;
  659. }
  660. return token;
  661. case "@" /* TokenChars.LinkedAlias */:
  662. if (context.braceNest > 0) {
  663. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  664. }
  665. token = readTokenInLinked(scnr, context) || getEndToken(context);
  666. context.braceNest = 0;
  667. return token;
  668. default:
  669. let validNamedIdentifier = true;
  670. let validListIdentifier = true;
  671. let validLiteral = true;
  672. if (isPluralStart(scnr)) {
  673. if (context.braceNest > 0) {
  674. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  675. }
  676. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  677. // reset
  678. context.braceNest = 0;
  679. context.inLinked = false;
  680. return token;
  681. }
  682. if (context.braceNest > 0 &&
  683. (context.currentType === 5 /* TokenTypes.Named */ ||
  684. context.currentType === 6 /* TokenTypes.List */ ||
  685. context.currentType === 7 /* TokenTypes.Literal */)) {
  686. emitError(CompileErrorCodes.UNTERMINATED_CLOSING_BRACE, currentPosition(), 0);
  687. context.braceNest = 0;
  688. return readToken(scnr, context);
  689. }
  690. if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
  691. token = getToken(context, 5 /* TokenTypes.Named */, readNamedIdentifier(scnr));
  692. skipSpaces(scnr);
  693. return token;
  694. }
  695. if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
  696. token = getToken(context, 6 /* TokenTypes.List */, readListIdentifier(scnr));
  697. skipSpaces(scnr);
  698. return token;
  699. }
  700. if ((validLiteral = isLiteralStart(scnr, context))) {
  701. token = getToken(context, 7 /* TokenTypes.Literal */, readLiteral(scnr));
  702. skipSpaces(scnr);
  703. return token;
  704. }
  705. if (!validNamedIdentifier && !validListIdentifier && !validLiteral) {
  706. // TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
  707. token = getToken(context, 13 /* TokenTypes.InvalidPlace */, readInvalidIdentifier(scnr));
  708. emitError(CompileErrorCodes.INVALID_TOKEN_IN_PLACEHOLDER, currentPosition(), 0, token.value);
  709. skipSpaces(scnr);
  710. return token;
  711. }
  712. break;
  713. }
  714. return token;
  715. }
  716. // TODO: We need refactoring of token parsing ...
  717. function readTokenInLinked(scnr, context) {
  718. const { currentType } = context;
  719. let token = null;
  720. const ch = scnr.currentChar();
  721. if ((currentType === 8 /* TokenTypes.LinkedAlias */ ||
  722. currentType === 9 /* TokenTypes.LinkedDot */ ||
  723. currentType === 12 /* TokenTypes.LinkedModifier */ ||
  724. currentType === 10 /* TokenTypes.LinkedDelimiter */) &&
  725. (ch === CHAR_LF || ch === CHAR_SP)) {
  726. emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
  727. }
  728. switch (ch) {
  729. case "@" /* TokenChars.LinkedAlias */:
  730. scnr.next();
  731. token = getToken(context, 8 /* TokenTypes.LinkedAlias */, "@" /* TokenChars.LinkedAlias */);
  732. context.inLinked = true;
  733. return token;
  734. case "." /* TokenChars.LinkedDot */:
  735. skipSpaces(scnr);
  736. scnr.next();
  737. return getToken(context, 9 /* TokenTypes.LinkedDot */, "." /* TokenChars.LinkedDot */);
  738. case ":" /* TokenChars.LinkedDelimiter */:
  739. skipSpaces(scnr);
  740. scnr.next();
  741. return getToken(context, 10 /* TokenTypes.LinkedDelimiter */, ":" /* TokenChars.LinkedDelimiter */);
  742. default:
  743. if (isPluralStart(scnr)) {
  744. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  745. // reset
  746. context.braceNest = 0;
  747. context.inLinked = false;
  748. return token;
  749. }
  750. if (isLinkedDotStart(scnr, context) ||
  751. isLinkedDelimiterStart(scnr, context)) {
  752. skipSpaces(scnr);
  753. return readTokenInLinked(scnr, context);
  754. }
  755. if (isLinkedModifierStart(scnr, context)) {
  756. skipSpaces(scnr);
  757. return getToken(context, 12 /* TokenTypes.LinkedModifier */, readLinkedModifier(scnr));
  758. }
  759. if (isLinkedReferStart(scnr, context)) {
  760. skipSpaces(scnr);
  761. if (ch === "{" /* TokenChars.BraceLeft */) {
  762. // scan the placeholder
  763. return readTokenInPlaceholder(scnr, context) || token;
  764. }
  765. else {
  766. return getToken(context, 11 /* TokenTypes.LinkedKey */, readLinkedRefer(scnr));
  767. }
  768. }
  769. if (currentType === 8 /* TokenTypes.LinkedAlias */) {
  770. emitError(CompileErrorCodes.INVALID_LINKED_FORMAT, currentPosition(), 0);
  771. }
  772. context.braceNest = 0;
  773. context.inLinked = false;
  774. return readToken(scnr, context);
  775. }
  776. }
  777. // TODO: We need refactoring of token parsing ...
  778. function readToken(scnr, context) {
  779. let token = { type: 14 /* TokenTypes.EOF */ };
  780. if (context.braceNest > 0) {
  781. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  782. }
  783. if (context.inLinked) {
  784. return readTokenInLinked(scnr, context) || getEndToken(context);
  785. }
  786. const ch = scnr.currentChar();
  787. switch (ch) {
  788. case "{" /* TokenChars.BraceLeft */:
  789. return readTokenInPlaceholder(scnr, context) || getEndToken(context);
  790. case "}" /* TokenChars.BraceRight */:
  791. emitError(CompileErrorCodes.UNBALANCED_CLOSING_BRACE, currentPosition(), 0);
  792. scnr.next();
  793. return getToken(context, 3 /* TokenTypes.BraceRight */, "}" /* TokenChars.BraceRight */);
  794. case "@" /* TokenChars.LinkedAlias */:
  795. return readTokenInLinked(scnr, context) || getEndToken(context);
  796. default:
  797. if (isPluralStart(scnr)) {
  798. token = getToken(context, 1 /* TokenTypes.Pipe */, readPlural(scnr));
  799. // reset
  800. context.braceNest = 0;
  801. context.inLinked = false;
  802. return token;
  803. }
  804. const { isModulo, hasSpace } = detectModuloStart(scnr);
  805. if (isModulo) {
  806. return hasSpace
  807. ? getToken(context, 0 /* TokenTypes.Text */, readText(scnr))
  808. : getToken(context, 4 /* TokenTypes.Modulo */, readModulo(scnr));
  809. }
  810. if (isTextStart(scnr)) {
  811. return getToken(context, 0 /* TokenTypes.Text */, readText(scnr));
  812. }
  813. break;
  814. }
  815. return token;
  816. }
  817. function nextToken() {
  818. const { currentType, offset, startLoc, endLoc } = _context;
  819. _context.lastType = currentType;
  820. _context.lastOffset = offset;
  821. _context.lastStartLoc = startLoc;
  822. _context.lastEndLoc = endLoc;
  823. _context.offset = currentOffset();
  824. _context.startLoc = currentPosition();
  825. if (_scnr.currentChar() === EOF) {
  826. return getToken(_context, 14 /* TokenTypes.EOF */);
  827. }
  828. return readToken(_scnr, _context);
  829. }
  830. return {
  831. nextToken,
  832. currentOffset,
  833. currentPosition,
  834. context
  835. };
  836. }
  837. const ERROR_DOMAIN$2 = 'parser';
  838. // Backslash backslash, backslash quote, uHHHH, UHHHHHH.
  839. const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
  840. function fromEscapeSequence(match, codePoint4, codePoint6) {
  841. switch (match) {
  842. case `\\\\`:
  843. return `\\`;
  844. case `\\\'`:
  845. return `\'`;
  846. default: {
  847. const codePoint = parseInt(codePoint4 || codePoint6, 16);
  848. if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
  849. return String.fromCodePoint(codePoint);
  850. }
  851. // invalid ...
  852. // Replace them with U+FFFD REPLACEMENT CHARACTER.
  853. return '�';
  854. }
  855. }
  856. }
  857. function createParser(options = {}) {
  858. const location = options.location !== false;
  859. const { onError } = options;
  860. function emitError(tokenzer, code, start, offset, ...args) {
  861. const end = tokenzer.currentPosition();
  862. end.offset += offset;
  863. end.column += offset;
  864. if (onError) {
  865. const loc = location ? createLocation(start, end) : null;
  866. const err = createCompileError(code, loc, {
  867. domain: ERROR_DOMAIN$2,
  868. args
  869. });
  870. onError(err);
  871. }
  872. }
  873. function startNode(type, offset, loc) {
  874. const node = { type };
  875. if (location) {
  876. node.start = offset;
  877. node.end = offset;
  878. node.loc = { start: loc, end: loc };
  879. }
  880. return node;
  881. }
  882. function endNode(node, offset, pos, type) {
  883. if (type) {
  884. node.type = type;
  885. }
  886. if (location) {
  887. node.end = offset;
  888. if (node.loc) {
  889. node.loc.end = pos;
  890. }
  891. }
  892. }
  893. function parseText(tokenizer, value) {
  894. const context = tokenizer.context();
  895. const node = startNode(3 /* NodeTypes.Text */, context.offset, context.startLoc);
  896. node.value = value;
  897. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  898. return node;
  899. }
  900. function parseList(tokenizer, index) {
  901. const context = tokenizer.context();
  902. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  903. const node = startNode(5 /* NodeTypes.List */, offset, loc);
  904. node.index = parseInt(index, 10);
  905. tokenizer.nextToken(); // skip brach right
  906. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  907. return node;
  908. }
  909. function parseNamed(tokenizer, key) {
  910. const context = tokenizer.context();
  911. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  912. const node = startNode(4 /* NodeTypes.Named */, offset, loc);
  913. node.key = key;
  914. tokenizer.nextToken(); // skip brach right
  915. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  916. return node;
  917. }
  918. function parseLiteral(tokenizer, value) {
  919. const context = tokenizer.context();
  920. const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
  921. const node = startNode(9 /* NodeTypes.Literal */, offset, loc);
  922. node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
  923. tokenizer.nextToken(); // skip brach right
  924. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  925. return node;
  926. }
  927. function parseLinkedModifier(tokenizer) {
  928. const token = tokenizer.nextToken();
  929. const context = tokenizer.context();
  930. const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
  931. const node = startNode(8 /* NodeTypes.LinkedModifier */, offset, loc);
  932. if (token.type !== 12 /* TokenTypes.LinkedModifier */) {
  933. // empty modifier
  934. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_MODIFIER, context.lastStartLoc, 0);
  935. node.value = '';
  936. endNode(node, offset, loc);
  937. return {
  938. nextConsumeToken: token,
  939. node
  940. };
  941. }
  942. // check token
  943. if (token.value == null) {
  944. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  945. }
  946. node.value = token.value || '';
  947. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  948. return {
  949. node
  950. };
  951. }
  952. function parseLinkedKey(tokenizer, value) {
  953. const context = tokenizer.context();
  954. const node = startNode(7 /* NodeTypes.LinkedKey */, context.offset, context.startLoc);
  955. node.value = value;
  956. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  957. return node;
  958. }
  959. function parseLinked(tokenizer) {
  960. const context = tokenizer.context();
  961. const linkedNode = startNode(6 /* NodeTypes.Linked */, context.offset, context.startLoc);
  962. let token = tokenizer.nextToken();
  963. if (token.type === 9 /* TokenTypes.LinkedDot */) {
  964. const parsed = parseLinkedModifier(tokenizer);
  965. linkedNode.modifier = parsed.node;
  966. token = parsed.nextConsumeToken || tokenizer.nextToken();
  967. }
  968. // asset check token
  969. if (token.type !== 10 /* TokenTypes.LinkedDelimiter */) {
  970. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  971. }
  972. token = tokenizer.nextToken();
  973. // skip brace left
  974. if (token.type === 2 /* TokenTypes.BraceLeft */) {
  975. token = tokenizer.nextToken();
  976. }
  977. switch (token.type) {
  978. case 11 /* TokenTypes.LinkedKey */:
  979. if (token.value == null) {
  980. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  981. }
  982. linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
  983. break;
  984. case 5 /* TokenTypes.Named */:
  985. if (token.value == null) {
  986. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  987. }
  988. linkedNode.key = parseNamed(tokenizer, token.value || '');
  989. break;
  990. case 6 /* TokenTypes.List */:
  991. if (token.value == null) {
  992. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  993. }
  994. linkedNode.key = parseList(tokenizer, token.value || '');
  995. break;
  996. case 7 /* TokenTypes.Literal */:
  997. if (token.value == null) {
  998. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  999. }
  1000. linkedNode.key = parseLiteral(tokenizer, token.value || '');
  1001. break;
  1002. default:
  1003. // empty key
  1004. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_EMPTY_LINKED_KEY, context.lastStartLoc, 0);
  1005. const nextContext = tokenizer.context();
  1006. const emptyLinkedKeyNode = startNode(7 /* NodeTypes.LinkedKey */, nextContext.offset, nextContext.startLoc);
  1007. emptyLinkedKeyNode.value = '';
  1008. endNode(emptyLinkedKeyNode, nextContext.offset, nextContext.startLoc);
  1009. linkedNode.key = emptyLinkedKeyNode;
  1010. endNode(linkedNode, nextContext.offset, nextContext.startLoc);
  1011. return {
  1012. nextConsumeToken: token,
  1013. node: linkedNode
  1014. };
  1015. }
  1016. endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
  1017. return {
  1018. node: linkedNode
  1019. };
  1020. }
  1021. function parseMessage(tokenizer) {
  1022. const context = tokenizer.context();
  1023. const startOffset = context.currentType === 1 /* TokenTypes.Pipe */
  1024. ? tokenizer.currentOffset()
  1025. : context.offset;
  1026. const startLoc = context.currentType === 1 /* TokenTypes.Pipe */
  1027. ? context.endLoc
  1028. : context.startLoc;
  1029. const node = startNode(2 /* NodeTypes.Message */, startOffset, startLoc);
  1030. node.items = [];
  1031. let nextToken = null;
  1032. do {
  1033. const token = nextToken || tokenizer.nextToken();
  1034. nextToken = null;
  1035. switch (token.type) {
  1036. case 0 /* TokenTypes.Text */:
  1037. if (token.value == null) {
  1038. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1039. }
  1040. node.items.push(parseText(tokenizer, token.value || ''));
  1041. break;
  1042. case 6 /* TokenTypes.List */:
  1043. if (token.value == null) {
  1044. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1045. }
  1046. node.items.push(parseList(tokenizer, token.value || ''));
  1047. break;
  1048. case 5 /* TokenTypes.Named */:
  1049. if (token.value == null) {
  1050. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1051. }
  1052. node.items.push(parseNamed(tokenizer, token.value || ''));
  1053. break;
  1054. case 7 /* TokenTypes.Literal */:
  1055. if (token.value == null) {
  1056. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, getTokenCaption(token));
  1057. }
  1058. node.items.push(parseLiteral(tokenizer, token.value || ''));
  1059. break;
  1060. case 8 /* TokenTypes.LinkedAlias */:
  1061. const parsed = parseLinked(tokenizer);
  1062. node.items.push(parsed.node);
  1063. nextToken = parsed.nextConsumeToken || null;
  1064. break;
  1065. }
  1066. } while (context.currentType !== 14 /* TokenTypes.EOF */ &&
  1067. context.currentType !== 1 /* TokenTypes.Pipe */);
  1068. // adjust message node loc
  1069. const endOffset = context.currentType === 1 /* TokenTypes.Pipe */
  1070. ? context.lastOffset
  1071. : tokenizer.currentOffset();
  1072. const endLoc = context.currentType === 1 /* TokenTypes.Pipe */
  1073. ? context.lastEndLoc
  1074. : tokenizer.currentPosition();
  1075. endNode(node, endOffset, endLoc);
  1076. return node;
  1077. }
  1078. function parsePlural(tokenizer, offset, loc, msgNode) {
  1079. const context = tokenizer.context();
  1080. let hasEmptyMessage = msgNode.items.length === 0;
  1081. const node = startNode(1 /* NodeTypes.Plural */, offset, loc);
  1082. node.cases = [];
  1083. node.cases.push(msgNode);
  1084. do {
  1085. const msg = parseMessage(tokenizer);
  1086. if (!hasEmptyMessage) {
  1087. hasEmptyMessage = msg.items.length === 0;
  1088. }
  1089. node.cases.push(msg);
  1090. } while (context.currentType !== 14 /* TokenTypes.EOF */);
  1091. if (hasEmptyMessage) {
  1092. emitError(tokenizer, CompileErrorCodes.MUST_HAVE_MESSAGES_IN_PLURAL, loc, 0);
  1093. }
  1094. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1095. return node;
  1096. }
  1097. function parseResource(tokenizer) {
  1098. const context = tokenizer.context();
  1099. const { offset, startLoc } = context;
  1100. const msgNode = parseMessage(tokenizer);
  1101. if (context.currentType === 14 /* TokenTypes.EOF */) {
  1102. return msgNode;
  1103. }
  1104. else {
  1105. return parsePlural(tokenizer, offset, startLoc, msgNode);
  1106. }
  1107. }
  1108. function parse(source) {
  1109. const tokenizer = createTokenizer(source, assign({}, options));
  1110. const context = tokenizer.context();
  1111. const node = startNode(0 /* NodeTypes.Resource */, context.offset, context.startLoc);
  1112. if (location && node.loc) {
  1113. node.loc.source = source;
  1114. }
  1115. node.body = parseResource(tokenizer);
  1116. if (options.onCacheKey) {
  1117. node.cacheKey = options.onCacheKey(source);
  1118. }
  1119. // assert whether achieved to EOF
  1120. if (context.currentType !== 14 /* TokenTypes.EOF */) {
  1121. emitError(tokenizer, CompileErrorCodes.UNEXPECTED_LEXICAL_ANALYSIS, context.lastStartLoc, 0, source[context.offset] || '');
  1122. }
  1123. endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
  1124. return node;
  1125. }
  1126. return { parse };
  1127. }
  1128. function getTokenCaption(token) {
  1129. if (token.type === 14 /* TokenTypes.EOF */) {
  1130. return 'EOF';
  1131. }
  1132. const name = (token.value || '').replace(/\r?\n/gu, '\\n');
  1133. return name.length > 10 ? name.slice(0, 9) + '…' : name;
  1134. }
  1135. function createTransformer(ast, options = {} // eslint-disable-line
  1136. ) {
  1137. const _context = {
  1138. ast,
  1139. helpers: new Set()
  1140. };
  1141. const context = () => _context;
  1142. const helper = (name) => {
  1143. _context.helpers.add(name);
  1144. return name;
  1145. };
  1146. return { context, helper };
  1147. }
  1148. function traverseNodes(nodes, transformer) {
  1149. for (let i = 0; i < nodes.length; i++) {
  1150. traverseNode(nodes[i], transformer);
  1151. }
  1152. }
  1153. function traverseNode(node, transformer) {
  1154. // TODO: if we need pre-hook of transform, should be implemented to here
  1155. switch (node.type) {
  1156. case 1 /* NodeTypes.Plural */:
  1157. traverseNodes(node.cases, transformer);
  1158. transformer.helper("plural" /* HelperNameMap.PLURAL */);
  1159. break;
  1160. case 2 /* NodeTypes.Message */:
  1161. traverseNodes(node.items, transformer);
  1162. break;
  1163. case 6 /* NodeTypes.Linked */:
  1164. const linked = node;
  1165. traverseNode(linked.key, transformer);
  1166. transformer.helper("linked" /* HelperNameMap.LINKED */);
  1167. transformer.helper("type" /* HelperNameMap.TYPE */);
  1168. break;
  1169. case 5 /* NodeTypes.List */:
  1170. transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
  1171. transformer.helper("list" /* HelperNameMap.LIST */);
  1172. break;
  1173. case 4 /* NodeTypes.Named */:
  1174. transformer.helper("interpolate" /* HelperNameMap.INTERPOLATE */);
  1175. transformer.helper("named" /* HelperNameMap.NAMED */);
  1176. break;
  1177. }
  1178. // TODO: if we need post-hook of transform, should be implemented to here
  1179. }
  1180. // transform AST
  1181. function transform(ast, options = {} // eslint-disable-line
  1182. ) {
  1183. const transformer = createTransformer(ast);
  1184. transformer.helper("normalize" /* HelperNameMap.NORMALIZE */);
  1185. // traverse
  1186. ast.body && traverseNode(ast.body, transformer);
  1187. // set meta information
  1188. const context = transformer.context();
  1189. ast.helpers = Array.from(context.helpers);
  1190. }
  1191. function optimize(ast) {
  1192. const body = ast.body;
  1193. if (body.type === 2 /* NodeTypes.Message */) {
  1194. optimizeMessageNode(body);
  1195. }
  1196. else {
  1197. body.cases.forEach(c => optimizeMessageNode(c));
  1198. }
  1199. return ast;
  1200. }
  1201. function optimizeMessageNode(message) {
  1202. if (message.items.length === 1) {
  1203. const item = message.items[0];
  1204. if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
  1205. message.static = item.value;
  1206. delete item.value; // optimization for size
  1207. }
  1208. }
  1209. else {
  1210. const values = [];
  1211. for (let i = 0; i < message.items.length; i++) {
  1212. const item = message.items[i];
  1213. if (!(item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */)) {
  1214. break;
  1215. }
  1216. if (item.value == null) {
  1217. break;
  1218. }
  1219. values.push(item.value);
  1220. }
  1221. if (values.length === message.items.length) {
  1222. message.static = join(values);
  1223. for (let i = 0; i < message.items.length; i++) {
  1224. const item = message.items[i];
  1225. if (item.type === 3 /* NodeTypes.Text */ || item.type === 9 /* NodeTypes.Literal */) {
  1226. delete item.value; // optimization for size
  1227. }
  1228. }
  1229. }
  1230. }
  1231. }
  1232. const ERROR_DOMAIN$1 = 'minifier';
  1233. /* eslint-disable @typescript-eslint/no-explicit-any */
  1234. function minify(node) {
  1235. node.t = node.type;
  1236. switch (node.type) {
  1237. case 0 /* NodeTypes.Resource */:
  1238. const resource = node;
  1239. minify(resource.body);
  1240. resource.b = resource.body;
  1241. delete resource.body;
  1242. break;
  1243. case 1 /* NodeTypes.Plural */:
  1244. const plural = node;
  1245. const cases = plural.cases;
  1246. for (let i = 0; i < cases.length; i++) {
  1247. minify(cases[i]);
  1248. }
  1249. plural.c = cases;
  1250. delete plural.cases;
  1251. break;
  1252. case 2 /* NodeTypes.Message */:
  1253. const message = node;
  1254. const items = message.items;
  1255. for (let i = 0; i < items.length; i++) {
  1256. minify(items[i]);
  1257. }
  1258. message.i = items;
  1259. delete message.items;
  1260. if (message.static) {
  1261. message.s = message.static;
  1262. delete message.static;
  1263. }
  1264. break;
  1265. case 3 /* NodeTypes.Text */:
  1266. case 9 /* NodeTypes.Literal */:
  1267. case 8 /* NodeTypes.LinkedModifier */:
  1268. case 7 /* NodeTypes.LinkedKey */:
  1269. const valueNode = node;
  1270. if (valueNode.value) {
  1271. valueNode.v = valueNode.value;
  1272. delete valueNode.value;
  1273. }
  1274. break;
  1275. case 6 /* NodeTypes.Linked */:
  1276. const linked = node;
  1277. minify(linked.key);
  1278. linked.k = linked.key;
  1279. delete linked.key;
  1280. if (linked.modifier) {
  1281. minify(linked.modifier);
  1282. linked.m = linked.modifier;
  1283. delete linked.modifier;
  1284. }
  1285. break;
  1286. case 5 /* NodeTypes.List */:
  1287. const list = node;
  1288. list.i = list.index;
  1289. delete list.index;
  1290. break;
  1291. case 4 /* NodeTypes.Named */:
  1292. const named = node;
  1293. named.k = named.key;
  1294. delete named.key;
  1295. break;
  1296. default:
  1297. if ((process.env.NODE_ENV !== 'production')) {
  1298. throw createCompileError(CompileErrorCodes.UNHANDLED_MINIFIER_NODE_TYPE, null, {
  1299. domain: ERROR_DOMAIN$1,
  1300. args: [node.type]
  1301. });
  1302. }
  1303. }
  1304. delete node.type;
  1305. }
  1306. /* eslint-enable @typescript-eslint/no-explicit-any */
  1307. const ERROR_DOMAIN = 'parser';
  1308. function createCodeGenerator(ast, options) {
  1309. const { sourceMap, filename, breakLineCode, needIndent: _needIndent } = options;
  1310. const location = options.location !== false;
  1311. const _context = {
  1312. filename,
  1313. code: '',
  1314. column: 1,
  1315. line: 1,
  1316. offset: 0,
  1317. map: undefined,
  1318. breakLineCode,
  1319. needIndent: _needIndent,
  1320. indentLevel: 0
  1321. };
  1322. if (location && ast.loc) {
  1323. _context.source = ast.loc.source;
  1324. }
  1325. const context = () => _context;
  1326. function push(code, node) {
  1327. _context.code += code;
  1328. }
  1329. function _newline(n, withBreakLine = true) {
  1330. const _breakLineCode = withBreakLine ? breakLineCode : '';
  1331. push(_needIndent ? _breakLineCode + ` `.repeat(n) : _breakLineCode);
  1332. }
  1333. function indent(withNewLine = true) {
  1334. const level = ++_context.indentLevel;
  1335. withNewLine && _newline(level);
  1336. }
  1337. function deindent(withNewLine = true) {
  1338. const level = --_context.indentLevel;
  1339. withNewLine && _newline(level);
  1340. }
  1341. function newline() {
  1342. _newline(_context.indentLevel);
  1343. }
  1344. const helper = (key) => `_${key}`;
  1345. const needIndent = () => _context.needIndent;
  1346. return {
  1347. context,
  1348. push,
  1349. indent,
  1350. deindent,
  1351. newline,
  1352. helper,
  1353. needIndent
  1354. };
  1355. }
  1356. function generateLinkedNode(generator, node) {
  1357. const { helper } = generator;
  1358. generator.push(`${helper("linked" /* HelperNameMap.LINKED */)}(`);
  1359. generateNode(generator, node.key);
  1360. if (node.modifier) {
  1361. generator.push(`, `);
  1362. generateNode(generator, node.modifier);
  1363. generator.push(`, _type`);
  1364. }
  1365. else {
  1366. generator.push(`, undefined, _type`);
  1367. }
  1368. generator.push(`)`);
  1369. }
  1370. function generateMessageNode(generator, node) {
  1371. const { helper, needIndent } = generator;
  1372. generator.push(`${helper("normalize" /* HelperNameMap.NORMALIZE */)}([`);
  1373. generator.indent(needIndent());
  1374. const length = node.items.length;
  1375. for (let i = 0; i < length; i++) {
  1376. generateNode(generator, node.items[i]);
  1377. if (i === length - 1) {
  1378. break;
  1379. }
  1380. generator.push(', ');
  1381. }
  1382. generator.deindent(needIndent());
  1383. generator.push('])');
  1384. }
  1385. function generatePluralNode(generator, node) {
  1386. const { helper, needIndent } = generator;
  1387. if (node.cases.length > 1) {
  1388. generator.push(`${helper("plural" /* HelperNameMap.PLURAL */)}([`);
  1389. generator.indent(needIndent());
  1390. const length = node.cases.length;
  1391. for (let i = 0; i < length; i++) {
  1392. generateNode(generator, node.cases[i]);
  1393. if (i === length - 1) {
  1394. break;
  1395. }
  1396. generator.push(', ');
  1397. }
  1398. generator.deindent(needIndent());
  1399. generator.push(`])`);
  1400. }
  1401. }
  1402. function generateResource(generator, node) {
  1403. if (node.body) {
  1404. generateNode(generator, node.body);
  1405. }
  1406. else {
  1407. generator.push('null');
  1408. }
  1409. }
  1410. function generateNode(generator, node) {
  1411. const { helper } = generator;
  1412. switch (node.type) {
  1413. case 0 /* NodeTypes.Resource */:
  1414. generateResource(generator, node);
  1415. break;
  1416. case 1 /* NodeTypes.Plural */:
  1417. generatePluralNode(generator, node);
  1418. break;
  1419. case 2 /* NodeTypes.Message */:
  1420. generateMessageNode(generator, node);
  1421. break;
  1422. case 6 /* NodeTypes.Linked */:
  1423. generateLinkedNode(generator, node);
  1424. break;
  1425. case 8 /* NodeTypes.LinkedModifier */:
  1426. generator.push(JSON.stringify(node.value), node);
  1427. break;
  1428. case 7 /* NodeTypes.LinkedKey */:
  1429. generator.push(JSON.stringify(node.value), node);
  1430. break;
  1431. case 5 /* NodeTypes.List */:
  1432. generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("list" /* HelperNameMap.LIST */)}(${node.index}))`, node);
  1433. break;
  1434. case 4 /* NodeTypes.Named */:
  1435. generator.push(`${helper("interpolate" /* HelperNameMap.INTERPOLATE */)}(${helper("named" /* HelperNameMap.NAMED */)}(${JSON.stringify(node.key)}))`, node);
  1436. break;
  1437. case 9 /* NodeTypes.Literal */:
  1438. generator.push(JSON.stringify(node.value), node);
  1439. break;
  1440. case 3 /* NodeTypes.Text */:
  1441. generator.push(JSON.stringify(node.value), node);
  1442. break;
  1443. default:
  1444. if ((process.env.NODE_ENV !== 'production')) {
  1445. throw createCompileError(CompileErrorCodes.UNHANDLED_CODEGEN_NODE_TYPE, null, {
  1446. domain: ERROR_DOMAIN,
  1447. args: [node.type]
  1448. });
  1449. }
  1450. }
  1451. }
  1452. // generate code from AST
  1453. const generate = (ast, options = {} // eslint-disable-line
  1454. ) => {
  1455. const mode = isString(options.mode) ? options.mode : 'normal';
  1456. const filename = isString(options.filename)
  1457. ? options.filename
  1458. : 'message.intl';
  1459. const sourceMap = !!options.sourceMap;
  1460. // prettier-ignore
  1461. const breakLineCode = options.breakLineCode != null
  1462. ? options.breakLineCode
  1463. : mode === 'arrow'
  1464. ? ';'
  1465. : '\n';
  1466. const needIndent = options.needIndent ? options.needIndent : mode !== 'arrow';
  1467. const helpers = ast.helpers || [];
  1468. const generator = createCodeGenerator(ast, {
  1469. mode,
  1470. filename,
  1471. sourceMap,
  1472. breakLineCode,
  1473. needIndent
  1474. });
  1475. generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
  1476. generator.indent(needIndent);
  1477. if (helpers.length > 0) {
  1478. generator.push(`const { ${join(helpers.map(s => `${s}: _${s}`), ', ')} } = ctx`);
  1479. generator.newline();
  1480. }
  1481. generator.push(`return `);
  1482. generateNode(generator, ast);
  1483. generator.deindent(needIndent);
  1484. generator.push(`}`);
  1485. delete ast.helpers;
  1486. const { code, map } = generator.context();
  1487. return {
  1488. ast,
  1489. code,
  1490. map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
  1491. };
  1492. };
  1493. function baseCompile(source, options = {}) {
  1494. const assignedOptions = assign({}, options);
  1495. const jit = !!assignedOptions.jit;
  1496. const enalbeMinify = !!assignedOptions.minify;
  1497. const enambeOptimize = assignedOptions.optimize == null ? true : assignedOptions.optimize;
  1498. // parse source codes
  1499. const parser = createParser(assignedOptions);
  1500. const ast = parser.parse(source);
  1501. if (!jit) {
  1502. // transform ASTs
  1503. transform(ast, assignedOptions);
  1504. // generate javascript codes
  1505. return generate(ast, assignedOptions);
  1506. }
  1507. else {
  1508. // optimize ASTs
  1509. enambeOptimize && optimize(ast);
  1510. // minimize ASTs
  1511. enalbeMinify && minify(ast);
  1512. // In JIT mode, no ast transform, no code generation.
  1513. return { ast, code: '' };
  1514. }
  1515. }
  1516. export { CompileErrorCodes, ERROR_DOMAIN$2 as ERROR_DOMAIN, LOCATION_STUB, baseCompile, createCompileError, createLocation, createParser, createPosition, defaultOnError, detectHtmlTag, errorMessages };