message-compiler.cjs 57 KB

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