Node-Red configuration
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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