Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
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 94KB

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