You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

escodegen.js 93KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620
  1. /*
  2. Copyright (C) 2012-2014 Yusuke Suzuki <utatane.tea@gmail.com>
  3. Copyright (C) 2015 Ingvar Stepanyan <me@rreverser.com>
  4. Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com>
  5. Copyright (C) 2012-2013 Michael Ficarra <escodegen.copyright@michael.ficarra.me>
  6. Copyright (C) 2012-2013 Mathias Bynens <mathias@qiwi.be>
  7. Copyright (C) 2013 Irakli Gozalishvili <rfobic@gmail.com>
  8. Copyright (C) 2012 Robert Gust-Bardon <donate@robert.gust-bardon.org>
  9. Copyright (C) 2012 John Freeman <jfreeman08@gmail.com>
  10. Copyright (C) 2011-2012 Ariya Hidayat <ariya.hidayat@gmail.com>
  11. Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
  12. Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
  13. Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
  14. Redistribution and use in source and binary forms, with or without
  15. modification, are permitted provided that the following conditions are met:
  16. * Redistributions of source code must retain the above copyright
  17. notice, this list of conditions and the following disclaimer.
  18. * Redistributions in binary form must reproduce the above copyright
  19. notice, this list of conditions and the following disclaimer in the
  20. documentation and/or other materials provided with the distribution.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  22. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  23. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  24. ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  25. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  26. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  27. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  28. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  30. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. */
  32. /*global exports:true, require:true, global:true*/
  33. (function () {
  34. 'use strict';
  35. var Syntax,
  36. Precedence,
  37. BinaryPrecedence,
  38. SourceNode,
  39. estraverse,
  40. esutils,
  41. base,
  42. indent,
  43. json,
  44. renumber,
  45. hexadecimal,
  46. quotes,
  47. escapeless,
  48. newline,
  49. space,
  50. parentheses,
  51. semicolons,
  52. safeConcatenation,
  53. directive,
  54. extra,
  55. parse,
  56. sourceMap,
  57. sourceCode,
  58. preserveBlankLines,
  59. FORMAT_MINIFY,
  60. FORMAT_DEFAULTS;
  61. estraverse = require('estraverse');
  62. esutils = require('esutils');
  63. Syntax = estraverse.Syntax;
  64. // Generation is done by generateExpression.
  65. function isExpression(node) {
  66. return CodeGenerator.Expression.hasOwnProperty(node.type);
  67. }
  68. // Generation is done by generateStatement.
  69. function isStatement(node) {
  70. return CodeGenerator.Statement.hasOwnProperty(node.type);
  71. }
  72. Precedence = {
  73. Sequence: 0,
  74. Yield: 1,
  75. Assignment: 1,
  76. Conditional: 2,
  77. ArrowFunction: 2,
  78. LogicalOR: 3,
  79. LogicalAND: 4,
  80. BitwiseOR: 5,
  81. BitwiseXOR: 6,
  82. BitwiseAND: 7,
  83. Equality: 8,
  84. Relational: 9,
  85. BitwiseSHIFT: 10,
  86. Additive: 11,
  87. Multiplicative: 12,
  88. Exponentiation: 13,
  89. Await: 14,
  90. Unary: 14,
  91. Postfix: 15,
  92. Call: 16,
  93. New: 17,
  94. TaggedTemplate: 18,
  95. Member: 19,
  96. Primary: 20
  97. };
  98. BinaryPrecedence = {
  99. '||': Precedence.LogicalOR,
  100. '&&': Precedence.LogicalAND,
  101. '|': Precedence.BitwiseOR,
  102. '^': Precedence.BitwiseXOR,
  103. '&': Precedence.BitwiseAND,
  104. '==': Precedence.Equality,
  105. '!=': Precedence.Equality,
  106. '===': Precedence.Equality,
  107. '!==': Precedence.Equality,
  108. 'is': Precedence.Equality,
  109. 'isnt': Precedence.Equality,
  110. '<': Precedence.Relational,
  111. '>': Precedence.Relational,
  112. '<=': Precedence.Relational,
  113. '>=': Precedence.Relational,
  114. 'in': Precedence.Relational,
  115. 'instanceof': Precedence.Relational,
  116. '<<': Precedence.BitwiseSHIFT,
  117. '>>': Precedence.BitwiseSHIFT,
  118. '>>>': Precedence.BitwiseSHIFT,
  119. '+': Precedence.Additive,
  120. '-': Precedence.Additive,
  121. '*': Precedence.Multiplicative,
  122. '%': Precedence.Multiplicative,
  123. '/': Precedence.Multiplicative,
  124. '**': Precedence.Exponentiation
  125. };
  126. //Flags
  127. var F_ALLOW_IN = 1,
  128. F_ALLOW_CALL = 1 << 1,
  129. F_ALLOW_UNPARATH_NEW = 1 << 2,
  130. F_FUNC_BODY = 1 << 3,
  131. F_DIRECTIVE_CTX = 1 << 4,
  132. F_SEMICOLON_OPT = 1 << 5;
  133. //Expression flag sets
  134. //NOTE: Flag order:
  135. // F_ALLOW_IN
  136. // F_ALLOW_CALL
  137. // F_ALLOW_UNPARATH_NEW
  138. var E_FTT = F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW,
  139. E_TTF = F_ALLOW_IN | F_ALLOW_CALL,
  140. E_TTT = F_ALLOW_IN | F_ALLOW_CALL | F_ALLOW_UNPARATH_NEW,
  141. E_TFF = F_ALLOW_IN,
  142. E_FFT = F_ALLOW_UNPARATH_NEW,
  143. E_TFT = F_ALLOW_IN | F_ALLOW_UNPARATH_NEW;
  144. //Statement flag sets
  145. //NOTE: Flag order:
  146. // F_ALLOW_IN
  147. // F_FUNC_BODY
  148. // F_DIRECTIVE_CTX
  149. // F_SEMICOLON_OPT
  150. var S_TFFF = F_ALLOW_IN,
  151. S_TFFT = F_ALLOW_IN | F_SEMICOLON_OPT,
  152. S_FFFF = 0x00,
  153. S_TFTF = F_ALLOW_IN | F_DIRECTIVE_CTX,
  154. S_TTFF = F_ALLOW_IN | F_FUNC_BODY;
  155. function getDefaultOptions() {
  156. // default options
  157. return {
  158. indent: null,
  159. base: null,
  160. parse: null,
  161. comment: false,
  162. format: {
  163. indent: {
  164. style: ' ',
  165. base: 0,
  166. adjustMultilineComment: false
  167. },
  168. newline: '\n',
  169. space: ' ',
  170. json: false,
  171. renumber: false,
  172. hexadecimal: false,
  173. quotes: 'single',
  174. escapeless: false,
  175. compact: false,
  176. parentheses: true,
  177. semicolons: true,
  178. safeConcatenation: false,
  179. preserveBlankLines: false
  180. },
  181. moz: {
  182. comprehensionExpressionStartsWithAssignment: false,
  183. starlessGenerator: false
  184. },
  185. sourceMap: null,
  186. sourceMapRoot: null,
  187. sourceMapWithCode: false,
  188. directive: false,
  189. raw: true,
  190. verbatim: null,
  191. sourceCode: null
  192. };
  193. }
  194. function stringRepeat(str, num) {
  195. var result = '';
  196. for (num |= 0; num > 0; num >>>= 1, str += str) {
  197. if (num & 1) {
  198. result += str;
  199. }
  200. }
  201. return result;
  202. }
  203. function hasLineTerminator(str) {
  204. return (/[\r\n]/g).test(str);
  205. }
  206. function endsWithLineTerminator(str) {
  207. var len = str.length;
  208. return len && esutils.code.isLineTerminator(str.charCodeAt(len - 1));
  209. }
  210. function merge(target, override) {
  211. var key;
  212. for (key in override) {
  213. if (override.hasOwnProperty(key)) {
  214. target[key] = override[key];
  215. }
  216. }
  217. return target;
  218. }
  219. function updateDeeply(target, override) {
  220. var key, val;
  221. function isHashObject(target) {
  222. return typeof target === 'object' && target instanceof Object && !(target instanceof RegExp);
  223. }
  224. for (key in override) {
  225. if (override.hasOwnProperty(key)) {
  226. val = override[key];
  227. if (isHashObject(val)) {
  228. if (isHashObject(target[key])) {
  229. updateDeeply(target[key], val);
  230. } else {
  231. target[key] = updateDeeply({}, val);
  232. }
  233. } else {
  234. target[key] = val;
  235. }
  236. }
  237. }
  238. return target;
  239. }
  240. function generateNumber(value) {
  241. var result, point, temp, exponent, pos;
  242. if (value !== value) {
  243. throw new Error('Numeric literal whose value is NaN');
  244. }
  245. if (value < 0 || (value === 0 && 1 / value < 0)) {
  246. throw new Error('Numeric literal whose value is negative');
  247. }
  248. if (value === 1 / 0) {
  249. return json ? 'null' : renumber ? '1e400' : '1e+400';
  250. }
  251. result = '' + value;
  252. if (!renumber || result.length < 3) {
  253. return result;
  254. }
  255. point = result.indexOf('.');
  256. if (!json && result.charCodeAt(0) === 0x30 /* 0 */ && point === 1) {
  257. point = 0;
  258. result = result.slice(1);
  259. }
  260. temp = result;
  261. result = result.replace('e+', 'e');
  262. exponent = 0;
  263. if ((pos = temp.indexOf('e')) > 0) {
  264. exponent = +temp.slice(pos + 1);
  265. temp = temp.slice(0, pos);
  266. }
  267. if (point >= 0) {
  268. exponent -= temp.length - point - 1;
  269. temp = +(temp.slice(0, point) + temp.slice(point + 1)) + '';
  270. }
  271. pos = 0;
  272. while (temp.charCodeAt(temp.length + pos - 1) === 0x30 /* 0 */) {
  273. --pos;
  274. }
  275. if (pos !== 0) {
  276. exponent -= pos;
  277. temp = temp.slice(0, pos);
  278. }
  279. if (exponent !== 0) {
  280. temp += 'e' + exponent;
  281. }
  282. if ((temp.length < result.length ||
  283. (hexadecimal && value > 1e12 && Math.floor(value) === value && (temp = '0x' + value.toString(16)).length < result.length)) &&
  284. +temp === value) {
  285. result = temp;
  286. }
  287. return result;
  288. }
  289. // Generate valid RegExp expression.
  290. // This function is based on https://github.com/Constellation/iv Engine
  291. function escapeRegExpCharacter(ch, previousIsBackslash) {
  292. // not handling '\' and handling \u2028 or \u2029 to unicode escape sequence
  293. if ((ch & ~1) === 0x2028) {
  294. return (previousIsBackslash ? 'u' : '\\u') + ((ch === 0x2028) ? '2028' : '2029');
  295. } else if (ch === 10 || ch === 13) { // \n, \r
  296. return (previousIsBackslash ? '' : '\\') + ((ch === 10) ? 'n' : 'r');
  297. }
  298. return String.fromCharCode(ch);
  299. }
  300. function generateRegExp(reg) {
  301. var match, result, flags, i, iz, ch, characterInBrack, previousIsBackslash;
  302. result = reg.toString();
  303. if (reg.source) {
  304. // extract flag from toString result
  305. match = result.match(/\/([^/]*)$/);
  306. if (!match) {
  307. return result;
  308. }
  309. flags = match[1];
  310. result = '';
  311. characterInBrack = false;
  312. previousIsBackslash = false;
  313. for (i = 0, iz = reg.source.length; i < iz; ++i) {
  314. ch = reg.source.charCodeAt(i);
  315. if (!previousIsBackslash) {
  316. if (characterInBrack) {
  317. if (ch === 93) { // ]
  318. characterInBrack = false;
  319. }
  320. } else {
  321. if (ch === 47) { // /
  322. result += '\\';
  323. } else if (ch === 91) { // [
  324. characterInBrack = true;
  325. }
  326. }
  327. result += escapeRegExpCharacter(ch, previousIsBackslash);
  328. previousIsBackslash = ch === 92; // \
  329. } else {
  330. // if new RegExp("\\\n') is provided, create /\n/
  331. result += escapeRegExpCharacter(ch, previousIsBackslash);
  332. // prevent like /\\[/]/
  333. previousIsBackslash = false;
  334. }
  335. }
  336. return '/' + result + '/' + flags;
  337. }
  338. return result;
  339. }
  340. function escapeAllowedCharacter(code, next) {
  341. var hex;
  342. if (code === 0x08 /* \b */) {
  343. return '\\b';
  344. }
  345. if (code === 0x0C /* \f */) {
  346. return '\\f';
  347. }
  348. if (code === 0x09 /* \t */) {
  349. return '\\t';
  350. }
  351. hex = code.toString(16).toUpperCase();
  352. if (json || code > 0xFF) {
  353. return '\\u' + '0000'.slice(hex.length) + hex;
  354. } else if (code === 0x0000 && !esutils.code.isDecimalDigit(next)) {
  355. return '\\0';
  356. } else if (code === 0x000B /* \v */) { // '\v'
  357. return '\\x0B';
  358. } else {
  359. return '\\x' + '00'.slice(hex.length) + hex;
  360. }
  361. }
  362. function escapeDisallowedCharacter(code) {
  363. if (code === 0x5C /* \ */) {
  364. return '\\\\';
  365. }
  366. if (code === 0x0A /* \n */) {
  367. return '\\n';
  368. }
  369. if (code === 0x0D /* \r */) {
  370. return '\\r';
  371. }
  372. if (code === 0x2028) {
  373. return '\\u2028';
  374. }
  375. if (code === 0x2029) {
  376. return '\\u2029';
  377. }
  378. throw new Error('Incorrectly classified character');
  379. }
  380. function escapeDirective(str) {
  381. var i, iz, code, quote;
  382. quote = quotes === 'double' ? '"' : '\'';
  383. for (i = 0, iz = str.length; i < iz; ++i) {
  384. code = str.charCodeAt(i);
  385. if (code === 0x27 /* ' */) {
  386. quote = '"';
  387. break;
  388. } else if (code === 0x22 /* " */) {
  389. quote = '\'';
  390. break;
  391. } else if (code === 0x5C /* \ */) {
  392. ++i;
  393. }
  394. }
  395. return quote + str + quote;
  396. }
  397. function escapeString(str) {
  398. var result = '', i, len, code, singleQuotes = 0, doubleQuotes = 0, single, quote;
  399. for (i = 0, len = str.length; i < len; ++i) {
  400. code = str.charCodeAt(i);
  401. if (code === 0x27 /* ' */) {
  402. ++singleQuotes;
  403. } else if (code === 0x22 /* " */) {
  404. ++doubleQuotes;
  405. } else if (code === 0x2F /* / */ && json) {
  406. result += '\\';
  407. } else if (esutils.code.isLineTerminator(code) || code === 0x5C /* \ */) {
  408. result += escapeDisallowedCharacter(code);
  409. continue;
  410. } else if (!esutils.code.isIdentifierPartES5(code) && (json && code < 0x20 /* SP */ || !json && !escapeless && (code < 0x20 /* SP */ || code > 0x7E /* ~ */))) {
  411. result += escapeAllowedCharacter(code, str.charCodeAt(i + 1));
  412. continue;
  413. }
  414. result += String.fromCharCode(code);
  415. }
  416. single = !(quotes === 'double' || (quotes === 'auto' && doubleQuotes < singleQuotes));
  417. quote = single ? '\'' : '"';
  418. if (!(single ? singleQuotes : doubleQuotes)) {
  419. return quote + result + quote;
  420. }
  421. str = result;
  422. result = quote;
  423. for (i = 0, len = str.length; i < len; ++i) {
  424. code = str.charCodeAt(i);
  425. if ((code === 0x27 /* ' */ && single) || (code === 0x22 /* " */ && !single)) {
  426. result += '\\';
  427. }
  428. result += String.fromCharCode(code);
  429. }
  430. return result + quote;
  431. }
  432. /**
  433. * flatten an array to a string, where the array can contain
  434. * either strings or nested arrays
  435. */
  436. function flattenToString(arr) {
  437. var i, iz, elem, result = '';
  438. for (i = 0, iz = arr.length; i < iz; ++i) {
  439. elem = arr[i];
  440. result += Array.isArray(elem) ? flattenToString(elem) : elem;
  441. }
  442. return result;
  443. }
  444. /**
  445. * convert generated to a SourceNode when source maps are enabled.
  446. */
  447. function toSourceNodeWhenNeeded(generated, node) {
  448. if (!sourceMap) {
  449. // with no source maps, generated is either an
  450. // array or a string. if an array, flatten it.
  451. // if a string, just return it
  452. if (Array.isArray(generated)) {
  453. return flattenToString(generated);
  454. } else {
  455. return generated;
  456. }
  457. }
  458. if (node == null) {
  459. if (generated instanceof SourceNode) {
  460. return generated;
  461. } else {
  462. node = {};
  463. }
  464. }
  465. if (node.loc == null) {
  466. return new SourceNode(null, null, sourceMap, generated, node.name || null);
  467. }
  468. return new SourceNode(node.loc.start.line, node.loc.start.column, (sourceMap === true ? node.loc.source || null : sourceMap), generated, node.name || null);
  469. }
  470. function noEmptySpace() {
  471. return (space) ? space : ' ';
  472. }
  473. function join(left, right) {
  474. var leftSource,
  475. rightSource,
  476. leftCharCode,
  477. rightCharCode;
  478. leftSource = toSourceNodeWhenNeeded(left).toString();
  479. if (leftSource.length === 0) {
  480. return [right];
  481. }
  482. rightSource = toSourceNodeWhenNeeded(right).toString();
  483. if (rightSource.length === 0) {
  484. return [left];
  485. }
  486. leftCharCode = leftSource.charCodeAt(leftSource.length - 1);
  487. rightCharCode = rightSource.charCodeAt(0);
  488. if ((leftCharCode === 0x2B /* + */ || leftCharCode === 0x2D /* - */) && leftCharCode === rightCharCode ||
  489. esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode) ||
  490. leftCharCode === 0x2F /* / */ && rightCharCode === 0x69 /* i */) { // infix word operators all start with `i`
  491. return [left, noEmptySpace(), right];
  492. } else if (esutils.code.isWhiteSpace(leftCharCode) || esutils.code.isLineTerminator(leftCharCode) ||
  493. esutils.code.isWhiteSpace(rightCharCode) || esutils.code.isLineTerminator(rightCharCode)) {
  494. return [left, right];
  495. }
  496. return [left, space, right];
  497. }
  498. function addIndent(stmt) {
  499. return [base, stmt];
  500. }
  501. function withIndent(fn) {
  502. var previousBase;
  503. previousBase = base;
  504. base += indent;
  505. fn(base);
  506. base = previousBase;
  507. }
  508. function calculateSpaces(str) {
  509. var i;
  510. for (i = str.length - 1; i >= 0; --i) {
  511. if (esutils.code.isLineTerminator(str.charCodeAt(i))) {
  512. break;
  513. }
  514. }
  515. return (str.length - 1) - i;
  516. }
  517. function adjustMultilineComment(value, specialBase) {
  518. var array, i, len, line, j, spaces, previousBase, sn;
  519. array = value.split(/\r\n|[\r\n]/);
  520. spaces = Number.MAX_VALUE;
  521. // first line doesn't have indentation
  522. for (i = 1, len = array.length; i < len; ++i) {
  523. line = array[i];
  524. j = 0;
  525. while (j < line.length && esutils.code.isWhiteSpace(line.charCodeAt(j))) {
  526. ++j;
  527. }
  528. if (spaces > j) {
  529. spaces = j;
  530. }
  531. }
  532. if (typeof specialBase !== 'undefined') {
  533. // pattern like
  534. // {
  535. // var t = 20; /*
  536. // * this is comment
  537. // */
  538. // }
  539. previousBase = base;
  540. if (array[1][spaces] === '*') {
  541. specialBase += ' ';
  542. }
  543. base = specialBase;
  544. } else {
  545. if (spaces & 1) {
  546. // /*
  547. // *
  548. // */
  549. // If spaces are odd number, above pattern is considered.
  550. // We waste 1 space.
  551. --spaces;
  552. }
  553. previousBase = base;
  554. }
  555. for (i = 1, len = array.length; i < len; ++i) {
  556. sn = toSourceNodeWhenNeeded(addIndent(array[i].slice(spaces)));
  557. array[i] = sourceMap ? sn.join('') : sn;
  558. }
  559. base = previousBase;
  560. return array.join('\n');
  561. }
  562. function generateComment(comment, specialBase) {
  563. if (comment.type === 'Line') {
  564. if (endsWithLineTerminator(comment.value)) {
  565. return '//' + comment.value;
  566. } else {
  567. // Always use LineTerminator
  568. var result = '//' + comment.value;
  569. if (!preserveBlankLines) {
  570. result += '\n';
  571. }
  572. return result;
  573. }
  574. }
  575. if (extra.format.indent.adjustMultilineComment && /[\n\r]/.test(comment.value)) {
  576. return adjustMultilineComment('/*' + comment.value + '*/', specialBase);
  577. }
  578. return '/*' + comment.value + '*/';
  579. }
  580. function addComments(stmt, result) {
  581. var i, len, comment, save, tailingToStatement, specialBase, fragment,
  582. extRange, range, prevRange, prefix, infix, suffix, count;
  583. if (stmt.leadingComments && stmt.leadingComments.length > 0) {
  584. save = result;
  585. if (preserveBlankLines) {
  586. comment = stmt.leadingComments[0];
  587. result = [];
  588. extRange = comment.extendedRange;
  589. range = comment.range;
  590. prefix = sourceCode.substring(extRange[0], range[0]);
  591. count = (prefix.match(/\n/g) || []).length;
  592. if (count > 0) {
  593. result.push(stringRepeat('\n', count));
  594. result.push(addIndent(generateComment(comment)));
  595. } else {
  596. result.push(prefix);
  597. result.push(generateComment(comment));
  598. }
  599. prevRange = range;
  600. for (i = 1, len = stmt.leadingComments.length; i < len; i++) {
  601. comment = stmt.leadingComments[i];
  602. range = comment.range;
  603. infix = sourceCode.substring(prevRange[1], range[0]);
  604. count = (infix.match(/\n/g) || []).length;
  605. result.push(stringRepeat('\n', count));
  606. result.push(addIndent(generateComment(comment)));
  607. prevRange = range;
  608. }
  609. suffix = sourceCode.substring(range[1], extRange[1]);
  610. count = (suffix.match(/\n/g) || []).length;
  611. result.push(stringRepeat('\n', count));
  612. } else {
  613. comment = stmt.leadingComments[0];
  614. result = [];
  615. if (safeConcatenation && stmt.type === Syntax.Program && stmt.body.length === 0) {
  616. result.push('\n');
  617. }
  618. result.push(generateComment(comment));
  619. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  620. result.push('\n');
  621. }
  622. for (i = 1, len = stmt.leadingComments.length; i < len; ++i) {
  623. comment = stmt.leadingComments[i];
  624. fragment = [generateComment(comment)];
  625. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  626. fragment.push('\n');
  627. }
  628. result.push(addIndent(fragment));
  629. }
  630. }
  631. result.push(addIndent(save));
  632. }
  633. if (stmt.trailingComments) {
  634. if (preserveBlankLines) {
  635. comment = stmt.trailingComments[0];
  636. extRange = comment.extendedRange;
  637. range = comment.range;
  638. prefix = sourceCode.substring(extRange[0], range[0]);
  639. count = (prefix.match(/\n/g) || []).length;
  640. if (count > 0) {
  641. result.push(stringRepeat('\n', count));
  642. result.push(addIndent(generateComment(comment)));
  643. } else {
  644. result.push(prefix);
  645. result.push(generateComment(comment));
  646. }
  647. } else {
  648. tailingToStatement = !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString());
  649. specialBase = stringRepeat(' ', calculateSpaces(toSourceNodeWhenNeeded([base, result, indent]).toString()));
  650. for (i = 0, len = stmt.trailingComments.length; i < len; ++i) {
  651. comment = stmt.trailingComments[i];
  652. if (tailingToStatement) {
  653. // We assume target like following script
  654. //
  655. // var t = 20; /**
  656. // * This is comment of t
  657. // */
  658. if (i === 0) {
  659. // first case
  660. result = [result, indent];
  661. } else {
  662. result = [result, specialBase];
  663. }
  664. result.push(generateComment(comment, specialBase));
  665. } else {
  666. result = [result, addIndent(generateComment(comment))];
  667. }
  668. if (i !== len - 1 && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  669. result = [result, '\n'];
  670. }
  671. }
  672. }
  673. }
  674. return result;
  675. }
  676. function generateBlankLines(start, end, result) {
  677. var j, newlineCount = 0;
  678. for (j = start; j < end; j++) {
  679. if (sourceCode[j] === '\n') {
  680. newlineCount++;
  681. }
  682. }
  683. for (j = 1; j < newlineCount; j++) {
  684. result.push(newline);
  685. }
  686. }
  687. function parenthesize(text, current, should) {
  688. if (current < should) {
  689. return ['(', text, ')'];
  690. }
  691. return text;
  692. }
  693. function generateVerbatimString(string) {
  694. var i, iz, result;
  695. result = string.split(/\r\n|\n/);
  696. for (i = 1, iz = result.length; i < iz; i++) {
  697. result[i] = newline + base + result[i];
  698. }
  699. return result;
  700. }
  701. function generateVerbatim(expr, precedence) {
  702. var verbatim, result, prec;
  703. verbatim = expr[extra.verbatim];
  704. if (typeof verbatim === 'string') {
  705. result = parenthesize(generateVerbatimString(verbatim), Precedence.Sequence, precedence);
  706. } else {
  707. // verbatim is object
  708. result = generateVerbatimString(verbatim.content);
  709. prec = (verbatim.precedence != null) ? verbatim.precedence : Precedence.Sequence;
  710. result = parenthesize(result, prec, precedence);
  711. }
  712. return toSourceNodeWhenNeeded(result, expr);
  713. }
  714. function CodeGenerator() {
  715. }
  716. // Helpers.
  717. CodeGenerator.prototype.maybeBlock = function(stmt, flags) {
  718. var result, noLeadingComment, that = this;
  719. noLeadingComment = !extra.comment || !stmt.leadingComments;
  720. if (stmt.type === Syntax.BlockStatement && noLeadingComment) {
  721. return [space, this.generateStatement(stmt, flags)];
  722. }
  723. if (stmt.type === Syntax.EmptyStatement && noLeadingComment) {
  724. return ';';
  725. }
  726. withIndent(function () {
  727. result = [
  728. newline,
  729. addIndent(that.generateStatement(stmt, flags))
  730. ];
  731. });
  732. return result;
  733. };
  734. CodeGenerator.prototype.maybeBlockSuffix = function (stmt, result) {
  735. var ends = endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString());
  736. if (stmt.type === Syntax.BlockStatement && (!extra.comment || !stmt.leadingComments) && !ends) {
  737. return [result, space];
  738. }
  739. if (ends) {
  740. return [result, base];
  741. }
  742. return [result, newline, base];
  743. };
  744. function generateIdentifier(node) {
  745. return toSourceNodeWhenNeeded(node.name, node);
  746. }
  747. function generateAsyncPrefix(node, spaceRequired) {
  748. return node.async ? 'async' + (spaceRequired ? noEmptySpace() : space) : '';
  749. }
  750. function generateStarSuffix(node) {
  751. var isGenerator = node.generator && !extra.moz.starlessGenerator;
  752. return isGenerator ? '*' + space : '';
  753. }
  754. function generateMethodPrefix(prop) {
  755. var func = prop.value, prefix = '';
  756. if (func.async) {
  757. prefix += generateAsyncPrefix(func, !prop.computed);
  758. }
  759. if (func.generator) {
  760. // avoid space before method name
  761. prefix += generateStarSuffix(func) ? '*' : '';
  762. }
  763. return prefix;
  764. }
  765. CodeGenerator.prototype.generatePattern = function (node, precedence, flags) {
  766. if (node.type === Syntax.Identifier) {
  767. return generateIdentifier(node);
  768. }
  769. return this.generateExpression(node, precedence, flags);
  770. };
  771. CodeGenerator.prototype.generateFunctionParams = function (node) {
  772. var i, iz, result, hasDefault;
  773. hasDefault = false;
  774. if (node.type === Syntax.ArrowFunctionExpression &&
  775. !node.rest && (!node.defaults || node.defaults.length === 0) &&
  776. node.params.length === 1 && node.params[0].type === Syntax.Identifier) {
  777. // arg => { } case
  778. result = [generateAsyncPrefix(node, true), generateIdentifier(node.params[0])];
  779. } else {
  780. result = node.type === Syntax.ArrowFunctionExpression ? [generateAsyncPrefix(node, false)] : [];
  781. result.push('(');
  782. if (node.defaults) {
  783. hasDefault = true;
  784. }
  785. for (i = 0, iz = node.params.length; i < iz; ++i) {
  786. if (hasDefault && node.defaults[i]) {
  787. // Handle default values.
  788. result.push(this.generateAssignment(node.params[i], node.defaults[i], '=', Precedence.Assignment, E_TTT));
  789. } else {
  790. result.push(this.generatePattern(node.params[i], Precedence.Assignment, E_TTT));
  791. }
  792. if (i + 1 < iz) {
  793. result.push(',' + space);
  794. }
  795. }
  796. if (node.rest) {
  797. if (node.params.length) {
  798. result.push(',' + space);
  799. }
  800. result.push('...');
  801. result.push(generateIdentifier(node.rest));
  802. }
  803. result.push(')');
  804. }
  805. return result;
  806. };
  807. CodeGenerator.prototype.generateFunctionBody = function (node) {
  808. var result, expr;
  809. result = this.generateFunctionParams(node);
  810. if (node.type === Syntax.ArrowFunctionExpression) {
  811. result.push(space);
  812. result.push('=>');
  813. }
  814. if (node.expression) {
  815. result.push(space);
  816. expr = this.generateExpression(node.body, Precedence.Assignment, E_TTT);
  817. if (expr.toString().charAt(0) === '{') {
  818. expr = ['(', expr, ')'];
  819. }
  820. result.push(expr);
  821. } else {
  822. result.push(this.maybeBlock(node.body, S_TTFF));
  823. }
  824. return result;
  825. };
  826. CodeGenerator.prototype.generateIterationForStatement = function (operator, stmt, flags) {
  827. var result = ['for' + (stmt.await ? noEmptySpace() + 'await' : '') + space + '('], that = this;
  828. withIndent(function () {
  829. if (stmt.left.type === Syntax.VariableDeclaration) {
  830. withIndent(function () {
  831. result.push(stmt.left.kind + noEmptySpace());
  832. result.push(that.generateStatement(stmt.left.declarations[0], S_FFFF));
  833. });
  834. } else {
  835. result.push(that.generateExpression(stmt.left, Precedence.Call, E_TTT));
  836. }
  837. result = join(result, operator);
  838. result = [join(
  839. result,
  840. that.generateExpression(stmt.right, Precedence.Assignment, E_TTT)
  841. ), ')'];
  842. });
  843. result.push(this.maybeBlock(stmt.body, flags));
  844. return result;
  845. };
  846. CodeGenerator.prototype.generatePropertyKey = function (expr, computed) {
  847. var result = [];
  848. if (computed) {
  849. result.push('[');
  850. }
  851. result.push(this.generateExpression(expr, Precedence.Sequence, E_TTT));
  852. if (computed) {
  853. result.push(']');
  854. }
  855. return result;
  856. };
  857. CodeGenerator.prototype.generateAssignment = function (left, right, operator, precedence, flags) {
  858. if (Precedence.Assignment < precedence) {
  859. flags |= F_ALLOW_IN;
  860. }
  861. return parenthesize(
  862. [
  863. this.generateExpression(left, Precedence.Call, flags),
  864. space + operator + space,
  865. this.generateExpression(right, Precedence.Assignment, flags)
  866. ],
  867. Precedence.Assignment,
  868. precedence
  869. );
  870. };
  871. CodeGenerator.prototype.semicolon = function (flags) {
  872. if (!semicolons && flags & F_SEMICOLON_OPT) {
  873. return '';
  874. }
  875. return ';';
  876. };
  877. // Statements.
  878. CodeGenerator.Statement = {
  879. BlockStatement: function (stmt, flags) {
  880. var range, content, result = ['{', newline], that = this;
  881. withIndent(function () {
  882. // handle functions without any code
  883. if (stmt.body.length === 0 && preserveBlankLines) {
  884. range = stmt.range;
  885. if (range[1] - range[0] > 2) {
  886. content = sourceCode.substring(range[0] + 1, range[1] - 1);
  887. if (content[0] === '\n') {
  888. result = ['{'];
  889. }
  890. result.push(content);
  891. }
  892. }
  893. var i, iz, fragment, bodyFlags;
  894. bodyFlags = S_TFFF;
  895. if (flags & F_FUNC_BODY) {
  896. bodyFlags |= F_DIRECTIVE_CTX;
  897. }
  898. for (i = 0, iz = stmt.body.length; i < iz; ++i) {
  899. if (preserveBlankLines) {
  900. // handle spaces before the first line
  901. if (i === 0) {
  902. if (stmt.body[0].leadingComments) {
  903. range = stmt.body[0].leadingComments[0].extendedRange;
  904. content = sourceCode.substring(range[0], range[1]);
  905. if (content[0] === '\n') {
  906. result = ['{'];
  907. }
  908. }
  909. if (!stmt.body[0].leadingComments) {
  910. generateBlankLines(stmt.range[0], stmt.body[0].range[0], result);
  911. }
  912. }
  913. // handle spaces between lines
  914. if (i > 0) {
  915. if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) {
  916. generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result);
  917. }
  918. }
  919. }
  920. if (i === iz - 1) {
  921. bodyFlags |= F_SEMICOLON_OPT;
  922. }
  923. if (stmt.body[i].leadingComments && preserveBlankLines) {
  924. fragment = that.generateStatement(stmt.body[i], bodyFlags);
  925. } else {
  926. fragment = addIndent(that.generateStatement(stmt.body[i], bodyFlags));
  927. }
  928. result.push(fragment);
  929. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  930. if (preserveBlankLines && i < iz - 1) {
  931. // don't add a new line if there are leading coments
  932. // in the next statement
  933. if (!stmt.body[i + 1].leadingComments) {
  934. result.push(newline);
  935. }
  936. } else {
  937. result.push(newline);
  938. }
  939. }
  940. if (preserveBlankLines) {
  941. // handle spaces after the last line
  942. if (i === iz - 1) {
  943. if (!stmt.body[i].trailingComments) {
  944. generateBlankLines(stmt.body[i].range[1], stmt.range[1], result);
  945. }
  946. }
  947. }
  948. }
  949. });
  950. result.push(addIndent('}'));
  951. return result;
  952. },
  953. BreakStatement: function (stmt, flags) {
  954. if (stmt.label) {
  955. return 'break ' + stmt.label.name + this.semicolon(flags);
  956. }
  957. return 'break' + this.semicolon(flags);
  958. },
  959. ContinueStatement: function (stmt, flags) {
  960. if (stmt.label) {
  961. return 'continue ' + stmt.label.name + this.semicolon(flags);
  962. }
  963. return 'continue' + this.semicolon(flags);
  964. },
  965. ClassBody: function (stmt, flags) {
  966. var result = [ '{', newline], that = this;
  967. withIndent(function (indent) {
  968. var i, iz;
  969. for (i = 0, iz = stmt.body.length; i < iz; ++i) {
  970. result.push(indent);
  971. result.push(that.generateExpression(stmt.body[i], Precedence.Sequence, E_TTT));
  972. if (i + 1 < iz) {
  973. result.push(newline);
  974. }
  975. }
  976. });
  977. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  978. result.push(newline);
  979. }
  980. result.push(base);
  981. result.push('}');
  982. return result;
  983. },
  984. ClassDeclaration: function (stmt, flags) {
  985. var result, fragment;
  986. result = ['class'];
  987. if (stmt.id) {
  988. result = join(result, this.generateExpression(stmt.id, Precedence.Sequence, E_TTT));
  989. }
  990. if (stmt.superClass) {
  991. fragment = join('extends', this.generateExpression(stmt.superClass, Precedence.Unary, E_TTT));
  992. result = join(result, fragment);
  993. }
  994. result.push(space);
  995. result.push(this.generateStatement(stmt.body, S_TFFT));
  996. return result;
  997. },
  998. DirectiveStatement: function (stmt, flags) {
  999. if (extra.raw && stmt.raw) {
  1000. return stmt.raw + this.semicolon(flags);
  1001. }
  1002. return escapeDirective(stmt.directive) + this.semicolon(flags);
  1003. },
  1004. DoWhileStatement: function (stmt, flags) {
  1005. // Because `do 42 while (cond)` is Syntax Error. We need semicolon.
  1006. var result = join('do', this.maybeBlock(stmt.body, S_TFFF));
  1007. result = this.maybeBlockSuffix(stmt.body, result);
  1008. return join(result, [
  1009. 'while' + space + '(',
  1010. this.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
  1011. ')' + this.semicolon(flags)
  1012. ]);
  1013. },
  1014. CatchClause: function (stmt, flags) {
  1015. var result, that = this;
  1016. withIndent(function () {
  1017. var guard;
  1018. if (stmt.param) {
  1019. result = [
  1020. 'catch' + space + '(',
  1021. that.generateExpression(stmt.param, Precedence.Sequence, E_TTT),
  1022. ')'
  1023. ];
  1024. if (stmt.guard) {
  1025. guard = that.generateExpression(stmt.guard, Precedence.Sequence, E_TTT);
  1026. result.splice(2, 0, ' if ', guard);
  1027. }
  1028. } else {
  1029. result = ['catch'];
  1030. }
  1031. });
  1032. result.push(this.maybeBlock(stmt.body, S_TFFF));
  1033. return result;
  1034. },
  1035. DebuggerStatement: function (stmt, flags) {
  1036. return 'debugger' + this.semicolon(flags);
  1037. },
  1038. EmptyStatement: function (stmt, flags) {
  1039. return ';';
  1040. },
  1041. ExportDefaultDeclaration: function (stmt, flags) {
  1042. var result = [ 'export' ], bodyFlags;
  1043. bodyFlags = (flags & F_SEMICOLON_OPT) ? S_TFFT : S_TFFF;
  1044. // export default HoistableDeclaration[Default]
  1045. // export default AssignmentExpression[In] ;
  1046. result = join(result, 'default');
  1047. if (isStatement(stmt.declaration)) {
  1048. result = join(result, this.generateStatement(stmt.declaration, bodyFlags));
  1049. } else {
  1050. result = join(result, this.generateExpression(stmt.declaration, Precedence.Assignment, E_TTT) + this.semicolon(flags));
  1051. }
  1052. return result;
  1053. },
  1054. ExportNamedDeclaration: function (stmt, flags) {
  1055. var result = [ 'export' ], bodyFlags, that = this;
  1056. bodyFlags = (flags & F_SEMICOLON_OPT) ? S_TFFT : S_TFFF;
  1057. // export VariableStatement
  1058. // export Declaration[Default]
  1059. if (stmt.declaration) {
  1060. return join(result, this.generateStatement(stmt.declaration, bodyFlags));
  1061. }
  1062. // export ExportClause[NoReference] FromClause ;
  1063. // export ExportClause ;
  1064. if (stmt.specifiers) {
  1065. if (stmt.specifiers.length === 0) {
  1066. result = join(result, '{' + space + '}');
  1067. } else if (stmt.specifiers[0].type === Syntax.ExportBatchSpecifier) {
  1068. result = join(result, this.generateExpression(stmt.specifiers[0], Precedence.Sequence, E_TTT));
  1069. } else {
  1070. result = join(result, '{');
  1071. withIndent(function (indent) {
  1072. var i, iz;
  1073. result.push(newline);
  1074. for (i = 0, iz = stmt.specifiers.length; i < iz; ++i) {
  1075. result.push(indent);
  1076. result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT));
  1077. if (i + 1 < iz) {
  1078. result.push(',' + newline);
  1079. }
  1080. }
  1081. });
  1082. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  1083. result.push(newline);
  1084. }
  1085. result.push(base + '}');
  1086. }
  1087. if (stmt.source) {
  1088. result = join(result, [
  1089. 'from' + space,
  1090. // ModuleSpecifier
  1091. this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
  1092. this.semicolon(flags)
  1093. ]);
  1094. } else {
  1095. result.push(this.semicolon(flags));
  1096. }
  1097. }
  1098. return result;
  1099. },
  1100. ExportAllDeclaration: function (stmt, flags) {
  1101. // export * FromClause ;
  1102. return [
  1103. 'export' + space,
  1104. '*' + space,
  1105. 'from' + space,
  1106. // ModuleSpecifier
  1107. this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
  1108. this.semicolon(flags)
  1109. ];
  1110. },
  1111. ExpressionStatement: function (stmt, flags) {
  1112. var result, fragment;
  1113. function isClassPrefixed(fragment) {
  1114. var code;
  1115. if (fragment.slice(0, 5) !== 'class') {
  1116. return false;
  1117. }
  1118. code = fragment.charCodeAt(5);
  1119. return code === 0x7B /* '{' */ || esutils.code.isWhiteSpace(code) || esutils.code.isLineTerminator(code);
  1120. }
  1121. function isFunctionPrefixed(fragment) {
  1122. var code;
  1123. if (fragment.slice(0, 8) !== 'function') {
  1124. return false;
  1125. }
  1126. code = fragment.charCodeAt(8);
  1127. return code === 0x28 /* '(' */ || esutils.code.isWhiteSpace(code) || code === 0x2A /* '*' */ || esutils.code.isLineTerminator(code);
  1128. }
  1129. function isAsyncPrefixed(fragment) {
  1130. var code, i, iz;
  1131. if (fragment.slice(0, 5) !== 'async') {
  1132. return false;
  1133. }
  1134. if (!esutils.code.isWhiteSpace(fragment.charCodeAt(5))) {
  1135. return false;
  1136. }
  1137. for (i = 6, iz = fragment.length; i < iz; ++i) {
  1138. if (!esutils.code.isWhiteSpace(fragment.charCodeAt(i))) {
  1139. break;
  1140. }
  1141. }
  1142. if (i === iz) {
  1143. return false;
  1144. }
  1145. if (fragment.slice(i, i + 8) !== 'function') {
  1146. return false;
  1147. }
  1148. code = fragment.charCodeAt(i + 8);
  1149. return code === 0x28 /* '(' */ || esutils.code.isWhiteSpace(code) || code === 0x2A /* '*' */ || esutils.code.isLineTerminator(code);
  1150. }
  1151. result = [this.generateExpression(stmt.expression, Precedence.Sequence, E_TTT)];
  1152. // 12.4 '{', 'function', 'class' is not allowed in this position.
  1153. // wrap expression with parentheses
  1154. fragment = toSourceNodeWhenNeeded(result).toString();
  1155. if (fragment.charCodeAt(0) === 0x7B /* '{' */ || // ObjectExpression
  1156. isClassPrefixed(fragment) ||
  1157. isFunctionPrefixed(fragment) ||
  1158. isAsyncPrefixed(fragment) ||
  1159. (directive && (flags & F_DIRECTIVE_CTX) && stmt.expression.type === Syntax.Literal && typeof stmt.expression.value === 'string')) {
  1160. result = ['(', result, ')' + this.semicolon(flags)];
  1161. } else {
  1162. result.push(this.semicolon(flags));
  1163. }
  1164. return result;
  1165. },
  1166. ImportDeclaration: function (stmt, flags) {
  1167. // ES6: 15.2.1 valid import declarations:
  1168. // - import ImportClause FromClause ;
  1169. // - import ModuleSpecifier ;
  1170. var result, cursor, that = this;
  1171. // If no ImportClause is present,
  1172. // this should be `import ModuleSpecifier` so skip `from`
  1173. // ModuleSpecifier is StringLiteral.
  1174. if (stmt.specifiers.length === 0) {
  1175. // import ModuleSpecifier ;
  1176. return [
  1177. 'import',
  1178. space,
  1179. // ModuleSpecifier
  1180. this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
  1181. this.semicolon(flags)
  1182. ];
  1183. }
  1184. // import ImportClause FromClause ;
  1185. result = [
  1186. 'import'
  1187. ];
  1188. cursor = 0;
  1189. // ImportedBinding
  1190. if (stmt.specifiers[cursor].type === Syntax.ImportDefaultSpecifier) {
  1191. result = join(result, [
  1192. this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)
  1193. ]);
  1194. ++cursor;
  1195. }
  1196. if (stmt.specifiers[cursor]) {
  1197. if (cursor !== 0) {
  1198. result.push(',');
  1199. }
  1200. if (stmt.specifiers[cursor].type === Syntax.ImportNamespaceSpecifier) {
  1201. // NameSpaceImport
  1202. result = join(result, [
  1203. space,
  1204. this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT)
  1205. ]);
  1206. } else {
  1207. // NamedImports
  1208. result.push(space + '{');
  1209. if ((stmt.specifiers.length - cursor) === 1) {
  1210. // import { ... } from "...";
  1211. result.push(space);
  1212. result.push(this.generateExpression(stmt.specifiers[cursor], Precedence.Sequence, E_TTT));
  1213. result.push(space + '}' + space);
  1214. } else {
  1215. // import {
  1216. // ...,
  1217. // ...,
  1218. // } from "...";
  1219. withIndent(function (indent) {
  1220. var i, iz;
  1221. result.push(newline);
  1222. for (i = cursor, iz = stmt.specifiers.length; i < iz; ++i) {
  1223. result.push(indent);
  1224. result.push(that.generateExpression(stmt.specifiers[i], Precedence.Sequence, E_TTT));
  1225. if (i + 1 < iz) {
  1226. result.push(',' + newline);
  1227. }
  1228. }
  1229. });
  1230. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  1231. result.push(newline);
  1232. }
  1233. result.push(base + '}' + space);
  1234. }
  1235. }
  1236. }
  1237. result = join(result, [
  1238. 'from' + space,
  1239. // ModuleSpecifier
  1240. this.generateExpression(stmt.source, Precedence.Sequence, E_TTT),
  1241. this.semicolon(flags)
  1242. ]);
  1243. return result;
  1244. },
  1245. VariableDeclarator: function (stmt, flags) {
  1246. var itemFlags = (flags & F_ALLOW_IN) ? E_TTT : E_FTT;
  1247. if (stmt.init) {
  1248. return [
  1249. this.generateExpression(stmt.id, Precedence.Assignment, itemFlags),
  1250. space,
  1251. '=',
  1252. space,
  1253. this.generateExpression(stmt.init, Precedence.Assignment, itemFlags)
  1254. ];
  1255. }
  1256. return this.generatePattern(stmt.id, Precedence.Assignment, itemFlags);
  1257. },
  1258. VariableDeclaration: function (stmt, flags) {
  1259. // VariableDeclarator is typed as Statement,
  1260. // but joined with comma (not LineTerminator).
  1261. // So if comment is attached to target node, we should specialize.
  1262. var result, i, iz, node, bodyFlags, that = this;
  1263. result = [ stmt.kind ];
  1264. bodyFlags = (flags & F_ALLOW_IN) ? S_TFFF : S_FFFF;
  1265. function block() {
  1266. node = stmt.declarations[0];
  1267. if (extra.comment && node.leadingComments) {
  1268. result.push('\n');
  1269. result.push(addIndent(that.generateStatement(node, bodyFlags)));
  1270. } else {
  1271. result.push(noEmptySpace());
  1272. result.push(that.generateStatement(node, bodyFlags));
  1273. }
  1274. for (i = 1, iz = stmt.declarations.length; i < iz; ++i) {
  1275. node = stmt.declarations[i];
  1276. if (extra.comment && node.leadingComments) {
  1277. result.push(',' + newline);
  1278. result.push(addIndent(that.generateStatement(node, bodyFlags)));
  1279. } else {
  1280. result.push(',' + space);
  1281. result.push(that.generateStatement(node, bodyFlags));
  1282. }
  1283. }
  1284. }
  1285. if (stmt.declarations.length > 1) {
  1286. withIndent(block);
  1287. } else {
  1288. block();
  1289. }
  1290. result.push(this.semicolon(flags));
  1291. return result;
  1292. },
  1293. ThrowStatement: function (stmt, flags) {
  1294. return [join(
  1295. 'throw',
  1296. this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT)
  1297. ), this.semicolon(flags)];
  1298. },
  1299. TryStatement: function (stmt, flags) {
  1300. var result, i, iz, guardedHandlers;
  1301. result = ['try', this.maybeBlock(stmt.block, S_TFFF)];
  1302. result = this.maybeBlockSuffix(stmt.block, result);
  1303. if (stmt.handlers) {
  1304. // old interface
  1305. for (i = 0, iz = stmt.handlers.length; i < iz; ++i) {
  1306. result = join(result, this.generateStatement(stmt.handlers[i], S_TFFF));
  1307. if (stmt.finalizer || i + 1 !== iz) {
  1308. result = this.maybeBlockSuffix(stmt.handlers[i].body, result);
  1309. }
  1310. }
  1311. } else {
  1312. guardedHandlers = stmt.guardedHandlers || [];
  1313. for (i = 0, iz = guardedHandlers.length; i < iz; ++i) {
  1314. result = join(result, this.generateStatement(guardedHandlers[i], S_TFFF));
  1315. if (stmt.finalizer || i + 1 !== iz) {
  1316. result = this.maybeBlockSuffix(guardedHandlers[i].body, result);
  1317. }
  1318. }
  1319. // new interface
  1320. if (stmt.handler) {
  1321. if (Array.isArray(stmt.handler)) {
  1322. for (i = 0, iz = stmt.handler.length; i < iz; ++i) {
  1323. result = join(result, this.generateStatement(stmt.handler[i], S_TFFF));
  1324. if (stmt.finalizer || i + 1 !== iz) {
  1325. result = this.maybeBlockSuffix(stmt.handler[i].body, result);
  1326. }
  1327. }
  1328. } else {
  1329. result = join(result, this.generateStatement(stmt.handler, S_TFFF));
  1330. if (stmt.finalizer) {
  1331. result = this.maybeBlockSuffix(stmt.handler.body, result);
  1332. }
  1333. }
  1334. }
  1335. }
  1336. if (stmt.finalizer) {
  1337. result = join(result, ['finally', this.maybeBlock(stmt.finalizer, S_TFFF)]);
  1338. }
  1339. return result;
  1340. },
  1341. SwitchStatement: function (stmt, flags) {
  1342. var result, fragment, i, iz, bodyFlags, that = this;
  1343. withIndent(function () {
  1344. result = [
  1345. 'switch' + space + '(',
  1346. that.generateExpression(stmt.discriminant, Precedence.Sequence, E_TTT),
  1347. ')' + space + '{' + newline
  1348. ];
  1349. });
  1350. if (stmt.cases) {
  1351. bodyFlags = S_TFFF;
  1352. for (i = 0, iz = stmt.cases.length; i < iz; ++i) {
  1353. if (i === iz - 1) {
  1354. bodyFlags |= F_SEMICOLON_OPT;
  1355. }
  1356. fragment = addIndent(this.generateStatement(stmt.cases[i], bodyFlags));
  1357. result.push(fragment);
  1358. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  1359. result.push(newline);
  1360. }
  1361. }
  1362. }
  1363. result.push(addIndent('}'));
  1364. return result;
  1365. },
  1366. SwitchCase: function (stmt, flags) {
  1367. var result, fragment, i, iz, bodyFlags, that = this;
  1368. withIndent(function () {
  1369. if (stmt.test) {
  1370. result = [
  1371. join('case', that.generateExpression(stmt.test, Precedence.Sequence, E_TTT)),
  1372. ':'
  1373. ];
  1374. } else {
  1375. result = ['default:'];
  1376. }
  1377. i = 0;
  1378. iz = stmt.consequent.length;
  1379. if (iz && stmt.consequent[0].type === Syntax.BlockStatement) {
  1380. fragment = that.maybeBlock(stmt.consequent[0], S_TFFF);
  1381. result.push(fragment);
  1382. i = 1;
  1383. }
  1384. if (i !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  1385. result.push(newline);
  1386. }
  1387. bodyFlags = S_TFFF;
  1388. for (; i < iz; ++i) {
  1389. if (i === iz - 1 && flags & F_SEMICOLON_OPT) {
  1390. bodyFlags |= F_SEMICOLON_OPT;
  1391. }
  1392. fragment = addIndent(that.generateStatement(stmt.consequent[i], bodyFlags));
  1393. result.push(fragment);
  1394. if (i + 1 !== iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  1395. result.push(newline);
  1396. }
  1397. }
  1398. });
  1399. return result;
  1400. },
  1401. IfStatement: function (stmt, flags) {
  1402. var result, bodyFlags, semicolonOptional, that = this;
  1403. withIndent(function () {
  1404. result = [
  1405. 'if' + space + '(',
  1406. that.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
  1407. ')'
  1408. ];
  1409. });
  1410. semicolonOptional = flags & F_SEMICOLON_OPT;
  1411. bodyFlags = S_TFFF;
  1412. if (semicolonOptional) {
  1413. bodyFlags |= F_SEMICOLON_OPT;
  1414. }
  1415. if (stmt.alternate) {
  1416. result.push(this.maybeBlock(stmt.consequent, S_TFFF));
  1417. result = this.maybeBlockSuffix(stmt.consequent, result);
  1418. if (stmt.alternate.type === Syntax.IfStatement) {
  1419. result = join(result, ['else ', this.generateStatement(stmt.alternate, bodyFlags)]);
  1420. } else {
  1421. result = join(result, join('else', this.maybeBlock(stmt.alternate, bodyFlags)));
  1422. }
  1423. } else {
  1424. result.push(this.maybeBlock(stmt.consequent, bodyFlags));
  1425. }
  1426. return result;
  1427. },
  1428. ForStatement: function (stmt, flags) {
  1429. var result, that = this;
  1430. withIndent(function () {
  1431. result = ['for' + space + '('];
  1432. if (stmt.init) {
  1433. if (stmt.init.type === Syntax.VariableDeclaration) {
  1434. result.push(that.generateStatement(stmt.init, S_FFFF));
  1435. } else {
  1436. // F_ALLOW_IN becomes false.
  1437. result.push(that.generateExpression(stmt.init, Precedence.Sequence, E_FTT));
  1438. result.push(';');
  1439. }
  1440. } else {
  1441. result.push(';');
  1442. }
  1443. if (stmt.test) {
  1444. result.push(space);
  1445. result.push(that.generateExpression(stmt.test, Precedence.Sequence, E_TTT));
  1446. result.push(';');
  1447. } else {
  1448. result.push(';');
  1449. }
  1450. if (stmt.update) {
  1451. result.push(space);
  1452. result.push(that.generateExpression(stmt.update, Precedence.Sequence, E_TTT));
  1453. result.push(')');
  1454. } else {
  1455. result.push(')');
  1456. }
  1457. });
  1458. result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
  1459. return result;
  1460. },
  1461. ForInStatement: function (stmt, flags) {
  1462. return this.generateIterationForStatement('in', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF);
  1463. },
  1464. ForOfStatement: function (stmt, flags) {
  1465. return this.generateIterationForStatement('of', stmt, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF);
  1466. },
  1467. LabeledStatement: function (stmt, flags) {
  1468. return [stmt.label.name + ':', this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF)];
  1469. },
  1470. Program: function (stmt, flags) {
  1471. var result, fragment, i, iz, bodyFlags;
  1472. iz = stmt.body.length;
  1473. result = [safeConcatenation && iz > 0 ? '\n' : ''];
  1474. bodyFlags = S_TFTF;
  1475. for (i = 0; i < iz; ++i) {
  1476. if (!safeConcatenation && i === iz - 1) {
  1477. bodyFlags |= F_SEMICOLON_OPT;
  1478. }
  1479. if (preserveBlankLines) {
  1480. // handle spaces before the first line
  1481. if (i === 0) {
  1482. if (!stmt.body[0].leadingComments) {
  1483. generateBlankLines(stmt.range[0], stmt.body[i].range[0], result);
  1484. }
  1485. }
  1486. // handle spaces between lines
  1487. if (i > 0) {
  1488. if (!stmt.body[i - 1].trailingComments && !stmt.body[i].leadingComments) {
  1489. generateBlankLines(stmt.body[i - 1].range[1], stmt.body[i].range[0], result);
  1490. }
  1491. }
  1492. }
  1493. fragment = addIndent(this.generateStatement(stmt.body[i], bodyFlags));
  1494. result.push(fragment);
  1495. if (i + 1 < iz && !endsWithLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  1496. if (preserveBlankLines) {
  1497. if (!stmt.body[i + 1].leadingComments) {
  1498. result.push(newline);
  1499. }
  1500. } else {
  1501. result.push(newline);
  1502. }
  1503. }
  1504. if (preserveBlankLines) {
  1505. // handle spaces after the last line
  1506. if (i === iz - 1) {
  1507. if (!stmt.body[i].trailingComments) {
  1508. generateBlankLines(stmt.body[i].range[1], stmt.range[1], result);
  1509. }
  1510. }
  1511. }
  1512. }
  1513. return result;
  1514. },
  1515. FunctionDeclaration: function (stmt, flags) {
  1516. return [
  1517. generateAsyncPrefix(stmt, true),
  1518. 'function',
  1519. generateStarSuffix(stmt) || noEmptySpace(),
  1520. stmt.id ? generateIdentifier(stmt.id) : '',
  1521. this.generateFunctionBody(stmt)
  1522. ];
  1523. },
  1524. ReturnStatement: function (stmt, flags) {
  1525. if (stmt.argument) {
  1526. return [join(
  1527. 'return',
  1528. this.generateExpression(stmt.argument, Precedence.Sequence, E_TTT)
  1529. ), this.semicolon(flags)];
  1530. }
  1531. return ['return' + this.semicolon(flags)];
  1532. },
  1533. WhileStatement: function (stmt, flags) {
  1534. var result, that = this;
  1535. withIndent(function () {
  1536. result = [
  1537. 'while' + space + '(',
  1538. that.generateExpression(stmt.test, Precedence.Sequence, E_TTT),
  1539. ')'
  1540. ];
  1541. });
  1542. result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
  1543. return result;
  1544. },
  1545. WithStatement: function (stmt, flags) {
  1546. var result, that = this;
  1547. withIndent(function () {
  1548. result = [
  1549. 'with' + space + '(',
  1550. that.generateExpression(stmt.object, Precedence.Sequence, E_TTT),
  1551. ')'
  1552. ];
  1553. });
  1554. result.push(this.maybeBlock(stmt.body, flags & F_SEMICOLON_OPT ? S_TFFT : S_TFFF));
  1555. return result;
  1556. }
  1557. };
  1558. merge(CodeGenerator.prototype, CodeGenerator.Statement);
  1559. // Expressions.
  1560. CodeGenerator.Expression = {
  1561. SequenceExpression: function (expr, precedence, flags) {
  1562. var result, i, iz;
  1563. if (Precedence.Sequence < precedence) {
  1564. flags |= F_ALLOW_IN;
  1565. }
  1566. result = [];
  1567. for (i = 0, iz = expr.expressions.length; i < iz; ++i) {
  1568. result.push(this.generateExpression(expr.expressions[i], Precedence.Assignment, flags));
  1569. if (i + 1 < iz) {
  1570. result.push(',' + space);
  1571. }
  1572. }
  1573. return parenthesize(result, Precedence.Sequence, precedence);
  1574. },
  1575. AssignmentExpression: function (expr, precedence, flags) {
  1576. return this.generateAssignment(expr.left, expr.right, expr.operator, precedence, flags);
  1577. },
  1578. ArrowFunctionExpression: function (expr, precedence, flags) {
  1579. return parenthesize(this.generateFunctionBody(expr), Precedence.ArrowFunction, precedence);
  1580. },
  1581. ConditionalExpression: function (expr, precedence, flags) {
  1582. if (Precedence.Conditional < precedence) {
  1583. flags |= F_ALLOW_IN;
  1584. }
  1585. return parenthesize(
  1586. [
  1587. this.generateExpression(expr.test, Precedence.LogicalOR, flags),
  1588. space + '?' + space,
  1589. this.generateExpression(expr.consequent, Precedence.Assignment, flags),
  1590. space + ':' + space,
  1591. this.generateExpression(expr.alternate, Precedence.Assignment, flags)
  1592. ],
  1593. Precedence.Conditional,
  1594. precedence
  1595. );
  1596. },
  1597. LogicalExpression: function (expr, precedence, flags) {
  1598. return this.BinaryExpression(expr, precedence, flags);
  1599. },
  1600. BinaryExpression: function (expr, precedence, flags) {
  1601. var result, leftPrecedence, rightPrecedence, currentPrecedence, fragment, leftSource;
  1602. currentPrecedence = BinaryPrecedence[expr.operator];
  1603. leftPrecedence = expr.operator === '**' ? Precedence.Postfix : currentPrecedence;
  1604. rightPrecedence = expr.operator === '**' ? currentPrecedence : currentPrecedence + 1;
  1605. if (currentPrecedence < precedence) {
  1606. flags |= F_ALLOW_IN;
  1607. }
  1608. fragment = this.generateExpression(expr.left, leftPrecedence, flags);
  1609. leftSource = fragment.toString();
  1610. if (leftSource.charCodeAt(leftSource.length - 1) === 0x2F /* / */ && esutils.code.isIdentifierPartES5(expr.operator.charCodeAt(0))) {
  1611. result = [fragment, noEmptySpace(), expr.operator];
  1612. } else {
  1613. result = join(fragment, expr.operator);
  1614. }
  1615. fragment = this.generateExpression(expr.right, rightPrecedence, flags);
  1616. if (expr.operator === '/' && fragment.toString().charAt(0) === '/' ||
  1617. expr.operator.slice(-1) === '<' && fragment.toString().slice(0, 3) === '!--') {
  1618. // If '/' concats with '/' or `<` concats with `!--`, it is interpreted as comment start
  1619. result.push(noEmptySpace());
  1620. result.push(fragment);
  1621. } else {
  1622. result = join(result, fragment);
  1623. }
  1624. if (expr.operator === 'in' && !(flags & F_ALLOW_IN)) {
  1625. return ['(', result, ')'];
  1626. }
  1627. return parenthesize(result, currentPrecedence, precedence);
  1628. },
  1629. CallExpression: function (expr, precedence, flags) {
  1630. var result, i, iz;
  1631. // F_ALLOW_UNPARATH_NEW becomes false.
  1632. result = [this.generateExpression(expr.callee, Precedence.Call, E_TTF)];
  1633. result.push('(');
  1634. for (i = 0, iz = expr['arguments'].length; i < iz; ++i) {
  1635. result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT));
  1636. if (i + 1 < iz) {
  1637. result.push(',' + space);
  1638. }
  1639. }
  1640. result.push(')');
  1641. if (!(flags & F_ALLOW_CALL)) {
  1642. return ['(', result, ')'];
  1643. }
  1644. return parenthesize(result, Precedence.Call, precedence);
  1645. },
  1646. NewExpression: function (expr, precedence, flags) {
  1647. var result, length, i, iz, itemFlags;
  1648. length = expr['arguments'].length;
  1649. // F_ALLOW_CALL becomes false.
  1650. // F_ALLOW_UNPARATH_NEW may become false.
  1651. itemFlags = (flags & F_ALLOW_UNPARATH_NEW && !parentheses && length === 0) ? E_TFT : E_TFF;
  1652. result = join(
  1653. 'new',
  1654. this.generateExpression(expr.callee, Precedence.New, itemFlags)
  1655. );
  1656. if (!(flags & F_ALLOW_UNPARATH_NEW) || parentheses || length > 0) {
  1657. result.push('(');
  1658. for (i = 0, iz = length; i < iz; ++i) {
  1659. result.push(this.generateExpression(expr['arguments'][i], Precedence.Assignment, E_TTT));
  1660. if (i + 1 < iz) {
  1661. result.push(',' + space);
  1662. }
  1663. }
  1664. result.push(')');
  1665. }
  1666. return parenthesize(result, Precedence.New, precedence);
  1667. },
  1668. MemberExpression: function (expr, precedence, flags) {
  1669. var result, fragment;
  1670. // F_ALLOW_UNPARATH_NEW becomes false.
  1671. result = [this.generateExpression(expr.object, Precedence.Call, (flags & F_ALLOW_CALL) ? E_TTF : E_TFF)];
  1672. if (expr.computed) {
  1673. result.push('[');
  1674. result.push(this.generateExpression(expr.property, Precedence.Sequence, flags & F_ALLOW_CALL ? E_TTT : E_TFT));
  1675. result.push(']');
  1676. } else {
  1677. if (expr.object.type === Syntax.Literal && typeof expr.object.value === 'number') {
  1678. fragment = toSourceNodeWhenNeeded(result).toString();
  1679. // When the following conditions are all true,
  1680. // 1. No floating point
  1681. // 2. Don't have exponents
  1682. // 3. The last character is a decimal digit
  1683. // 4. Not hexadecimal OR octal number literal
  1684. // we should add a floating point.
  1685. if (
  1686. fragment.indexOf('.') < 0 &&
  1687. !/[eExX]/.test(fragment) &&
  1688. esutils.code.isDecimalDigit(fragment.charCodeAt(fragment.length - 1)) &&
  1689. !(fragment.length >= 2 && fragment.charCodeAt(0) === 48) // '0'
  1690. ) {
  1691. result.push(' ');
  1692. }
  1693. }
  1694. result.push('.');
  1695. result.push(generateIdentifier(expr.property));
  1696. }
  1697. return parenthesize(result, Precedence.Member, precedence);
  1698. },
  1699. MetaProperty: function (expr, precedence, flags) {
  1700. var result;
  1701. result = [];
  1702. result.push(typeof expr.meta === "string" ? expr.meta : generateIdentifier(expr.meta));
  1703. result.push('.');
  1704. result.push(typeof expr.property === "string" ? expr.property : generateIdentifier(expr.property));
  1705. return parenthesize(result, Precedence.Member, precedence);
  1706. },
  1707. UnaryExpression: function (expr, precedence, flags) {
  1708. var result, fragment, rightCharCode, leftSource, leftCharCode;
  1709. fragment = this.generateExpression(expr.argument, Precedence.Unary, E_TTT);
  1710. if (space === '') {
  1711. result = join(expr.operator, fragment);
  1712. } else {
  1713. result = [expr.operator];
  1714. if (expr.operator.length > 2) {
  1715. // delete, void, typeof
  1716. // get `typeof []`, not `typeof[]`
  1717. result = join(result, fragment);
  1718. } else {
  1719. // Prevent inserting spaces between operator and argument if it is unnecessary
  1720. // like, `!cond`
  1721. leftSource = toSourceNodeWhenNeeded(result).toString();
  1722. leftCharCode = leftSource.charCodeAt(leftSource.length - 1);
  1723. rightCharCode = fragment.toString().charCodeAt(0);
  1724. if (((leftCharCode === 0x2B /* + */ || leftCharCode === 0x2D /* - */) && leftCharCode === rightCharCode) ||
  1725. (esutils.code.isIdentifierPartES5(leftCharCode) && esutils.code.isIdentifierPartES5(rightCharCode))) {
  1726. result.push(noEmptySpace());
  1727. result.push(fragment);
  1728. } else {
  1729. result.push(fragment);
  1730. }
  1731. }
  1732. }
  1733. return parenthesize(result, Precedence.Unary, precedence);
  1734. },
  1735. YieldExpression: function (expr, precedence, flags) {
  1736. var result;
  1737. if (expr.delegate) {
  1738. result = 'yield*';
  1739. } else {
  1740. result = 'yield';
  1741. }
  1742. if (expr.argument) {
  1743. result = join(
  1744. result,
  1745. this.generateExpression(expr.argument, Precedence.Yield, E_TTT)
  1746. );
  1747. }
  1748. return parenthesize(result, Precedence.Yield, precedence);
  1749. },
  1750. AwaitExpression: function (expr, precedence, flags) {
  1751. var result = join(
  1752. expr.all ? 'await*' : 'await',
  1753. this.generateExpression(expr.argument, Precedence.Await, E_TTT)
  1754. );
  1755. return parenthesize(result, Precedence.Await, precedence);
  1756. },
  1757. UpdateExpression: function (expr, precedence, flags) {
  1758. if (expr.prefix) {
  1759. return parenthesize(
  1760. [
  1761. expr.operator,
  1762. this.generateExpression(expr.argument, Precedence.Unary, E_TTT)
  1763. ],
  1764. Precedence.Unary,
  1765. precedence
  1766. );
  1767. }
  1768. return parenthesize(
  1769. [
  1770. this.generateExpression(expr.argument, Precedence.Postfix, E_TTT),
  1771. expr.operator
  1772. ],
  1773. Precedence.Postfix,
  1774. precedence
  1775. );
  1776. },
  1777. FunctionExpression: function (expr, precedence, flags) {
  1778. var result = [
  1779. generateAsyncPrefix(expr, true),
  1780. 'function'
  1781. ];
  1782. if (expr.id) {
  1783. result.push(generateStarSuffix(expr) || noEmptySpace());
  1784. result.push(generateIdentifier(expr.id));
  1785. } else {
  1786. result.push(generateStarSuffix(expr) || space);
  1787. }
  1788. result.push(this.generateFunctionBody(expr));
  1789. return result;
  1790. },
  1791. ArrayPattern: function (expr, precedence, flags) {
  1792. return this.ArrayExpression(expr, precedence, flags, true);
  1793. },
  1794. ArrayExpression: function (expr, precedence, flags, isPattern) {
  1795. var result, multiline, that = this;
  1796. if (!expr.elements.length) {
  1797. return '[]';
  1798. }
  1799. multiline = isPattern ? false : expr.elements.length > 1;
  1800. result = ['[', multiline ? newline : ''];
  1801. withIndent(function (indent) {
  1802. var i, iz;
  1803. for (i = 0, iz = expr.elements.length; i < iz; ++i) {
  1804. if (!expr.elements[i]) {
  1805. if (multiline) {
  1806. result.push(indent);
  1807. }
  1808. if (i + 1 === iz) {
  1809. result.push(',');
  1810. }
  1811. } else {
  1812. result.push(multiline ? indent : '');
  1813. result.push(that.generateExpression(expr.elements[i], Precedence.Assignment, E_TTT));
  1814. }
  1815. if (i + 1 < iz) {
  1816. result.push(',' + (multiline ? newline : space));
  1817. }
  1818. }
  1819. });
  1820. if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  1821. result.push(newline);
  1822. }
  1823. result.push(multiline ? base : '');
  1824. result.push(']');
  1825. return result;
  1826. },
  1827. RestElement: function(expr, precedence, flags) {
  1828. return '...' + this.generatePattern(expr.argument);
  1829. },
  1830. ClassExpression: function (expr, precedence, flags) {
  1831. var result, fragment;
  1832. result = ['class'];
  1833. if (expr.id) {
  1834. result = join(result, this.generateExpression(expr.id, Precedence.Sequence, E_TTT));
  1835. }
  1836. if (expr.superClass) {
  1837. fragment = join('extends', this.generateExpression(expr.superClass, Precedence.Unary, E_TTT));
  1838. result = join(result, fragment);
  1839. }
  1840. result.push(space);
  1841. result.push(this.generateStatement(expr.body, S_TFFT));
  1842. return result;
  1843. },
  1844. MethodDefinition: function (expr, precedence, flags) {
  1845. var result, fragment;
  1846. if (expr['static']) {
  1847. result = ['static' + space];
  1848. } else {
  1849. result = [];
  1850. }
  1851. if (expr.kind === 'get' || expr.kind === 'set') {
  1852. fragment = [
  1853. join(expr.kind, this.generatePropertyKey(expr.key, expr.computed)),
  1854. this.generateFunctionBody(expr.value)
  1855. ];
  1856. } else {
  1857. fragment = [
  1858. generateMethodPrefix(expr),
  1859. this.generatePropertyKey(expr.key, expr.computed),
  1860. this.generateFunctionBody(expr.value)
  1861. ];
  1862. }
  1863. return join(result, fragment);
  1864. },
  1865. Property: function (expr, precedence, flags) {
  1866. if (expr.kind === 'get' || expr.kind === 'set') {
  1867. return [
  1868. expr.kind, noEmptySpace(),
  1869. this.generatePropertyKey(expr.key, expr.computed),
  1870. this.generateFunctionBody(expr.value)
  1871. ];
  1872. }
  1873. if (expr.shorthand) {
  1874. if (expr.value.type === "AssignmentPattern") {
  1875. return this.AssignmentPattern(expr.value, Precedence.Sequence, E_TTT);
  1876. }
  1877. return this.generatePropertyKey(expr.key, expr.computed);
  1878. }
  1879. if (expr.method) {
  1880. return [
  1881. generateMethodPrefix(expr),
  1882. this.generatePropertyKey(expr.key, expr.computed),
  1883. this.generateFunctionBody(expr.value)
  1884. ];
  1885. }
  1886. return [
  1887. this.generatePropertyKey(expr.key, expr.computed),
  1888. ':' + space,
  1889. this.generateExpression(expr.value, Precedence.Assignment, E_TTT)
  1890. ];
  1891. },
  1892. ObjectExpression: function (expr, precedence, flags) {
  1893. var multiline, result, fragment, that = this;
  1894. if (!expr.properties.length) {
  1895. return '{}';
  1896. }
  1897. multiline = expr.properties.length > 1;
  1898. withIndent(function () {
  1899. fragment = that.generateExpression(expr.properties[0], Precedence.Sequence, E_TTT);
  1900. });
  1901. if (!multiline) {
  1902. // issues 4
  1903. // Do not transform from
  1904. // dejavu.Class.declare({
  1905. // method2: function () {}
  1906. // });
  1907. // to
  1908. // dejavu.Class.declare({method2: function () {
  1909. // }});
  1910. if (!hasLineTerminator(toSourceNodeWhenNeeded(fragment).toString())) {
  1911. return [ '{', space, fragment, space, '}' ];
  1912. }
  1913. }
  1914. withIndent(function (indent) {
  1915. var i, iz;
  1916. result = [ '{', newline, indent, fragment ];
  1917. if (multiline) {
  1918. result.push(',' + newline);
  1919. for (i = 1, iz = expr.properties.length; i < iz; ++i) {
  1920. result.push(indent);
  1921. result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT));
  1922. if (i + 1 < iz) {
  1923. result.push(',' + newline);
  1924. }
  1925. }
  1926. }
  1927. });
  1928. if (!endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  1929. result.push(newline);
  1930. }
  1931. result.push(base);
  1932. result.push('}');
  1933. return result;
  1934. },
  1935. AssignmentPattern: function(expr, precedence, flags) {
  1936. return this.generateAssignment(expr.left, expr.right, '=', precedence, flags);
  1937. },
  1938. ObjectPattern: function (expr, precedence, flags) {
  1939. var result, i, iz, multiline, property, that = this;
  1940. if (!expr.properties.length) {
  1941. return '{}';
  1942. }
  1943. multiline = false;
  1944. if (expr.properties.length === 1) {
  1945. property = expr.properties[0];
  1946. if (property.value.type !== Syntax.Identifier) {
  1947. multiline = true;
  1948. }
  1949. } else {
  1950. for (i = 0, iz = expr.properties.length; i < iz; ++i) {
  1951. property = expr.properties[i];
  1952. if (!property.shorthand) {
  1953. multiline = true;
  1954. break;
  1955. }
  1956. }
  1957. }
  1958. result = ['{', multiline ? newline : '' ];
  1959. withIndent(function (indent) {
  1960. var i, iz;
  1961. for (i = 0, iz = expr.properties.length; i < iz; ++i) {
  1962. result.push(multiline ? indent : '');
  1963. result.push(that.generateExpression(expr.properties[i], Precedence.Sequence, E_TTT));
  1964. if (i + 1 < iz) {
  1965. result.push(',' + (multiline ? newline : space));
  1966. }
  1967. }
  1968. });
  1969. if (multiline && !endsWithLineTerminator(toSourceNodeWhenNeeded(result).toString())) {
  1970. result.push(newline);
  1971. }
  1972. result.push(multiline ? base : '');
  1973. result.push('}');
  1974. return result;
  1975. },
  1976. ThisExpression: function (expr, precedence, flags) {
  1977. return 'this';
  1978. },
  1979. Super: function (expr, precedence, flags) {
  1980. return 'super';
  1981. },
  1982. Identifier: function (expr, precedence, flags) {
  1983. return generateIdentifier(expr);
  1984. },
  1985. ImportDefaultSpecifier: function (expr, precedence, flags) {
  1986. return generateIdentifier(expr.id || expr.local);
  1987. },
  1988. ImportNamespaceSpecifier: function (expr, precedence, flags) {
  1989. var result = ['*'];
  1990. var id = expr.id || expr.local;
  1991. if (id) {
  1992. result.push(space + 'as' + noEmptySpace() + generateIdentifier(id));
  1993. }
  1994. return result;
  1995. },
  1996. ImportSpecifier: function (expr, precedence, flags) {
  1997. var imported = expr.imported;
  1998. var result = [ imported.name ];
  1999. var local = expr.local;
  2000. if (local && local.name !== imported.name) {
  2001. result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(local));
  2002. }
  2003. return result;
  2004. },
  2005. ExportSpecifier: function (expr, precedence, flags) {
  2006. var local = expr.local;
  2007. var result = [ local.name ];
  2008. var exported = expr.exported;
  2009. if (exported && exported.name !== local.name) {
  2010. result.push(noEmptySpace() + 'as' + noEmptySpace() + generateIdentifier(exported));
  2011. }
  2012. return result;
  2013. },
  2014. Literal: function (expr, precedence, flags) {
  2015. var raw;
  2016. if (expr.hasOwnProperty('raw') && parse && extra.raw) {
  2017. try {
  2018. raw = parse(expr.raw).body[0].expression;
  2019. if (raw.type === Syntax.Literal) {
  2020. if (raw.value === expr.value) {
  2021. return expr.raw;
  2022. }
  2023. }
  2024. } catch (e) {
  2025. // not use raw property
  2026. }
  2027. }
  2028. if (expr.regex) {
  2029. return '/' + expr.regex.pattern + '/' + expr.regex.flags;
  2030. }
  2031. if (expr.value === null) {
  2032. return 'null';
  2033. }
  2034. if (typeof expr.value === 'string') {
  2035. return escapeString(expr.value);
  2036. }
  2037. if (typeof expr.value === 'number') {
  2038. return generateNumber(expr.value);
  2039. }
  2040. if (typeof expr.value === 'boolean') {
  2041. return expr.value ? 'true' : 'false';
  2042. }
  2043. return generateRegExp(expr.value);
  2044. },
  2045. GeneratorExpression: function (expr, precedence, flags) {
  2046. return this.ComprehensionExpression(expr, precedence, flags);
  2047. },
  2048. ComprehensionExpression: function (expr, precedence, flags) {
  2049. // GeneratorExpression should be parenthesized with (...), ComprehensionExpression with [...]
  2050. // Due to https://bugzilla.mozilla.org/show_bug.cgi?id=883468 position of expr.body can differ in Spidermonkey and ES6
  2051. var result, i, iz, fragment, that = this;
  2052. result = (expr.type === Syntax.GeneratorExpression) ? ['('] : ['['];
  2053. if (extra.moz.comprehensionExpressionStartsWithAssignment) {
  2054. fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);
  2055. result.push(fragment);
  2056. }
  2057. if (expr.blocks) {
  2058. withIndent(function () {
  2059. for (i = 0, iz = expr.blocks.length; i < iz; ++i) {
  2060. fragment = that.generateExpression(expr.blocks[i], Precedence.Sequence, E_TTT);
  2061. if (i > 0 || extra.moz.comprehensionExpressionStartsWithAssignment) {
  2062. result = join(result, fragment);
  2063. } else {
  2064. result.push(fragment);
  2065. }
  2066. }
  2067. });
  2068. }
  2069. if (expr.filter) {
  2070. result = join(result, 'if' + space);
  2071. fragment = this.generateExpression(expr.filter, Precedence.Sequence, E_TTT);
  2072. result = join(result, [ '(', fragment, ')' ]);
  2073. }
  2074. if (!extra.moz.comprehensionExpressionStartsWithAssignment) {
  2075. fragment = this.generateExpression(expr.body, Precedence.Assignment, E_TTT);
  2076. result = join(result, fragment);
  2077. }
  2078. result.push((expr.type === Syntax.GeneratorExpression) ? ')' : ']');
  2079. return result;
  2080. },
  2081. ComprehensionBlock: function (expr, precedence, flags) {
  2082. var fragment;
  2083. if (expr.left.type === Syntax.VariableDeclaration) {
  2084. fragment = [
  2085. expr.left.kind, noEmptySpace(),
  2086. this.generateStatement(expr.left.declarations[0], S_FFFF)
  2087. ];
  2088. } else {
  2089. fragment = this.generateExpression(expr.left, Precedence.Call, E_TTT);
  2090. }
  2091. fragment = join(fragment, expr.of ? 'of' : 'in');
  2092. fragment = join(fragment, this.generateExpression(expr.right, Precedence.Sequence, E_TTT));
  2093. return [ 'for' + space + '(', fragment, ')' ];
  2094. },
  2095. SpreadElement: function (expr, precedence, flags) {
  2096. return [
  2097. '...',
  2098. this.generateExpression(expr.argument, Precedence.Assignment, E_TTT)
  2099. ];
  2100. },
  2101. TaggedTemplateExpression: function (expr, precedence, flags) {
  2102. var itemFlags = E_TTF;
  2103. if (!(flags & F_ALLOW_CALL)) {
  2104. itemFlags = E_TFF;
  2105. }
  2106. var result = [
  2107. this.generateExpression(expr.tag, Precedence.Call, itemFlags),
  2108. this.generateExpression(expr.quasi, Precedence.Primary, E_FFT)
  2109. ];
  2110. return parenthesize(result, Precedence.TaggedTemplate, precedence);
  2111. },
  2112. TemplateElement: function (expr, precedence, flags) {
  2113. // Don't use "cooked". Since tagged template can use raw template
  2114. // representation. So if we do so, it breaks the script semantics.
  2115. return expr.value.raw;
  2116. },
  2117. TemplateLiteral: function (expr, precedence, flags) {
  2118. var result, i, iz;
  2119. result = [ '`' ];
  2120. for (i = 0, iz = expr.quasis.length; i < iz; ++i) {
  2121. result.push(this.generateExpression(expr.quasis[i], Precedence.Primary, E_TTT));
  2122. if (i + 1 < iz) {
  2123. result.push('${' + space);
  2124. result.push(this.generateExpression(expr.expressions[i], Precedence.Sequence, E_TTT));
  2125. result.push(space + '}');
  2126. }
  2127. }
  2128. result.push('`');
  2129. return result;
  2130. },
  2131. ModuleSpecifier: function (expr, precedence, flags) {
  2132. return this.Literal(expr, precedence, flags);
  2133. },
  2134. ImportExpression: function(expr, precedence, flag) {
  2135. return parenthesize([
  2136. 'import(',
  2137. this.generateExpression(expr.source, Precedence.Assignment, E_TTT),
  2138. ')'
  2139. ], Precedence.Call, precedence);
  2140. },
  2141. };
  2142. merge(CodeGenerator.prototype, CodeGenerator.Expression);
  2143. CodeGenerator.prototype.generateExpression = function (expr, precedence, flags) {
  2144. var result, type;
  2145. type = expr.type || Syntax.Property;
  2146. if (extra.verbatim && expr.hasOwnProperty(extra.verbatim)) {
  2147. return generateVerbatim(expr, precedence);
  2148. }
  2149. result = this[type](expr, precedence, flags);
  2150. if (extra.comment) {
  2151. result = addComments(expr, result);
  2152. }
  2153. return toSourceNodeWhenNeeded(result, expr);
  2154. };
  2155. CodeGenerator.prototype.generateStatement = function (stmt, flags) {
  2156. var result,
  2157. fragment;
  2158. result = this[stmt.type](stmt, flags);
  2159. // Attach comments
  2160. if (extra.comment) {
  2161. result = addComments(stmt, result);
  2162. }
  2163. fragment = toSourceNodeWhenNeeded(result).toString();
  2164. if (stmt.type === Syntax.Program && !safeConcatenation && newline === '' && fragment.charAt(fragment.length - 1) === '\n') {
  2165. result = sourceMap ? toSourceNodeWhenNeeded(result).replaceRight(/\s+$/, '') : fragment.replace(/\s+$/, '');
  2166. }
  2167. return toSourceNodeWhenNeeded(result, stmt);
  2168. };
  2169. function generateInternal(node) {
  2170. var codegen;
  2171. codegen = new CodeGenerator();
  2172. if (isStatement(node)) {
  2173. return codegen.generateStatement(node, S_TFFF);
  2174. }
  2175. if (isExpression(node)) {
  2176. return codegen.generateExpression(node, Precedence.Sequence, E_TTT);
  2177. }
  2178. throw new Error('Unknown node type: ' + node.type);
  2179. }
  2180. function generate(node, options) {
  2181. var defaultOptions = getDefaultOptions(), result, pair;
  2182. if (options != null) {
  2183. // Obsolete options
  2184. //
  2185. // `options.indent`
  2186. // `options.base`
  2187. //
  2188. // Instead of them, we can use `option.format.indent`.
  2189. if (typeof options.indent === 'string') {
  2190. defaultOptions.format.indent.style = options.indent;
  2191. }
  2192. if (typeof options.base === 'number') {
  2193. defaultOptions.format.indent.base = options.base;
  2194. }
  2195. options = updateDeeply(defaultOptions, options);
  2196. indent = options.format.indent.style;
  2197. if (typeof options.base === 'string') {
  2198. base = options.base;
  2199. } else {
  2200. base = stringRepeat(indent, options.format.indent.base);
  2201. }
  2202. } else {
  2203. options = defaultOptions;
  2204. indent = options.format.indent.style;
  2205. base = stringRepeat(indent, options.format.indent.base);
  2206. }
  2207. json = options.format.json;
  2208. renumber = options.format.renumber;
  2209. hexadecimal = json ? false : options.format.hexadecimal;
  2210. quotes = json ? 'double' : options.format.quotes;
  2211. escapeless = options.format.escapeless;
  2212. newline = options.format.newline;
  2213. space = options.format.space;
  2214. if (options.format.compact) {
  2215. newline = space = indent = base = '';
  2216. }
  2217. parentheses = options.format.parentheses;
  2218. semicolons = options.format.semicolons;
  2219. safeConcatenation = options.format.safeConcatenation;
  2220. directive = options.directive;
  2221. parse = json ? null : options.parse;
  2222. sourceMap = options.sourceMap;
  2223. sourceCode = options.sourceCode;
  2224. preserveBlankLines = options.format.preserveBlankLines && sourceCode !== null;
  2225. extra = options;
  2226. if (sourceMap) {
  2227. if (!exports.browser) {
  2228. // We assume environment is node.js
  2229. // And prevent from including source-map by browserify
  2230. SourceNode = require('source-map').SourceNode;
  2231. } else {
  2232. SourceNode = global.sourceMap.SourceNode;
  2233. }
  2234. }
  2235. result = generateInternal(node);
  2236. if (!sourceMap) {
  2237. pair = {code: result.toString(), map: null};
  2238. return options.sourceMapWithCode ? pair : pair.code;
  2239. }
  2240. pair = result.toStringWithSourceMap({
  2241. file: options.file,
  2242. sourceRoot: options.sourceMapRoot
  2243. });
  2244. if (options.sourceContent) {
  2245. pair.map.setSourceContent(options.sourceMap,
  2246. options.sourceContent);
  2247. }
  2248. if (options.sourceMapWithCode) {
  2249. return pair;
  2250. }
  2251. return pair.map.toString();
  2252. }
  2253. FORMAT_MINIFY = {
  2254. indent: {
  2255. style: '',
  2256. base: 0
  2257. },
  2258. renumber: true,
  2259. hexadecimal: true,
  2260. quotes: 'auto',
  2261. escapeless: true,
  2262. compact: true,
  2263. parentheses: false,
  2264. semicolons: false
  2265. };
  2266. FORMAT_DEFAULTS = getDefaultOptions().format;
  2267. exports.version = require('./package.json').version;
  2268. exports.generate = generate;
  2269. exports.attachComments = estraverse.attachComments;
  2270. exports.Precedence = updateDeeply({}, Precedence);
  2271. exports.browser = false;
  2272. exports.FORMAT_MINIFY = FORMAT_MINIFY;
  2273. exports.FORMAT_DEFAULTS = FORMAT_DEFAULTS;
  2274. }());
  2275. /* vim: set sw=4 ts=4 et tw=80 : */