python.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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 Python for blocks.
  22. * @author fraser@google.com (Neil Fraser)
  23. */
  24. 'use strict';
  25. goog.provide('Blockly.Python');
  26. goog.require('Blockly.Generator');
  27. /**
  28. * Python code generator.
  29. * @type {!Blockly.Generator}
  30. */
  31. Blockly.Python = new Blockly.Generator('Python');
  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.Python.addReservedWords(
  40. // import keyword
  41. // print ','.join(keyword.kwlist)
  42. // http://docs.python.org/reference/lexical_analysis.html#keywords
  43. 'and,as,assert,break,class,continue,def,del,elif,else,except,exec,' +
  44. 'finally,for,from,global,if,import,in,is,lambda,not,or,pass,print,raise,' +
  45. 'return,try,while,with,yield,' +
  46. //http://docs.python.org/library/constants.html
  47. 'True,False,None,NotImplemented,Ellipsis,__debug__,quit,exit,copyright,' +
  48. 'license,credits,' +
  49. // http://docs.python.org/library/functions.html
  50. 'abs,divmod,input,open,staticmethod,all,enumerate,int,ord,str,any,eval,' +
  51. 'isinstance,pow,sum,basestring,execfile,issubclass,print,super,bin,file,' +
  52. 'iter,property,tuple,bool,filter,len,range,type,bytearray,float,list,' +
  53. 'raw_input,unichr,callable,format,locals,reduce,unicode,chr,frozenset,' +
  54. 'long,reload,vars,classmethod,getattr,map,repr,xrange,cmp,globals,max,' +
  55. 'reversed,zip,compile,hasattr,memoryview,round,__import__,complex,hash,' +
  56. 'min,set,apply,delattr,help,next,setattr,buffer,dict,hex,object,slice,' +
  57. 'coerce,dir,id,oct,sorted,intern'
  58. );
  59. /**
  60. * Order of operation ENUMs.
  61. * http://docs.python.org/reference/expressions.html#summary
  62. */
  63. Blockly.Python.ORDER_ATOMIC = 0; // 0 "" ...
  64. Blockly.Python.ORDER_COLLECTION = 1; // tuples, lists, dictionaries
  65. Blockly.Python.ORDER_STRING_CONVERSION = 1; // `expression...`
  66. Blockly.Python.ORDER_MEMBER = 2.1; // . []
  67. Blockly.Python.ORDER_FUNCTION_CALL = 2.2; // ()
  68. Blockly.Python.ORDER_EXPONENTIATION = 3; // **
  69. Blockly.Python.ORDER_UNARY_SIGN = 4; // + -
  70. Blockly.Python.ORDER_BITWISE_NOT = 4; // ~
  71. Blockly.Python.ORDER_MULTIPLICATIVE = 5; // * / // %
  72. Blockly.Python.ORDER_ADDITIVE = 6; // + -
  73. Blockly.Python.ORDER_BITWISE_SHIFT = 7; // << >>
  74. Blockly.Python.ORDER_BITWISE_AND = 8; // &
  75. Blockly.Python.ORDER_BITWISE_XOR = 9; // ^
  76. Blockly.Python.ORDER_BITWISE_OR = 10; // |
  77. Blockly.Python.ORDER_RELATIONAL = 11; // in, not in, is, is not,
  78. // <, <=, >, >=, <>, !=, ==
  79. Blockly.Python.ORDER_LOGICAL_NOT = 12; // not
  80. Blockly.Python.ORDER_LOGICAL_AND = 13; // and
  81. Blockly.Python.ORDER_LOGICAL_OR = 14; // or
  82. Blockly.Python.ORDER_CONDITIONAL = 15; // if else
  83. Blockly.Python.ORDER_LAMBDA = 16; // lambda
  84. Blockly.Python.ORDER_NONE = 99; // (...)
  85. /**
  86. * Allow for switching between one and zero based indexing for lists and text,
  87. * one based by default.
  88. */
  89. Blockly.Python.ONE_BASED_INDEXING = true;
  90. /**
  91. * List of outer-inner pairings that do NOT require parentheses.
  92. * @type {!Array.<!Array.<number>>}
  93. */
  94. Blockly.Python.ORDER_OVERRIDES = [
  95. // (foo()).bar -> foo().bar
  96. // (foo())[0] -> foo()[0]
  97. [Blockly.Python.ORDER_FUNCTION_CALL, Blockly.Python.ORDER_MEMBER],
  98. // (foo())() -> foo()()
  99. [Blockly.Python.ORDER_FUNCTION_CALL, Blockly.Python.ORDER_FUNCTION_CALL],
  100. // (foo.bar).baz -> foo.bar.baz
  101. // (foo.bar)[0] -> foo.bar[0]
  102. // (foo[0]).bar -> foo[0].bar
  103. // (foo[0])[1] -> foo[0][1]
  104. [Blockly.Python.ORDER_MEMBER, Blockly.Python.ORDER_MEMBER],
  105. // (foo.bar)() -> foo.bar()
  106. // (foo[0])() -> foo[0]()
  107. [Blockly.Python.ORDER_MEMBER, Blockly.Python.ORDER_FUNCTION_CALL],
  108. // not (not foo) -> not not foo
  109. [Blockly.Python.ORDER_LOGICAL_NOT, Blockly.Python.ORDER_LOGICAL_NOT],
  110. // a and (b and c) -> a and b and c
  111. [Blockly.Python.ORDER_LOGICAL_AND, Blockly.Python.ORDER_LOGICAL_AND],
  112. // a or (b or c) -> a or b or c
  113. [Blockly.Python.ORDER_LOGICAL_OR, Blockly.Python.ORDER_LOGICAL_OR]
  114. ];
  115. /**
  116. * Initialise the database of variable names.
  117. * @param {!Blockly.Workspace} workspace Workspace to generate code from.
  118. */
  119. Blockly.Python.init = function(workspace) {
  120. /**
  121. * Empty loops or conditionals are not allowed in Python.
  122. */
  123. Blockly.Python.PASS = this.INDENT + 'pass\n';
  124. // Create a dictionary of definitions to be printed before the code.
  125. Blockly.Python.definitions_ = Object.create(null);
  126. // Create a dictionary mapping desired function names in definitions_
  127. // to actual function names (to avoid collisions with user functions).
  128. Blockly.Python.functionNames_ = Object.create(null);
  129. if (!Blockly.Python.variableDB_) {
  130. Blockly.Python.variableDB_ =
  131. new Blockly.Names(Blockly.Python.RESERVED_WORDS_);
  132. } else {
  133. Blockly.Python.variableDB_.reset();
  134. }
  135. var defvars = [];
  136. var variables = Blockly.Variables.allVariables(workspace);
  137. for (var i = 0; i < variables.length; i++) {
  138. defvars[i] = Blockly.Python.variableDB_.getName(variables[i],
  139. Blockly.Variables.NAME_TYPE) + ' = None';
  140. }
  141. Blockly.Python.definitions_['variables'] = defvars.join('\n');
  142. };
  143. /**
  144. * Prepend the generated code with the variable definitions.
  145. * @param {string} code Generated code.
  146. * @return {string} Completed code.
  147. */
  148. Blockly.Python.finish = function(code) {
  149. // Convert the definitions dictionary into a list.
  150. var imports = [];
  151. var definitions = [];
  152. for (var name in Blockly.Python.definitions_) {
  153. var def = Blockly.Python.definitions_[name];
  154. if (def.match(/^(from\s+\S+\s+)?import\s+\S+/)) {
  155. imports.push(def);
  156. } else {
  157. definitions.push(def);
  158. }
  159. }
  160. // Clean up temporary data.
  161. delete Blockly.Python.definitions_;
  162. delete Blockly.Python.functionNames_;
  163. Blockly.Python.variableDB_.reset();
  164. var allDefs = imports.join('\n') + '\n\n' + definitions.join('\n\n');
  165. return allDefs.replace(/\n\n+/g, '\n\n').replace(/\n*$/, '\n\n\n') + code;
  166. };
  167. /**
  168. * Naked values are top-level blocks with outputs that aren't plugged into
  169. * anything.
  170. * @param {string} line Line of generated code.
  171. * @return {string} Legal line of code.
  172. */
  173. Blockly.Python.scrubNakedValue = function(line) {
  174. return line + '\n';
  175. };
  176. /**
  177. * Encode a string as a properly escaped Python string, complete with quotes.
  178. * @param {string} string Text to encode.
  179. * @return {string} Python string.
  180. * @private
  181. */
  182. Blockly.Python.quote_ = function(string) {
  183. // Can't use goog.string.quote since % must also be escaped.
  184. string = string.replace(/\\/g, '\\\\')
  185. .replace(/\n/g, '\\\n')
  186. .replace(/\%/g, '\\%')
  187. .replace(/'/g, '\\\'');
  188. return '\'' + string + '\'';
  189. };
  190. /**
  191. * Common tasks for generating Python from blocks.
  192. * Handles comments for the specified block and any connected value blocks.
  193. * Calls any statements following this block.
  194. * @param {!Blockly.Block} block The current block.
  195. * @param {string} code The Python code created for this block.
  196. * @return {string} Python code with comments and subsequent blocks added.
  197. * @private
  198. */
  199. Blockly.Python.scrub_ = function(block, code) {
  200. var commentCode = '';
  201. // Only collect comments for blocks that aren't inline.
  202. if (!block.outputConnection || !block.outputConnection.targetConnection) {
  203. // Collect comment for this block.
  204. var comment = block.getCommentText();
  205. comment = Blockly.utils.wrap(comment, Blockly.Python.COMMENT_WRAP - 3);
  206. if (comment) {
  207. if (block.getProcedureDef) {
  208. // Use a comment block for function comments.
  209. commentCode += '"""' + comment + '\n"""\n';
  210. } else {
  211. commentCode += Blockly.Python.prefixLines(comment + '\n', '# ');
  212. }
  213. }
  214. // Collect comments for all value arguments.
  215. // Don't collect comments for nested statements.
  216. for (var i = 0; i < block.inputList.length; i++) {
  217. if (block.inputList[i].type == Blockly.INPUT_VALUE) {
  218. var childBlock = block.inputList[i].connection.targetBlock();
  219. if (childBlock) {
  220. var comment = Blockly.Python.allNestedComments(childBlock);
  221. if (comment) {
  222. commentCode += Blockly.Python.prefixLines(comment, '# ');
  223. }
  224. }
  225. }
  226. }
  227. }
  228. var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
  229. var nextCode = Blockly.Python.blockToCode(nextBlock);
  230. return commentCode + code + nextCode;
  231. };
  232. /**
  233. * Gets a property and adjusts the value, taking into account indexing, and
  234. * casts to an integer.
  235. * @param {!Blockly.Block} block The block.
  236. * @param {string} atId The property ID of the element to get.
  237. * @param {number=} opt_delta Value to add.
  238. * @param {boolean=} opt_negate Whether to negate the value.
  239. * @return {string|number}
  240. */
  241. Blockly.Python.getAdjustedInt = function(block, atId, opt_delta, opt_negate) {
  242. var delta = opt_delta || 0;
  243. if (Blockly.Python.ONE_BASED_INDEXING) {
  244. delta--;
  245. }
  246. var defaultAtIndex = Blockly.Python.ONE_BASED_INDEXING ? '1' : '0';
  247. var atOrder = delta ? Blockly.Python.ORDER_ADDITIVE :
  248. Blockly.Python.ORDER_NONE;
  249. var at = Blockly.Python.valueToCode(block, atId, atOrder) || defaultAtIndex;
  250. if (Blockly.isNumber(at)) {
  251. // If the index is a naked number, adjust it right now.
  252. at = parseInt(at, 10) + delta;
  253. if (opt_negate) {
  254. at = -at;
  255. }
  256. } else {
  257. // If the index is dynamic, adjust it in code.
  258. if (delta > 0) {
  259. at = 'int(' + at + ' + ' + delta + ')';
  260. } else if (delta < 0) {
  261. at = 'int(' + at + ' - ' + -delta + ')';
  262. } else {
  263. at = 'int(' + at + ')';
  264. }
  265. if (opt_negate) {
  266. at = '-' + at;
  267. }
  268. }
  269. return at;
  270. };