javascript.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /**
  2. * @license
  3. * Visual Blocks Language
  4. *
  5. * Copyright 2012 Google Inc.
  6. * https://developers.google.com/blockly/
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License");
  9. * you may not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. /**
  21. * @fileoverview Helper functions for generating JavaScript for blocks.
  22. * @author fraser@google.com (Neil Fraser)
  23. */
  24. 'use strict';
  25. goog.provide('Blockly.JavaScript');
  26. goog.require('Blockly.Generator');
  27. /**
  28. * JavaScript code generator.
  29. * @type {!Blockly.Generator}
  30. */
  31. Blockly.JavaScript = new Blockly.Generator('JavaScript');
  32. /**
  33. * List of illegal variable names.
  34. * This is not intended to be a security feature. Blockly is 100% client-side,
  35. * so bypassing this list is trivial. This is intended to prevent users from
  36. * accidentally clobbering a built-in object or function.
  37. * @private
  38. */
  39. Blockly.JavaScript.addReservedWords(
  40. 'Blockly,' + // In case JS is evaled in the current window.
  41. // https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words
  42. 'break,case,catch,continue,debugger,default,delete,do,else,finally,for,function,if,in,instanceof,new,return,switch,this,throw,try,typeof,var,void,while,with,' +
  43. 'class,enum,export,extends,import,super,implements,interface,let,package,private,protected,public,static,yield,' +
  44. 'const,null,true,false,' +
  45. // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects
  46. 'Array,ArrayBuffer,Boolean,Date,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Error,eval,EvalError,Float32Array,Float64Array,Function,Infinity,Int16Array,Int32Array,Int8Array,isFinite,isNaN,Iterator,JSON,Math,NaN,Number,Object,parseFloat,parseInt,RangeError,ReferenceError,RegExp,StopIteration,String,SyntaxError,TypeError,Uint16Array,Uint32Array,Uint8Array,Uint8ClampedArray,undefined,uneval,URIError,' +
  47. // https://developer.mozilla.org/en/DOM/window
  48. 'applicationCache,closed,Components,content,_content,controllers,crypto,defaultStatus,dialogArguments,directories,document,frameElement,frames,fullScreen,globalStorage,history,innerHeight,innerWidth,length,location,locationbar,localStorage,menubar,messageManager,mozAnimationStartTime,mozInnerScreenX,mozInnerScreenY,mozPaintCount,name,navigator,opener,outerHeight,outerWidth,pageXOffset,pageYOffset,parent,performance,personalbar,pkcs11,returnValue,screen,screenX,screenY,scrollbars,scrollMaxX,scrollMaxY,scrollX,scrollY,self,sessionStorage,sidebar,status,statusbar,toolbar,top,URL,window,' +
  49. 'addEventListener,alert,atob,back,blur,btoa,captureEvents,clearImmediate,clearInterval,clearTimeout,close,confirm,disableExternalCapture,dispatchEvent,dump,enableExternalCapture,escape,find,focus,forward,GeckoActiveXObject,getAttention,getAttentionWithCycleCount,getComputedStyle,getSelection,home,matchMedia,maximize,minimize,moveBy,moveTo,mozRequestAnimationFrame,open,openDialog,postMessage,print,prompt,QueryInterface,releaseEvents,removeEventListener,resizeBy,resizeTo,restore,routeEvent,scroll,scrollBy,scrollByLines,scrollByPages,scrollTo,setCursor,setImmediate,setInterval,setResizable,setTimeout,showModalDialog,sizeToContent,stop,unescape,updateCommands,XPCNativeWrapper,XPCSafeJSObjectWrapper,' +
  50. 'onabort,onbeforeunload,onblur,onchange,onclick,onclose,oncontextmenu,ondevicemotion,ondeviceorientation,ondragdrop,onerror,onfocus,onhashchange,onkeydown,onkeypress,onkeyup,onload,onmousedown,onmousemove,onmouseout,onmouseover,onmouseup,onmozbeforepaint,onpaint,onpopstate,onreset,onresize,onscroll,onselect,onsubmit,onunload,onpageshow,onpagehide,' +
  51. 'Image,Option,Worker,' +
  52. // https://developer.mozilla.org/en/Gecko_DOM_Reference
  53. 'Event,Range,File,FileReader,Blob,BlobBuilder,' +
  54. 'Attr,CDATASection,CharacterData,Comment,console,DocumentFragment,DocumentType,DomConfiguration,DOMError,DOMErrorHandler,DOMException,DOMImplementation,DOMImplementationList,DOMImplementationRegistry,DOMImplementationSource,DOMLocator,DOMObject,DOMString,DOMStringList,DOMTimeStamp,DOMUserData,Entity,EntityReference,MediaQueryList,MediaQueryListListener,NameList,NamedNodeMap,Node,NodeFilter,NodeIterator,NodeList,Notation,Plugin,PluginArray,ProcessingInstruction,SharedWorker,Text,TimeRanges,Treewalker,TypeInfo,UserDataHandler,Worker,WorkerGlobalScope,' +
  55. 'HTMLDocument,HTMLElement,HTMLAnchorElement,HTMLAppletElement,HTMLAudioElement,HTMLAreaElement,HTMLBaseElement,HTMLBaseFontElement,HTMLBodyElement,HTMLBRElement,HTMLButtonElement,HTMLCanvasElement,HTMLDirectoryElement,HTMLDivElement,HTMLDListElement,HTMLEmbedElement,HTMLFieldSetElement,HTMLFontElement,HTMLFormElement,HTMLFrameElement,HTMLFrameSetElement,HTMLHeadElement,HTMLHeadingElement,HTMLHtmlElement,HTMLHRElement,HTMLIFrameElement,HTMLImageElement,HTMLInputElement,HTMLKeygenElement,HTMLLabelElement,HTMLLIElement,HTMLLinkElement,HTMLMapElement,HTMLMenuElement,HTMLMetaElement,HTMLModElement,HTMLObjectElement,HTMLOListElement,HTMLOptGroupElement,HTMLOptionElement,HTMLOutputElement,HTMLParagraphElement,HTMLParamElement,HTMLPreElement,HTMLQuoteElement,HTMLScriptElement,HTMLSelectElement,HTMLSourceElement,HTMLSpanElement,HTMLStyleElement,HTMLTableElement,HTMLTableCaptionElement,HTMLTableCellElement,HTMLTableDataCellElement,HTMLTableHeaderCellElement,HTMLTableColElement,HTMLTableRowElement,HTMLTableSectionElement,HTMLTextAreaElement,HTMLTimeElement,HTMLTitleElement,HTMLTrackElement,HTMLUListElement,HTMLUnknownElement,HTMLVideoElement,' +
  56. 'HTMLCanvasElement,CanvasRenderingContext2D,CanvasGradient,CanvasPattern,TextMetrics,ImageData,CanvasPixelArray,HTMLAudioElement,HTMLVideoElement,NotifyAudioAvailableEvent,HTMLCollection,HTMLAllCollection,HTMLFormControlsCollection,HTMLOptionsCollection,HTMLPropertiesCollection,DOMTokenList,DOMSettableTokenList,DOMStringMap,RadioNodeList,' +
  57. 'SVGDocument,SVGElement,SVGAElement,SVGAltGlyphElement,SVGAltGlyphDefElement,SVGAltGlyphItemElement,SVGAnimationElement,SVGAnimateElement,SVGAnimateColorElement,SVGAnimateMotionElement,SVGAnimateTransformElement,SVGSetElement,SVGCircleElement,SVGClipPathElement,SVGColorProfileElement,SVGCursorElement,SVGDefsElement,SVGDescElement,SVGEllipseElement,SVGFilterElement,SVGFilterPrimitiveStandardAttributes,SVGFEBlendElement,SVGFEColorMatrixElement,SVGFEComponentTransferElement,SVGFECompositeElement,SVGFEConvolveMatrixElement,SVGFEDiffuseLightingElement,SVGFEDisplacementMapElement,SVGFEDistantLightElement,SVGFEFloodElement,SVGFEGaussianBlurElement,SVGFEImageElement,SVGFEMergeElement,SVGFEMergeNodeElement,SVGFEMorphologyElement,SVGFEOffsetElement,SVGFEPointLightElement,SVGFESpecularLightingElement,SVGFESpotLightElement,SVGFETileElement,SVGFETurbulenceElement,SVGComponentTransferFunctionElement,SVGFEFuncRElement,SVGFEFuncGElement,SVGFEFuncBElement,SVGFEFuncAElement,SVGFontElement,SVGFontFaceElement,SVGFontFaceFormatElement,SVGFontFaceNameElement,SVGFontFaceSrcElement,SVGFontFaceUriElement,SVGForeignObjectElement,SVGGElement,SVGGlyphElement,SVGGlyphRefElement,SVGGradientElement,SVGLinearGradientElement,SVGRadialGradientElement,SVGHKernElement,SVGImageElement,SVGLineElement,SVGMarkerElement,SVGMaskElement,SVGMetadataElement,SVGMissingGlyphElement,SVGMPathElement,SVGPathElement,SVGPatternElement,SVGPolylineElement,SVGPolygonElement,SVGRectElement,SVGScriptElement,SVGStopElement,SVGStyleElement,SVGSVGElement,SVGSwitchElement,SVGSymbolElement,SVGTextElement,SVGTextPathElement,SVGTitleElement,SVGTRefElement,SVGTSpanElement,SVGUseElement,SVGViewElement,SVGVKernElement,' +
  58. 'SVGAngle,SVGColor,SVGICCColor,SVGElementInstance,SVGElementInstanceList,SVGLength,SVGLengthList,SVGMatrix,SVGNumber,SVGNumberList,SVGPaint,SVGPoint,SVGPointList,SVGPreserveAspectRatio,SVGRect,SVGStringList,SVGTransform,SVGTransformList,' +
  59. 'SVGAnimatedAngle,SVGAnimatedBoolean,SVGAnimatedEnumeration,SVGAnimatedInteger,SVGAnimatedLength,SVGAnimatedLengthList,SVGAnimatedNumber,SVGAnimatedNumberList,SVGAnimatedPreserveAspectRatio,SVGAnimatedRect,SVGAnimatedString,SVGAnimatedTransformList,' +
  60. 'SVGPathSegList,SVGPathSeg,SVGPathSegArcAbs,SVGPathSegArcRel,SVGPathSegClosePath,SVGPathSegCurvetoCubicAbs,SVGPathSegCurvetoCubicRel,SVGPathSegCurvetoCubicSmoothAbs,SVGPathSegCurvetoCubicSmoothRel,SVGPathSegCurvetoQuadraticAbs,SVGPathSegCurvetoQuadraticRel,SVGPathSegCurvetoQuadraticSmoothAbs,SVGPathSegCurvetoQuadraticSmoothRel,SVGPathSegLinetoAbs,SVGPathSegLinetoHorizontalAbs,SVGPathSegLinetoHorizontalRel,SVGPathSegLinetoRel,SVGPathSegLinetoVerticalAbs,SVGPathSegLinetoVerticalRel,SVGPathSegMovetoAbs,SVGPathSegMovetoRel,ElementTimeControl,TimeEvent,SVGAnimatedPathData,' +
  61. 'SVGAnimatedPoints,SVGColorProfileRule,SVGCSSRule,SVGExternalResourcesRequired,SVGFitToViewBox,SVGLangSpace,SVGLocatable,SVGRenderingIntent,SVGStylable,SVGTests,SVGTextContentElement,SVGTextPositioningElement,SVGTransformable,SVGUnitTypes,SVGURIReference,SVGViewSpec,SVGZoomAndPan');
  62. /**
  63. * Order of operation ENUMs.
  64. * https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence
  65. */
  66. Blockly.JavaScript.ORDER_ATOMIC = 0; // 0 "" ...
  67. Blockly.JavaScript.ORDER_NEW = 1.1; // new
  68. Blockly.JavaScript.ORDER_MEMBER = 1.2; // . []
  69. Blockly.JavaScript.ORDER_FUNCTION_CALL = 2; // ()
  70. Blockly.JavaScript.ORDER_INCREMENT = 3; // ++
  71. Blockly.JavaScript.ORDER_DECREMENT = 3; // --
  72. Blockly.JavaScript.ORDER_BITWISE_NOT = 4.1; // ~
  73. Blockly.JavaScript.ORDER_UNARY_PLUS = 4.2; // +
  74. Blockly.JavaScript.ORDER_UNARY_NEGATION = 4.3; // -
  75. Blockly.JavaScript.ORDER_LOGICAL_NOT = 4.4; // !
  76. Blockly.JavaScript.ORDER_TYPEOF = 4.5; // typeof
  77. Blockly.JavaScript.ORDER_VOID = 4.6; // void
  78. Blockly.JavaScript.ORDER_DELETE = 4.7; // delete
  79. Blockly.JavaScript.ORDER_DIVISION = 5.1; // /
  80. Blockly.JavaScript.ORDER_MULTIPLICATION = 5.2; // *
  81. Blockly.JavaScript.ORDER_MODULUS = 5.3; // %
  82. Blockly.JavaScript.ORDER_SUBTRACTION = 6.1; // -
  83. Blockly.JavaScript.ORDER_ADDITION = 6.2; // +
  84. Blockly.JavaScript.ORDER_BITWISE_SHIFT = 7; // << >> >>>
  85. Blockly.JavaScript.ORDER_RELATIONAL = 8; // < <= > >=
  86. Blockly.JavaScript.ORDER_IN = 8; // in
  87. Blockly.JavaScript.ORDER_INSTANCEOF = 8; // instanceof
  88. Blockly.JavaScript.ORDER_EQUALITY = 9; // == != === !==
  89. Blockly.JavaScript.ORDER_BITWISE_AND = 10; // &
  90. Blockly.JavaScript.ORDER_BITWISE_XOR = 11; // ^
  91. Blockly.JavaScript.ORDER_BITWISE_OR = 12; // |
  92. Blockly.JavaScript.ORDER_LOGICAL_AND = 13; // &&
  93. Blockly.JavaScript.ORDER_LOGICAL_OR = 14; // ||
  94. Blockly.JavaScript.ORDER_CONDITIONAL = 15; // ?:
  95. Blockly.JavaScript.ORDER_ASSIGNMENT = 16; // = += -= *= /= %= <<= >>= ...
  96. Blockly.JavaScript.ORDER_COMMA = 17; // ,
  97. Blockly.JavaScript.ORDER_NONE = 99; // (...)
  98. /**
  99. * List of outer-inner pairings that do NOT require parentheses.
  100. * @type {!Array.<!Array.<number>>}
  101. */
  102. Blockly.JavaScript.ORDER_OVERRIDES = [
  103. // (foo()).bar -> foo().bar
  104. // (foo())[0] -> foo()[0]
  105. [Blockly.JavaScript.ORDER_FUNCTION_CALL, Blockly.JavaScript.ORDER_MEMBER],
  106. // (foo())() -> foo()()
  107. [Blockly.JavaScript.ORDER_FUNCTION_CALL, Blockly.JavaScript.ORDER_FUNCTION_CALL],
  108. // (foo.bar).baz -> foo.bar.baz
  109. // (foo.bar)[0] -> foo.bar[0]
  110. // (foo[0]).bar -> foo[0].bar
  111. // (foo[0])[1] -> foo[0][1]
  112. [Blockly.JavaScript.ORDER_MEMBER, Blockly.JavaScript.ORDER_MEMBER],
  113. // (foo.bar)() -> foo.bar()
  114. // (foo[0])() -> foo[0]()
  115. [Blockly.JavaScript.ORDER_MEMBER, Blockly.JavaScript.ORDER_FUNCTION_CALL],
  116. // !(!foo) -> !!foo
  117. [Blockly.JavaScript.ORDER_LOGICAL_NOT, Blockly.JavaScript.ORDER_LOGICAL_NOT],
  118. // a * (b * c) -> a * b * c
  119. [Blockly.JavaScript.ORDER_MULTIPLICATION, Blockly.JavaScript.ORDER_MULTIPLICATION],
  120. // a + (b + c) -> a + b + c
  121. [Blockly.JavaScript.ORDER_ADDITION, Blockly.JavaScript.ORDER_ADDITION],
  122. // a && (b && c) -> a && b && c
  123. [Blockly.JavaScript.ORDER_LOGICAL_AND, Blockly.JavaScript.ORDER_LOGICAL_AND],
  124. // a || (b || c) -> a || b || c
  125. [Blockly.JavaScript.ORDER_LOGICAL_OR, Blockly.JavaScript.ORDER_LOGICAL_OR]
  126. ];
  127. /**
  128. * Allow for switching between one and zero based indexing for lists and text,
  129. * one based by default.
  130. */
  131. Blockly.JavaScript.ONE_BASED_INDEXING = true;
  132. /**
  133. * Initialise the database of variable names.
  134. * @param {!Blockly.Workspace} workspace Workspace to generate code from.
  135. */
  136. Blockly.JavaScript.init = function(workspace) {
  137. // Create a dictionary of definitions to be printed before the code.
  138. Blockly.JavaScript.definitions_ = Object.create(null);
  139. // Create a dictionary mapping desired function names in definitions_
  140. // to actual function names (to avoid collisions with user functions).
  141. Blockly.JavaScript.functionNames_ = Object.create(null);
  142. if (!Blockly.JavaScript.variableDB_) {
  143. Blockly.JavaScript.variableDB_ =
  144. new Blockly.Names(Blockly.JavaScript.RESERVED_WORDS_);
  145. } else {
  146. Blockly.JavaScript.variableDB_.reset();
  147. }
  148. var defvars = [];
  149. var variables = Blockly.Variables.allVariables(workspace);
  150. if (variables.length) {
  151. for (var i = 0; i < variables.length; i++) {
  152. defvars[i] = Blockly.JavaScript.variableDB_.getName(variables[i],
  153. Blockly.Variables.NAME_TYPE);
  154. }
  155. Blockly.JavaScript.definitions_['variables'] =
  156. 'var ' + defvars.join(', ') + ';';
  157. }
  158. };
  159. /**
  160. * Prepend the generated code with the variable definitions.
  161. * @param {string} code Generated code.
  162. * @return {string} Completed code.
  163. */
  164. Blockly.JavaScript.finish = function(code) {
  165. // Convert the definitions dictionary into a list.
  166. var definitions = [];
  167. for (var name in Blockly.JavaScript.definitions_) {
  168. definitions.push(Blockly.JavaScript.definitions_[name]);
  169. }
  170. // Clean up temporary data.
  171. delete Blockly.JavaScript.definitions_;
  172. delete Blockly.JavaScript.functionNames_;
  173. Blockly.JavaScript.variableDB_.reset();
  174. return definitions.join('\n\n') + '\n\n\n' + code;
  175. };
  176. /**
  177. * Naked values are top-level blocks with outputs that aren't plugged into
  178. * anything. A trailing semicolon is needed to make this legal.
  179. * @param {string} line Line of generated code.
  180. * @return {string} Legal line of code.
  181. */
  182. Blockly.JavaScript.scrubNakedValue = function(line) {
  183. return line + ';\n';
  184. };
  185. /**
  186. * Encode a string as a properly escaped JavaScript string, complete with
  187. * quotes.
  188. * @param {string} string Text to encode.
  189. * @return {string} JavaScript string.
  190. * @private
  191. */
  192. Blockly.JavaScript.quote_ = function(string) {
  193. // Can't use goog.string.quote since Google's style guide recommends
  194. // JS string literals use single quotes.
  195. string = string.replace(/\\/g, '\\\\')
  196. .replace(/\n/g, '\\\n')
  197. .replace(/'/g, '\\\'');
  198. return '\'' + string + '\'';
  199. };
  200. /**
  201. * Common tasks for generating JavaScript from blocks.
  202. * Handles comments for the specified block and any connected value blocks.
  203. * Calls any statements following this block.
  204. * @param {!Blockly.Block} block The current block.
  205. * @param {string} code The JavaScript code created for this block.
  206. * @return {string} JavaScript code with comments and subsequent blocks added.
  207. * @private
  208. */
  209. Blockly.JavaScript.scrub_ = function(block, code) {
  210. var commentCode = '';
  211. // Only collect comments for blocks that aren't inline.
  212. if (!block.outputConnection || !block.outputConnection.targetConnection) {
  213. // Collect comment for this block.
  214. var comment = block.getCommentText();
  215. comment = Blockly.utils.wrap(comment, Blockly.JavaScript.COMMENT_WRAP - 3);
  216. if (comment) {
  217. if (block.getProcedureDef) {
  218. // Use a comment block for function comments.
  219. commentCode += '/**\n' +
  220. Blockly.JavaScript.prefixLines(comment + '\n', ' * ') +
  221. ' */\n';
  222. } else {
  223. commentCode += Blockly.JavaScript.prefixLines(comment + '\n', '// ');
  224. }
  225. }
  226. // Collect comments for all value arguments.
  227. // Don't collect comments for nested statements.
  228. for (var i = 0; i < block.inputList.length; i++) {
  229. if (block.inputList[i].type == Blockly.INPUT_VALUE) {
  230. var childBlock = block.inputList[i].connection.targetBlock();
  231. if (childBlock) {
  232. var comment = Blockly.JavaScript.allNestedComments(childBlock);
  233. if (comment) {
  234. commentCode += Blockly.JavaScript.prefixLines(comment, '// ');
  235. }
  236. }
  237. }
  238. }
  239. }
  240. var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
  241. var nextCode = Blockly.JavaScript.blockToCode(nextBlock);
  242. return commentCode + code + nextCode;
  243. };
  244. /**
  245. * Gets a property and adjusts the value while taking into account indexing.
  246. * @param {!Blockly.Block} block The block.
  247. * @param {string} atId The property ID of the element to get.
  248. * @param {number=} opt_delta Value to add.
  249. * @param {boolean=} opt_negate Whether to negate the value.
  250. * @param {number=} opt_order The highest order acting on this value.
  251. * @return {string|number}
  252. */
  253. Blockly.JavaScript.getAdjusted = function(block, atId, opt_delta, opt_negate,
  254. opt_order) {
  255. var delta = opt_delta || 0;
  256. var order = opt_order || Blockly.JavaScript.ORDER_NONE;
  257. if (Blockly.JavaScript.ONE_BASED_INDEXING) {
  258. delta--;
  259. }
  260. var defaultAtIndex = Blockly.JavaScript.ONE_BASED_INDEXING ? '1' : '0';
  261. if (delta > 0) {
  262. var at = Blockly.JavaScript.valueToCode(block, atId,
  263. Blockly.JavaScript.ORDER_ADDITION) || defaultAtIndex;
  264. } else if (delta < 0) {
  265. var at = Blockly.JavaScript.valueToCode(block, atId,
  266. Blockly.JavaScript.ORDER_SUBTRACTION) || defaultAtIndex;
  267. } else if (opt_negate) {
  268. var at = Blockly.JavaScript.valueToCode(block, atId,
  269. Blockly.JavaScript.ORDER_UNARY_NEGATION) || defaultAtIndex;
  270. } else {
  271. var at = Blockly.JavaScript.valueToCode(block, atId, order) ||
  272. defaultAtIndex;
  273. }
  274. if (Blockly.isNumber(at)) {
  275. // If the index is a naked number, adjust it right now.
  276. at = parseFloat(at) + delta;
  277. if (opt_negate) {
  278. at = -at;
  279. }
  280. } else {
  281. // If the index is dynamic, adjust it in code.
  282. if (delta > 0) {
  283. at = at + ' + ' + delta;
  284. var innerOrder = Blockly.JavaScript.ORDER_ADDITION;
  285. } else if (delta < 0) {
  286. at = at + ' - ' + -delta;
  287. var innerOrder = Blockly.JavaScript.ORDER_SUBTRACTION;
  288. }
  289. if (opt_negate) {
  290. if (delta) {
  291. at = '-(' + at + ')';
  292. } else {
  293. at = '-' + at;
  294. }
  295. var innerOrder = Blockly.JavaScript.ORDER_UNARY_NEGATION;
  296. }
  297. innerOrder = Math.floor(innerOrder);
  298. order = Math.floor(order);
  299. if (innerOrder && order >= innerOrder) {
  300. at = '(' + at + ')';
  301. }
  302. }
  303. return at;
  304. };