javascript.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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_MEMBER = 1; // . []
  68. Blockly.JavaScript.ORDER_NEW = 1; // new
  69. Blockly.JavaScript.ORDER_FUNCTION_CALL = 2; // ()
  70. Blockly.JavaScript.ORDER_INCREMENT = 3; // ++
  71. Blockly.JavaScript.ORDER_DECREMENT = 3; // --
  72. Blockly.JavaScript.ORDER_LOGICAL_NOT = 4; // !
  73. Blockly.JavaScript.ORDER_BITWISE_NOT = 4; // ~
  74. Blockly.JavaScript.ORDER_UNARY_PLUS = 4; // +
  75. Blockly.JavaScript.ORDER_UNARY_NEGATION = 4; // -
  76. Blockly.JavaScript.ORDER_TYPEOF = 4; // typeof
  77. Blockly.JavaScript.ORDER_VOID = 4; // void
  78. Blockly.JavaScript.ORDER_DELETE = 4; // delete
  79. Blockly.JavaScript.ORDER_MULTIPLICATION = 5; // *
  80. Blockly.JavaScript.ORDER_DIVISION = 5; // /
  81. Blockly.JavaScript.ORDER_MODULUS = 5; // %
  82. Blockly.JavaScript.ORDER_ADDITION = 6; // +
  83. Blockly.JavaScript.ORDER_SUBTRACTION = 6; // -
  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. * Initialise the database of variable names.
  100. * @param {!Blockly.Workspace} workspace Workspace to generate code from.
  101. */
  102. Blockly.JavaScript.init = function(workspace) {
  103. // Create a dictionary of definitions to be printed before the code.
  104. Blockly.JavaScript.definitions_ = Object.create(null);
  105. // Create a dictionary mapping desired function names in definitions_
  106. // to actual function names (to avoid collisions with user functions).
  107. Blockly.JavaScript.functionNames_ = Object.create(null);
  108. if (!Blockly.JavaScript.variableDB_) {
  109. Blockly.JavaScript.variableDB_ =
  110. new Blockly.Names(Blockly.JavaScript.RESERVED_WORDS_);
  111. } else {
  112. Blockly.JavaScript.variableDB_.reset();
  113. }
  114. var defvars = [];
  115. var variables = Blockly.Variables.allVariables(workspace);
  116. if (variables.length) {
  117. for (var i = 0; i < variables.length; i++) {
  118. defvars[i] = Blockly.JavaScript.variableDB_.getName(variables[i],
  119. Blockly.Variables.NAME_TYPE);
  120. }
  121. Blockly.JavaScript.definitions_['variables'] =
  122. 'var ' + defvars.join(', ') + ';';
  123. }
  124. };
  125. /**
  126. * Prepend the generated code with the variable definitions.
  127. * @param {string} code Generated code.
  128. * @return {string} Completed code.
  129. */
  130. Blockly.JavaScript.finish = function(code) {
  131. // Convert the definitions dictionary into a list.
  132. var definitions = [];
  133. for (var name in Blockly.JavaScript.definitions_) {
  134. definitions.push(Blockly.JavaScript.definitions_[name]);
  135. }
  136. // Clean up temporary data.
  137. delete Blockly.JavaScript.definitions_;
  138. delete Blockly.JavaScript.functionNames_;
  139. Blockly.JavaScript.variableDB_.reset();
  140. return definitions.join('\n\n') + '\n\n\n' + code;
  141. };
  142. /**
  143. * Naked values are top-level blocks with outputs that aren't plugged into
  144. * anything. A trailing semicolon is needed to make this legal.
  145. * @param {string} line Line of generated code.
  146. * @return {string} Legal line of code.
  147. */
  148. Blockly.JavaScript.scrubNakedValue = function(line) {
  149. return line + ';\n';
  150. };
  151. /**
  152. * Encode a string as a properly escaped JavaScript string, complete with
  153. * quotes.
  154. * @param {string} string Text to encode.
  155. * @return {string} JavaScript string.
  156. * @private
  157. */
  158. Blockly.JavaScript.quote_ = function(string) {
  159. // TODO: This is a quick hack. Replace with goog.string.quote
  160. string = string.replace(/\\/g, '\\\\')
  161. .replace(/\n/g, '\\\n')
  162. .replace(/'/g, '\\\'');
  163. return '\'' + string + '\'';
  164. };
  165. /**
  166. * Common tasks for generating JavaScript from blocks.
  167. * Handles comments for the specified block and any connected value blocks.
  168. * Calls any statements following this block.
  169. * @param {!Blockly.Block} block The current block.
  170. * @param {string} code The JavaScript code created for this block.
  171. * @return {string} JavaScript code with comments and subsequent blocks added.
  172. * @private
  173. */
  174. Blockly.JavaScript.scrub_ = function(block, code) {
  175. var commentCode = '';
  176. // Only collect comments for blocks that aren't inline.
  177. if (!block.outputConnection || !block.outputConnection.targetConnection) {
  178. // Collect comment for this block.
  179. var comment = block.getCommentText();
  180. if (comment) {
  181. commentCode += Blockly.JavaScript.prefixLines(comment, '// ') + '\n';
  182. }
  183. // Collect comments for all value arguments.
  184. // Don't collect comments for nested statements.
  185. for (var x = 0; x < block.inputList.length; x++) {
  186. if (block.inputList[x].type == Blockly.INPUT_VALUE) {
  187. var childBlock = block.inputList[x].connection.targetBlock();
  188. if (childBlock) {
  189. var comment = Blockly.JavaScript.allNestedComments(childBlock);
  190. if (comment) {
  191. commentCode += Blockly.JavaScript.prefixLines(comment, '// ');
  192. }
  193. }
  194. }
  195. }
  196. }
  197. var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
  198. var nextCode = Blockly.JavaScript.blockToCode(nextBlock);
  199. return commentCode + code + nextCode;
  200. };