loops.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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 Generating Python for loop blocks.
  22. * @author q.neutron@gmail.com (Quynh Neutron)
  23. */
  24. 'use strict';
  25. goog.provide('Blockly.Python.loops');
  26. goog.require('Blockly.Python');
  27. Blockly.Python['controls_repeat_ext'] = function(block) {
  28. // Repeat n times.
  29. if (block.getField('TIMES')) {
  30. // Internal number.
  31. var repeats = String(parseInt(block.getFieldValue('TIMES'), 10));
  32. } else {
  33. // External number.
  34. var repeats = Blockly.Python.valueToCode(block, 'TIMES',
  35. Blockly.Python.ORDER_NONE) || '0';
  36. }
  37. if (Blockly.isNumber(repeats)) {
  38. repeats = parseInt(repeats, 10);
  39. } else {
  40. repeats = 'int(' + repeats + ')';
  41. }
  42. var branch = Blockly.Python.statementToCode(block, 'DO');
  43. branch = Blockly.Python.addLoopTrap(branch, block.id) ||
  44. Blockly.Python.PASS;
  45. var loopVar = Blockly.Python.variableDB_.getDistinctName(
  46. 'count', Blockly.Variables.NAME_TYPE);
  47. var code = 'for ' + loopVar + ' in range(' + repeats + '):\n' + branch;
  48. return code;
  49. };
  50. Blockly.Python['controls_repeat'] = Blockly.Python['controls_repeat_ext'];
  51. Blockly.Python['controls_whileUntil'] = function(block) {
  52. // Do while/until loop.
  53. var until = block.getFieldValue('MODE') == 'UNTIL';
  54. var argument0 = Blockly.Python.valueToCode(block, 'BOOL',
  55. until ? Blockly.Python.ORDER_LOGICAL_NOT :
  56. Blockly.Python.ORDER_NONE) || 'False';
  57. var branch = Blockly.Python.statementToCode(block, 'DO');
  58. branch = Blockly.Python.addLoopTrap(branch, block.id) ||
  59. Blockly.Python.PASS;
  60. if (until) {
  61. argument0 = 'not ' + argument0;
  62. }
  63. return 'while ' + argument0 + ':\n' + branch;
  64. };
  65. Blockly.Python['controls_for'] = function(block) {
  66. // For loop.
  67. var variable0 = Blockly.Python.variableDB_.getName(
  68. block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
  69. var argument0 = Blockly.Python.valueToCode(block, 'FROM',
  70. Blockly.Python.ORDER_NONE) || '0';
  71. var argument1 = Blockly.Python.valueToCode(block, 'TO',
  72. Blockly.Python.ORDER_NONE) || '0';
  73. var increment = Blockly.Python.valueToCode(block, 'BY',
  74. Blockly.Python.ORDER_NONE) || '1';
  75. var branch = Blockly.Python.statementToCode(block, 'DO');
  76. branch = Blockly.Python.addLoopTrap(branch, block.id) ||
  77. Blockly.Python.PASS;
  78. var code = '';
  79. var range;
  80. // Helper functions.
  81. var defineUpRange = function() {
  82. return Blockly.Python.provideFunction_(
  83. 'upRange',
  84. ['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
  85. '(start, stop, step):',
  86. ' while start <= stop:',
  87. ' yield start',
  88. ' start += abs(step)']);
  89. };
  90. var defineDownRange = function() {
  91. return Blockly.Python.provideFunction_(
  92. 'downRange',
  93. ['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ +
  94. '(start, stop, step):',
  95. ' while start >= stop:',
  96. ' yield start',
  97. ' start -= abs(step)']);
  98. };
  99. // Arguments are legal Python code (numbers or strings returned by scrub()).
  100. var generateUpDownRange = function(start, end, inc) {
  101. return '(' + start + ' <= ' + end + ') and ' +
  102. defineUpRange() + '(' + start + ', ' + end + ', ' + inc + ') or ' +
  103. defineDownRange() + '(' + start + ', ' + end + ', ' + inc + ')';
  104. };
  105. if (Blockly.isNumber(argument0) && Blockly.isNumber(argument1) &&
  106. Blockly.isNumber(increment)) {
  107. // All parameters are simple numbers.
  108. argument0 = parseFloat(argument0);
  109. argument1 = parseFloat(argument1);
  110. increment = Math.abs(parseFloat(increment));
  111. if (argument0 % 1 === 0 && argument1 % 1 === 0 && increment % 1 === 0) {
  112. // All parameters are integers.
  113. if (argument0 <= argument1) {
  114. // Count up.
  115. argument1++;
  116. if (argument0 == 0 && increment == 1) {
  117. // If starting index is 0, omit it.
  118. range = argument1;
  119. } else {
  120. range = argument0 + ', ' + argument1;
  121. }
  122. // If increment isn't 1, it must be explicit.
  123. if (increment != 1) {
  124. range += ', ' + increment;
  125. }
  126. } else {
  127. // Count down.
  128. argument1--;
  129. range = argument0 + ', ' + argument1 + ', -' + increment;
  130. }
  131. range = 'range(' + range + ')';
  132. } else {
  133. // At least one of the parameters is not an integer.
  134. if (argument0 < argument1) {
  135. range = defineUpRange();
  136. } else {
  137. range = defineDownRange();
  138. }
  139. range += '(' + argument0 + ', ' + argument1 + ', ' + increment + ')';
  140. }
  141. } else {
  142. // Cache non-trivial values to variables to prevent repeated look-ups.
  143. var scrub = function(arg, suffix) {
  144. if (Blockly.isNumber(arg)) {
  145. // Simple number.
  146. arg = parseFloat(arg);
  147. } else if (arg.match(/^\w+$/)) {
  148. // Variable.
  149. arg = 'float(' + arg + ')';
  150. } else {
  151. // It's complicated.
  152. var varName = Blockly.Python.variableDB_.getDistinctName(
  153. variable0 + suffix, Blockly.Variables.NAME_TYPE);
  154. code += varName + ' = float(' + arg + ')\n';
  155. arg = varName;
  156. }
  157. return arg;
  158. };
  159. var startVar = scrub(argument0, '_start');
  160. var endVar = scrub(argument1, '_end');
  161. var incVar = scrub(increment, '_inc');
  162. if (typeof startVar == 'number' && typeof endVar == 'number') {
  163. if (startVar < endVar) {
  164. range = defineUpRange(startVar, endVar, increment);
  165. } else {
  166. range = defineDownRange(startVar, endVar, increment);
  167. }
  168. } else {
  169. // We cannot determine direction statically.
  170. range = generateUpDownRange(startVar, endVar, increment);
  171. }
  172. }
  173. code += 'for ' + variable0 + ' in ' + range + ':\n' + branch;
  174. return code;
  175. };
  176. Blockly.Python['controls_forEach'] = function(block) {
  177. // For each loop.
  178. var variable0 = Blockly.Python.variableDB_.getName(
  179. block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE);
  180. var argument0 = Blockly.Python.valueToCode(block, 'LIST',
  181. Blockly.Python.ORDER_RELATIONAL) || '[]';
  182. var branch = Blockly.Python.statementToCode(block, 'DO');
  183. branch = Blockly.Python.addLoopTrap(branch, block.id) ||
  184. Blockly.Python.PASS;
  185. var code = 'for ' + variable0 + ' in ' + argument0 + ':\n' + branch;
  186. return code;
  187. };
  188. Blockly.Python['controls_flow_statements'] = function(block) {
  189. // Flow statements: continue, break.
  190. switch (block.getFieldValue('FLOW')) {
  191. case 'BREAK':
  192. return 'break\n';
  193. case 'CONTINUE':
  194. return 'continue\n';
  195. }
  196. throw 'Unknown flow statement.';
  197. };