message-compiler.global.js 50 KB

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