pseudo.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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 Pseudo-code for blocks.
  22. * @author acbart@vt.edu (Austin Cory Bart)
  23. */
  24. 'use strict';
  25. goog.provide('Blockly.Pseudo');
  26. goog.require('Blockly.Generator');
  27. /**
  28. * Pseudo code generator.
  29. * @type {!Blockly.Generator}
  30. */
  31. Blockly.Pseudo = new Blockly.Generator('Pseudo');
  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.Pseudo.addReservedWords(
  40. 'and,as,assert,break,class,continue,def,del,elif,else,except,exec,finally,for,from,global,if,import,in,is,lambda,not,or,pass,print,raise,return,try,while,with,yield,' +
  41. //http://docs.python.org/library/constants.html
  42. 'True,False,None,NotImplemented,Ellipsis,__debug__,quit,exit,copyright,license,credits,' +
  43. // Reserved libraries
  44. 'crime,stocks,earthquakes,books,weather,plt,math,'+
  45. // http://docs.python.org/library/functions.html
  46. 'abs,divmod,input,open,staticmethod,all,enumerate,int,ord,str,any,eval,isinstance,pow,sum,basestring,execfile,issubclass,print,super,bin,file,iter,property,tuple,bool,filter,len,range,type,bytearray,float,list,raw_input,unichr,callable,format,locals,reduce,unicode,chr,frozenset,long,reload,vars,classmethod,getattr,map,repr,xrange,cmp,globals,max,reversed,zip,compile,hasattr,memoryview,round,__import__,complex,hash,min,set,apply,delattr,help,next,setattr,buffer,dict,hex,object,slice,coerce,dir,id,oct,sorted,intern');
  47. /**
  48. * Order of operation ENUMs.
  49. * http://docs.python.org/reference/expressions.html#summary
  50. */
  51. Blockly.Pseudo.ORDER_ATOMIC = 0; // 0 "" ...
  52. Blockly.Pseudo.ORDER_COLLECTION = 1; // tuples, lists, dictionaries
  53. Blockly.Pseudo.ORDER_STRING_CONVERSION = 1; // `expression...`
  54. Blockly.Pseudo.ORDER_MEMBER = 2; // . []
  55. Blockly.Pseudo.ORDER_FUNCTION_CALL = 2; // ()
  56. Blockly.Pseudo.ORDER_EXPONENTIATION = 3; // **
  57. Blockly.Pseudo.ORDER_UNARY_SIGN = 4; // + -
  58. Blockly.Pseudo.ORDER_BITWISE_NOT = 4; // ~
  59. Blockly.Pseudo.ORDER_MULTIPLICATIVE = 5; // * / // %
  60. Blockly.Pseudo.ORDER_ADDITIVE = 6; // + -
  61. Blockly.Pseudo.ORDER_BITWISE_SHIFT = 7; // << >>
  62. Blockly.Pseudo.ORDER_BITWISE_AND = 8; // &
  63. Blockly.Pseudo.ORDER_BITWISE_XOR = 9; // ^
  64. Blockly.Pseudo.ORDER_BITWISE_OR = 10; // |
  65. Blockly.Pseudo.ORDER_RELATIONAL = 11; // in, not in, is, is not,
  66. // <, <=, >, >=, <>, !=, ==
  67. Blockly.Pseudo.ORDER_LOGICAL_NOT = 12; // not
  68. Blockly.Pseudo.ORDER_LOGICAL_AND = 13; // and
  69. Blockly.Pseudo.ORDER_LOGICAL_OR = 14; // or
  70. Blockly.Pseudo.ORDER_CONDITIONAL = 15; // if else
  71. Blockly.Pseudo.ORDER_LAMBDA = 16; // lambda
  72. Blockly.Pseudo.ORDER_NONE = 99; // (...)
  73. /**
  74. * Empty loops or conditionals are not allowed in Pseudo.
  75. */
  76. Blockly.Pseudo.PASS = ' Do nothing.\n';
  77. /**
  78. * Initialise the database of variable names.
  79. * @param {!Blockly.Workspace} workspace Workspace to generate code from.
  80. */
  81. Blockly.Pseudo.init = function(workspace) {
  82. // Create a dictionary of definitions to be printed before the code.
  83. Blockly.Pseudo.definitions_ = Object.create(null);
  84. // Create a dictionary mapping desired function names in definitions_
  85. // to actual function names (to avoid collisions with user functions).
  86. Blockly.Pseudo.functionNames_ = Object.create(null);
  87. if (!Blockly.Pseudo.variableDB_) {
  88. Blockly.Pseudo.variableDB_ =
  89. new Blockly.Names(Blockly.Pseudo.RESERVED_WORDS_);
  90. } else {
  91. Blockly.Pseudo.variableDB_.reset();
  92. }
  93. // Removed, because we shouldn't teach students to do this.
  94. /*var defvars = [];
  95. var variables = Blockly.Variables.allVariables(workspace);
  96. for (var i = 0; i < variables.length; i++) {
  97. defvars[i] = Blockly.Pseudo.variableDB_.getName(variables[i],
  98. Blockly.Variables.NAME_TYPE) + ' = None';
  99. }
  100. Blockly.Pseudo.definitions_['variables'] = defvars.join('\n');*/
  101. };
  102. /**
  103. * Prepend the generated code with the variable definitions.
  104. * @param {string} code Generated code.
  105. * @return {string} Completed code.
  106. */
  107. Blockly.Pseudo.finish = function(code) {
  108. // Convert the definitions dictionary into a list.
  109. var imports = [];
  110. var definitions = [];
  111. for (var name in Blockly.Pseudo.definitions_) {
  112. var def = Blockly.Pseudo.definitions_[name];
  113. if (def.match(/^(from\s+\S+\s+)?import\s+\S+/)) {
  114. imports.push(def);
  115. } else {
  116. definitions.push(def);
  117. }
  118. }
  119. // Clean up temporary data.
  120. delete Blockly.Pseudo.definitions_;
  121. delete Blockly.Pseudo.functionNames_;
  122. Blockly.Pseudo.variableDB_.reset();
  123. var allDefs = imports.join('\n') + '\n' + definitions.join('\n\n');
  124. return allDefs.replace(/\n\n+/g, '\n').replace(/\n*$/, '\n\n') + code;
  125. };
  126. /**
  127. * Naked values are top-level blocks with outputs that aren't plugged into
  128. * anything.
  129. * @param {string} line Line of generated code.
  130. * @return {string} Legal line of code.
  131. */
  132. Blockly.Pseudo.scrubNakedValue = function(line) {
  133. return line + '\n';
  134. };
  135. /**
  136. * Encode a string as a properly escaped Pseudo string, complete with quotes.
  137. * @param {string} string Text to encode.
  138. * @return {string} Pseudo string.
  139. * @private
  140. */
  141. Blockly.Pseudo.quote_ = function(string) {
  142. // TODO: This is a quick hack. Replace with goog.string.quote
  143. string = string.replace(/\\/g, '\\\\')
  144. .replace(/\n/g, '\\\n');
  145. if (string.indexOf('"') > -1 && string.indexOf('"') == -1) {
  146. return '\'' + string + '\'';
  147. } else if (string.indexOf('"') == -1 && string.indexOf('"') > -1) {
  148. return '"' + string + '"';
  149. } else {
  150. string = string.replace(/"/g, '\\\"');
  151. return '"' + string + '"';
  152. }
  153. };
  154. /**
  155. * Common tasks for generating Pseudo from blocks.
  156. * Handles comments for the specified block and any connected value blocks.
  157. * Calls any statements following this block.
  158. * @param {!Blockly.Block} block The current block.
  159. * @param {string} code The Pseudo code created for this block.
  160. * @return {string} Pseudo code with comments and subsequent blocks added.
  161. * @private
  162. */
  163. Blockly.Pseudo.scrub_ = function(block, code) {
  164. var commentCode = '';
  165. // Only collect comments for blocks that aren't inline.
  166. if (!block.outputConnection || !block.outputConnection.targetConnection) {
  167. // Collect comment for this block.
  168. var comment = block.getCommentText();
  169. if (comment) {
  170. commentCode += Blockly.Pseudo.prefixLines(comment, '# ') + '\n';
  171. }
  172. // Collect comments for all value arguments.
  173. // Don't collect comments for nested statements.
  174. for (var x = 0; x < block.inputList.length; x++) {
  175. if (block.inputList[x].type == Blockly.INPUT_VALUE) {
  176. var childBlock = block.inputList[x].connection.targetBlock();
  177. if (childBlock) {
  178. var comment = Blockly.Pseudo.allNestedComments(childBlock);
  179. if (comment) {
  180. commentCode += Blockly.Pseudo.prefixLines(comment, '# ');
  181. }
  182. }
  183. }
  184. }
  185. }
  186. var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
  187. var nextCode = Blockly.Pseudo.blockToCode(nextBlock);
  188. return commentCode + code + nextCode;
  189. };