refactor(generators)!: Pass this CodeGenerator to individual generator functions (#7168)

* feat(generators): Pass this CodeGenerator to generator functions

  This implements option 1A of proposal 1 of #7086.

  This commit is not by itself a breaking change, except in the unlikely event that
  developers' custom generator functions take an (optional) second argument of a
  dfferent type.

* feat(generators): Accept generator argument in block functions

  Accept a CodeGenerator instance as parameter two of every
  per-block-type generator function.

* fix(generators): Pass generator when calling other generator functions

  Make sure to pass generator to any other block functions that are
  called recursively.

* refactor(generators)!: Use generator argument in generator functions

  Refactor per-block-type generator functions to use the provided
  generator argument to make recursive calls, rather than depending
  on the closed-over <lang>Generator instance.

  This allows generator functions to be moved between CodeGenerator
  instances (of the same language, at least).

  This commit was created by search-and-replace and addresses most
  but not all recursive references; remaining uses will require
  manual attention and will be dealt with in a following commit.

  BREAKING CHANGE: This commit makes the generator functions we provide
  dependent on the new generator parameter.  Although
  CodeGenerator.prototype.blockToCode has been modified to supply this,
  so this change will not affect most developers, this change will be a
  breaking change where developers make direct calls to these generator
  functions without supplying the generator parameter.  See previous
  commit for an example of the update required.

* refactor(generators): Manual fix for remaining uses of langGenerator

  Manually replace remaining uses of <lang>Generator in block
  generator functions.

* fix(generators): Delete duplicate procedures_callnoreturn generator

  For some reason the generator function for procedures_callnoreturn
  appears twice in generators/javascript/procedures.js.  Delete the
  first copy (since the second one overwrote it anyway).

* chore(generators): Format
This commit is contained in:
Christopher Allen
2023-06-14 23:25:36 +01:00
committed by GitHub
parent 12b91ae49c
commit a3458871db
44 changed files with 1474 additions and 1477 deletions

View File

@@ -14,39 +14,39 @@ goog.declareModuleId('Blockly.Python.colour');
import {pythonGenerator, Order} from '../python.js';
pythonGenerator.forBlock['colour_picker'] = function(block) {
pythonGenerator.forBlock['colour_picker'] = function(block, generator) {
// Colour picker.
const code = pythonGenerator.quote_(block.getFieldValue('COLOUR'));
const code = generator.quote_(block.getFieldValue('COLOUR'));
return [code, Order.ATOMIC];
};
pythonGenerator.forBlock['colour_random'] = function(block) {
pythonGenerator.forBlock['colour_random'] = function(block, generator) {
// Generate a random colour.
pythonGenerator.definitions_['import_random'] = 'import random';
generator.definitions_['import_random'] = 'import random';
const code = '\'#%06x\' % random.randint(0, 2**24 - 1)';
return [code, Order.FUNCTION_CALL];
};
pythonGenerator.forBlock['colour_rgb'] = function(block) {
pythonGenerator.forBlock['colour_rgb'] = function(block, generator) {
// Compose a colour from RGB components expressed as percentages.
const functionName = pythonGenerator.provideFunction_('colour_rgb', `
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(r, g, b):
const functionName = generator.provideFunction_('colour_rgb', `
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(r, g, b):
r = round(min(100, max(0, r)) * 2.55)
g = round(min(100, max(0, g)) * 2.55)
b = round(min(100, max(0, b)) * 2.55)
return '#%02x%02x%02x' % (r, g, b)
`);
const r = pythonGenerator.valueToCode(block, 'RED', Order.NONE) || 0;
const g = pythonGenerator.valueToCode(block, 'GREEN', Order.NONE) || 0;
const b = pythonGenerator.valueToCode(block, 'BLUE', Order.NONE) || 0;
const r = generator.valueToCode(block, 'RED', Order.NONE) || 0;
const g = generator.valueToCode(block, 'GREEN', Order.NONE) || 0;
const b = generator.valueToCode(block, 'BLUE', Order.NONE) || 0;
const code = functionName + '(' + r + ', ' + g + ', ' + b + ')';
return [code, Order.FUNCTION_CALL];
};
pythonGenerator.forBlock['colour_blend'] = function(block) {
pythonGenerator.forBlock['colour_blend'] = function(block, generator) {
// Blend two colours together.
const functionName = pythonGenerator.provideFunction_('colour_blend', `
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(colour1, colour2, ratio):
const functionName = generator.provideFunction_('colour_blend', `
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(colour1, colour2, ratio):
r1, r2 = int(colour1[1:3], 16), int(colour2[1:3], 16)
g1, g2 = int(colour1[3:5], 16), int(colour2[3:5], 16)
b1, b2 = int(colour1[5:7], 16), int(colour2[5:7], 16)
@@ -57,12 +57,12 @@ def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(colour1, colour2, ratio):
return '#%02x%02x%02x' % (r, g, b)
`);
const colour1 =
pythonGenerator.valueToCode(block, 'COLOUR1', Order.NONE)
generator.valueToCode(block, 'COLOUR1', Order.NONE)
|| '\'#000000\'';
const colour2 =
pythonGenerator.valueToCode(block, 'COLOUR2', Order.NONE)
generator.valueToCode(block, 'COLOUR2', Order.NONE)
|| '\'#000000\'';
const ratio = pythonGenerator.valueToCode(block, 'RATIO', Order.NONE) || 0;
const ratio = generator.valueToCode(block, 'RATIO', Order.NONE) || 0;
const code =
functionName + '(' + colour1 + ', ' + colour2 + ', ' + ratio + ')';
return [code, Order.FUNCTION_CALL];

View File

@@ -16,48 +16,48 @@ import {NameType} from '../../core/names.js';
import {pythonGenerator, Order} from '../python.js';
pythonGenerator.forBlock['lists_create_empty'] = function(block) {
pythonGenerator.forBlock['lists_create_empty'] = function(block, generator) {
// Create an empty list.
return ['[]', Order.ATOMIC];
};
pythonGenerator.forBlock['lists_create_with'] = function(block) {
pythonGenerator.forBlock['lists_create_with'] = function(block, generator) {
// Create a list with any number of elements of any type.
const elements = new Array(block.itemCount_);
for (let i = 0; i < block.itemCount_; i++) {
elements[i] =
pythonGenerator.valueToCode(block, 'ADD' + i, Order.NONE) || 'None';
generator.valueToCode(block, 'ADD' + i, Order.NONE) || 'None';
}
const code = '[' + elements.join(', ') + ']';
return [code, Order.ATOMIC];
};
pythonGenerator.forBlock['lists_repeat'] = function(block) {
pythonGenerator.forBlock['lists_repeat'] = function(block, generator) {
// Create a list with one element repeated.
const item = pythonGenerator.valueToCode(block, 'ITEM', Order.NONE) || 'None';
const item = generator.valueToCode(block, 'ITEM', Order.NONE) || 'None';
const times =
pythonGenerator.valueToCode(block, 'NUM', Order.MULTIPLICATIVE) || '0';
generator.valueToCode(block, 'NUM', Order.MULTIPLICATIVE) || '0';
const code = '[' + item + '] * ' + times;
return [code, Order.MULTIPLICATIVE];
};
pythonGenerator.forBlock['lists_length'] = function(block) {
pythonGenerator.forBlock['lists_length'] = function(block, generator) {
// String or array length.
const list = pythonGenerator.valueToCode(block, 'VALUE', Order.NONE) || '[]';
const list = generator.valueToCode(block, 'VALUE', Order.NONE) || '[]';
return ['len(' + list + ')', Order.FUNCTION_CALL];
};
pythonGenerator.forBlock['lists_isEmpty'] = function(block) {
pythonGenerator.forBlock['lists_isEmpty'] = function(block, generator) {
// Is the string null or array empty?
const list = pythonGenerator.valueToCode(block, 'VALUE', Order.NONE) || '[]';
const list = generator.valueToCode(block, 'VALUE', Order.NONE) || '[]';
const code = 'not len(' + list + ')';
return [code, Order.LOGICAL_NOT];
};
pythonGenerator.forBlock['lists_indexOf'] = function(block) {
pythonGenerator.forBlock['lists_indexOf'] = function(block, generator) {
// Find an item in the list.
const item = pythonGenerator.valueToCode(block, 'FIND', Order.NONE) || '[]';
const list = pythonGenerator.valueToCode(block, 'VALUE', Order.NONE) || "''";
const item = generator.valueToCode(block, 'FIND', Order.NONE) || '[]';
const list = generator.valueToCode(block, 'VALUE', Order.NONE) || "''";
let errorIndex = ' -1';
let firstIndexAdjustment = '';
let lastIndexAdjustment = ' - 1';
@@ -70,15 +70,15 @@ pythonGenerator.forBlock['lists_indexOf'] = function(block) {
let functionName;
if (block.getFieldValue('END') === 'FIRST') {
functionName = pythonGenerator.provideFunction_('first_index', `
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(my_list, elem):
functionName = generator.provideFunction_('first_index', `
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(my_list, elem):
try: index = my_list.index(elem)${firstIndexAdjustment}
except: index =${errorIndex}
return index
`);
} else {
functionName = pythonGenerator.provideFunction_('last_index', `
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(my_list, elem):
functionName = generator.provideFunction_('last_index', `
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(my_list, elem):
try: index = len(my_list) - my_list[::-1].index(elem)${lastIndexAdjustment}
except: index =${errorIndex}
return index
@@ -88,14 +88,14 @@ def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(my_list, elem):
return [code, Order.FUNCTION_CALL];
};
pythonGenerator.forBlock['lists_getIndex'] = function(block) {
pythonGenerator.forBlock['lists_getIndex'] = function(block, generator) {
// Get element at index.
// Note: Until January 2013 this block did not have MODE or WHERE inputs.
const mode = block.getFieldValue('MODE') || 'GET';
const where = block.getFieldValue('WHERE') || 'FROM_START';
const listOrder =
(where === 'RANDOM') ? Order.NONE : Order.MEMBER;
const list = pythonGenerator.valueToCode(block, 'VALUE', listOrder) || '[]';
const list = generator.valueToCode(block, 'VALUE', listOrder) || '[]';
switch (where) {
case 'FIRST':
@@ -121,7 +121,7 @@ pythonGenerator.forBlock['lists_getIndex'] = function(block) {
}
break;
case 'FROM_START': {
const at = pythonGenerator.getAdjustedInt(block, 'AT');
const at = generator.getAdjustedInt(block, 'AT');
if (mode === 'GET') {
const code = list + '[' + at + ']';
return [code, Order.MEMBER];
@@ -134,7 +134,7 @@ pythonGenerator.forBlock['lists_getIndex'] = function(block) {
break;
}
case 'FROM_END': {
const at = pythonGenerator.getAdjustedInt(block, 'AT', 1, true);
const at = generator.getAdjustedInt(block, 'AT', 1, true);
if (mode === 'GET') {
const code = list + '[' + at + ']';
return [code, Order.MEMBER];
@@ -147,14 +147,14 @@ pythonGenerator.forBlock['lists_getIndex'] = function(block) {
break;
}
case 'RANDOM':
pythonGenerator.definitions_['import_random'] = 'import random';
generator.definitions_['import_random'] = 'import random';
if (mode === 'GET') {
const code = 'random.choice(' + list + ')';
return [code, Order.FUNCTION_CALL];
} else {
const functionName =
pythonGenerator.provideFunction_('lists_remove_random_item', `
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(myList):
generator.provideFunction_('lists_remove_random_item', `
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(myList):
x = int(random.random() * len(myList))
return myList.pop(x)
`);
@@ -170,13 +170,13 @@ def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(myList):
throw Error('Unhandled combination (lists_getIndex).');
};
pythonGenerator.forBlock['lists_setIndex'] = function(block) {
pythonGenerator.forBlock['lists_setIndex'] = function(block, generator) {
// Set element at index.
// Note: Until February 2013 this block did not have MODE or WHERE inputs.
let list = pythonGenerator.valueToCode(block, 'LIST', Order.MEMBER) || '[]';
let list = generator.valueToCode(block, 'LIST', Order.MEMBER) || '[]';
const mode = block.getFieldValue('MODE') || 'GET';
const where = block.getFieldValue('WHERE') || 'FROM_START';
const value = pythonGenerator.valueToCode(block, 'TO', Order.NONE) || 'None';
const value = generator.valueToCode(block, 'TO', Order.NONE) || 'None';
// Cache non-trivial values to variables to prevent repeated look-ups.
// Closure, which accesses and modifies 'list'.
function cacheList() {
@@ -184,7 +184,7 @@ pythonGenerator.forBlock['lists_setIndex'] = function(block) {
return '';
}
const listVar =
pythonGenerator.nameDB_.getDistinctName('tmp_list', NameType.VARIABLE);
generator.nameDB_.getDistinctName('tmp_list', NameType.VARIABLE);
const code = listVar + ' = ' + list + '\n';
list = listVar;
return code;
@@ -206,7 +206,7 @@ pythonGenerator.forBlock['lists_setIndex'] = function(block) {
}
break;
case 'FROM_START': {
const at = pythonGenerator.getAdjustedInt(block, 'AT');
const at = generator.getAdjustedInt(block, 'AT');
if (mode === 'SET') {
return list + '[' + at + '] = ' + value + '\n';
} else if (mode === 'INSERT') {
@@ -215,7 +215,7 @@ pythonGenerator.forBlock['lists_setIndex'] = function(block) {
break;
}
case 'FROM_END': {
const at = pythonGenerator.getAdjustedInt(block, 'AT', 1, true);
const at = generator.getAdjustedInt(block, 'AT', 1, true);
if (mode === 'SET') {
return list + '[' + at + '] = ' + value + '\n';
} else if (mode === 'INSERT') {
@@ -224,10 +224,10 @@ pythonGenerator.forBlock['lists_setIndex'] = function(block) {
break;
}
case 'RANDOM': {
pythonGenerator.definitions_['import_random'] = 'import random';
generator.definitions_['import_random'] = 'import random';
let code = cacheList();
const xVar =
pythonGenerator.nameDB_.getDistinctName('tmp_x', NameType.VARIABLE);
generator.nameDB_.getDistinctName('tmp_x', NameType.VARIABLE);
code += xVar + ' = int(random.random() * len(' + list + '))\n';
if (mode === 'SET') {
code += list + '[' + xVar + '] = ' + value + '\n';
@@ -242,21 +242,21 @@ pythonGenerator.forBlock['lists_setIndex'] = function(block) {
throw Error('Unhandled combination (lists_setIndex).');
};
pythonGenerator.forBlock['lists_getSublist'] = function(block) {
pythonGenerator.forBlock['lists_getSublist'] = function(block, generator) {
// Get sublist.
const list = pythonGenerator.valueToCode(block, 'LIST', Order.MEMBER) || '[]';
const list = generator.valueToCode(block, 'LIST', Order.MEMBER) || '[]';
const where1 = block.getFieldValue('WHERE1');
const where2 = block.getFieldValue('WHERE2');
let at1;
switch (where1) {
case 'FROM_START':
at1 = pythonGenerator.getAdjustedInt(block, 'AT1');
at1 = generator.getAdjustedInt(block, 'AT1');
if (at1 === 0) {
at1 = '';
}
break;
case 'FROM_END':
at1 = pythonGenerator.getAdjustedInt(block, 'AT1', 1, true);
at1 = generator.getAdjustedInt(block, 'AT1', 1, true);
break;
case 'FIRST':
at1 = '';
@@ -268,14 +268,14 @@ pythonGenerator.forBlock['lists_getSublist'] = function(block) {
let at2;
switch (where2) {
case 'FROM_START':
at2 = pythonGenerator.getAdjustedInt(block, 'AT2', 1);
at2 = generator.getAdjustedInt(block, 'AT2', 1);
break;
case 'FROM_END':
at2 = pythonGenerator.getAdjustedInt(block, 'AT2', 0, true);
at2 = generator.getAdjustedInt(block, 'AT2', 0, true);
// Ensure that if the result calculated is 0 that sub-sequence will
// include all elements as expected.
if (!stringUtils.isNumber(String(at2))) {
pythonGenerator.definitions_['import_sys'] = 'import sys';
generator.definitions_['import_sys'] = 'import sys';
at2 += ' or sys.maxsize';
} else if (at2 === 0) {
at2 = '';
@@ -291,13 +291,13 @@ pythonGenerator.forBlock['lists_getSublist'] = function(block) {
return [code, Order.MEMBER];
};
pythonGenerator.forBlock['lists_sort'] = function(block) {
pythonGenerator.forBlock['lists_sort'] = function(block, generator) {
// Block for sorting a list.
const list = (pythonGenerator.valueToCode(block, 'LIST', Order.NONE) || '[]');
const list = (generator.valueToCode(block, 'LIST', Order.NONE) || '[]');
const type = block.getFieldValue('TYPE');
const reverse = block.getFieldValue('DIRECTION') === '1' ? 'False' : 'True';
const sortFunctionName = pythonGenerator.provideFunction_('lists_sort', `
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(my_list, type, reverse):
const sortFunctionName = generator.provideFunction_('lists_sort', `
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(my_list, type, reverse):
def try_float(s):
try:
return float(s)
@@ -318,20 +318,20 @@ def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(my_list, type, reverse):
return [code, Order.FUNCTION_CALL];
};
pythonGenerator.forBlock['lists_split'] = function(block) {
pythonGenerator.forBlock['lists_split'] = function(block, generator) {
// Block for splitting text into a list, or joining a list into text.
const mode = block.getFieldValue('MODE');
let code;
if (mode === 'SPLIT') {
const value_input =
pythonGenerator.valueToCode(block, 'INPUT', Order.MEMBER) || "''";
const value_delim = pythonGenerator.valueToCode(block, 'DELIM', Order.NONE);
generator.valueToCode(block, 'INPUT', Order.MEMBER) || "''";
const value_delim = generator.valueToCode(block, 'DELIM', Order.NONE);
code = value_input + '.split(' + value_delim + ')';
} else if (mode === 'JOIN') {
const value_input =
pythonGenerator.valueToCode(block, 'INPUT', Order.NONE) || '[]';
generator.valueToCode(block, 'INPUT', Order.NONE) || '[]';
const value_delim =
pythonGenerator.valueToCode(block, 'DELIM', Order.MEMBER) || "''";
generator.valueToCode(block, 'DELIM', Order.MEMBER) || "''";
code = value_delim + '.join(' + value_input + ')';
} else {
throw Error('Unknown mode: ' + mode);
@@ -339,9 +339,9 @@ pythonGenerator.forBlock['lists_split'] = function(block) {
return [code, Order.FUNCTION_CALL];
};
pythonGenerator.forBlock['lists_reverse'] = function(block) {
pythonGenerator.forBlock['lists_reverse'] = function(block, generator) {
// Block for reversing a list.
const list = pythonGenerator.valueToCode(block, 'LIST', Order.NONE) || '[]';
const list = generator.valueToCode(block, 'LIST', Order.NONE) || '[]';
const code = 'list(reversed(' + list + '))';
return [code, Order.FUNCTION_CALL];
};

View File

@@ -14,40 +14,40 @@ goog.declareModuleId('Blockly.Python.logic');
import {pythonGenerator, Order} from '../python.js';
pythonGenerator.forBlock['controls_if'] = function(block) {
pythonGenerator.forBlock['controls_if'] = function(block, generator) {
// If/elseif/else condition.
let n = 0;
let code = '', branchCode, conditionCode;
if (pythonGenerator.STATEMENT_PREFIX) {
if (generator.STATEMENT_PREFIX) {
// Automatic prefix insertion is switched off for this block. Add manually.
code += pythonGenerator.injectId(pythonGenerator.STATEMENT_PREFIX, block);
code += generator.injectId(generator.STATEMENT_PREFIX, block);
}
do {
conditionCode =
pythonGenerator.valueToCode(block, 'IF' + n, Order.NONE) || 'False';
generator.valueToCode(block, 'IF' + n, Order.NONE) || 'False';
branchCode =
pythonGenerator.statementToCode(block, 'DO' + n) ||
pythonGenerator.PASS;
if (pythonGenerator.STATEMENT_SUFFIX) {
generator.statementToCode(block, 'DO' + n) ||
generator.PASS;
if (generator.STATEMENT_SUFFIX) {
branchCode =
pythonGenerator.prefixLines(
pythonGenerator.injectId(pythonGenerator.STATEMENT_SUFFIX, block),
pythonGenerator.INDENT) +
generator.prefixLines(
generator.injectId(generator.STATEMENT_SUFFIX, block),
generator.INDENT) +
branchCode;
}
code += (n === 0 ? 'if ' : 'elif ') + conditionCode + ':\n' + branchCode;
n++;
} while (block.getInput('IF' + n));
if (block.getInput('ELSE') || pythonGenerator.STATEMENT_SUFFIX) {
if (block.getInput('ELSE') || generator.STATEMENT_SUFFIX) {
branchCode =
pythonGenerator.statementToCode(block, 'ELSE') || pythonGenerator.PASS;
if (pythonGenerator.STATEMENT_SUFFIX) {
generator.statementToCode(block, 'ELSE') || generator.PASS;
if (generator.STATEMENT_SUFFIX) {
branchCode =
pythonGenerator.prefixLines(
pythonGenerator.injectId(
pythonGenerator.STATEMENT_SUFFIX, block),
pythonGenerator.INDENT) +
generator.prefixLines(
generator.injectId(
generator.STATEMENT_SUFFIX, block),
generator.INDENT) +
branchCode;
}
code += 'else:\n' + branchCode;
@@ -58,25 +58,25 @@ pythonGenerator.forBlock['controls_if'] = function(block) {
pythonGenerator.forBlock['controls_ifelse'] =
pythonGenerator.forBlock['controls_if'];
pythonGenerator.forBlock['logic_compare'] = function(block) {
pythonGenerator.forBlock['logic_compare'] = function(block, generator) {
// Comparison operator.
const OPERATORS =
{'EQ': '==', 'NEQ': '!=', 'LT': '<', 'LTE': '<=', 'GT': '>', 'GTE': '>='};
const operator = OPERATORS[block.getFieldValue('OP')];
const order = Order.RELATIONAL;
const argument0 = pythonGenerator.valueToCode(block, 'A', order) || '0';
const argument1 = pythonGenerator.valueToCode(block, 'B', order) || '0';
const argument0 = generator.valueToCode(block, 'A', order) || '0';
const argument1 = generator.valueToCode(block, 'B', order) || '0';
const code = argument0 + ' ' + operator + ' ' + argument1;
return [code, order];
};
pythonGenerator.forBlock['logic_operation'] = function(block) {
pythonGenerator.forBlock['logic_operation'] = function(block, generator) {
// Operations 'and', 'or'.
const operator = (block.getFieldValue('OP') === 'AND') ? 'and' : 'or';
const order =
(operator === 'and') ? Order.LOGICAL_AND : Order.LOGICAL_OR;
let argument0 = pythonGenerator.valueToCode(block, 'A', order);
let argument1 = pythonGenerator.valueToCode(block, 'B', order);
let argument0 = generator.valueToCode(block, 'A', order);
let argument1 = generator.valueToCode(block, 'B', order);
if (!argument0 && !argument1) {
// If there are no arguments, then the return value is false.
argument0 = 'False';
@@ -95,33 +95,33 @@ pythonGenerator.forBlock['logic_operation'] = function(block) {
return [code, order];
};
pythonGenerator.forBlock['logic_negate'] = function(block) {
pythonGenerator.forBlock['logic_negate'] = function(block, generator) {
// Negation.
const argument0 =
pythonGenerator.valueToCode(block, 'BOOL', Order.LOGICAL_NOT) || 'True';
generator.valueToCode(block, 'BOOL', Order.LOGICAL_NOT) || 'True';
const code = 'not ' + argument0;
return [code, Order.LOGICAL_NOT];
};
pythonGenerator.forBlock['logic_boolean'] = function(block) {
pythonGenerator.forBlock['logic_boolean'] = function(block, generator) {
// Boolean values true and false.
const code = (block.getFieldValue('BOOL') === 'TRUE') ? 'True' : 'False';
return [code, Order.ATOMIC];
};
pythonGenerator.forBlock['logic_null'] = function(block) {
pythonGenerator.forBlock['logic_null'] = function(block, generator) {
// Null data type.
return ['None', Order.ATOMIC];
};
pythonGenerator.forBlock['logic_ternary'] = function(block) {
pythonGenerator.forBlock['logic_ternary'] = function(block, generator) {
// Ternary operator.
const value_if =
pythonGenerator.valueToCode(block, 'IF', Order.CONDITIONAL) || 'False';
generator.valueToCode(block, 'IF', Order.CONDITIONAL) || 'False';
const value_then =
pythonGenerator.valueToCode(block, 'THEN', Order.CONDITIONAL) || 'None';
generator.valueToCode(block, 'THEN', Order.CONDITIONAL) || 'None';
const value_else =
pythonGenerator.valueToCode(block, 'ELSE', Order.CONDITIONAL) || 'None';
generator.valueToCode(block, 'ELSE', Order.CONDITIONAL) || 'None';
const code = value_then + ' if ' + value_if + ' else ' + value_else;
return [code, Order.CONDITIONAL];
};

View File

@@ -16,7 +16,7 @@ import {NameType} from '../../core/names.js';
import {pythonGenerator, Order} from '../python.js';
pythonGenerator.forBlock['controls_repeat_ext'] = function(block) {
pythonGenerator.forBlock['controls_repeat_ext'] = function(block, generator) {
// Repeat n times.
let repeats;
if (block.getField('TIMES')) {
@@ -24,17 +24,17 @@ pythonGenerator.forBlock['controls_repeat_ext'] = function(block) {
repeats = String(parseInt(block.getFieldValue('TIMES'), 10));
} else {
// External number.
repeats = pythonGenerator.valueToCode(block, 'TIMES', Order.NONE) || '0';
repeats = generator.valueToCode(block, 'TIMES', Order.NONE) || '0';
}
if (stringUtils.isNumber(repeats)) {
repeats = parseInt(repeats, 10);
} else {
repeats = 'int(' + repeats + ')';
}
let branch = pythonGenerator.statementToCode(block, 'DO');
branch = pythonGenerator.addLoopTrap(branch, block) || pythonGenerator.PASS;
let branch = generator.statementToCode(block, 'DO');
branch = generator.addLoopTrap(branch, block) || generator.PASS;
const loopVar =
pythonGenerator.nameDB_.getDistinctName('count', NameType.VARIABLE);
generator.nameDB_.getDistinctName('count', NameType.VARIABLE);
const code = 'for ' + loopVar + ' in range(' + repeats + '):\n' + branch;
return code;
};
@@ -42,53 +42,53 @@ pythonGenerator.forBlock['controls_repeat_ext'] = function(block) {
pythonGenerator.forBlock['controls_repeat'] =
pythonGenerator.forBlock['controls_repeat_ext'];
pythonGenerator.forBlock['controls_whileUntil'] = function(block) {
pythonGenerator.forBlock['controls_whileUntil'] = function(block, generator) {
// Do while/until loop.
const until = block.getFieldValue('MODE') === 'UNTIL';
let argument0 = pythonGenerator.valueToCode(
let argument0 = generator.valueToCode(
block, 'BOOL',
until ? Order.LOGICAL_NOT : Order.NONE) ||
'False';
let branch = pythonGenerator.statementToCode(block, 'DO');
branch = pythonGenerator.addLoopTrap(branch, block) || pythonGenerator.PASS;
let branch = generator.statementToCode(block, 'DO');
branch = generator.addLoopTrap(branch, block) || generator.PASS;
if (until) {
argument0 = 'not ' + argument0;
}
return 'while ' + argument0 + ':\n' + branch;
};
pythonGenerator.forBlock['controls_for'] = function(block) {
pythonGenerator.forBlock['controls_for'] = function(block, generator) {
// For loop.
const variable0 =
pythonGenerator.nameDB_.getName(
generator.nameDB_.getName(
block.getFieldValue('VAR'), NameType.VARIABLE);
let argument0 = pythonGenerator.valueToCode(block, 'FROM', Order.NONE) || '0';
let argument1 = pythonGenerator.valueToCode(block, 'TO', Order.NONE) || '0';
let increment = pythonGenerator.valueToCode(block, 'BY', Order.NONE) || '1';
let branch = pythonGenerator.statementToCode(block, 'DO');
branch = pythonGenerator.addLoopTrap(branch, block) || pythonGenerator.PASS;
let argument0 = generator.valueToCode(block, 'FROM', Order.NONE) || '0';
let argument1 = generator.valueToCode(block, 'TO', Order.NONE) || '0';
let increment = generator.valueToCode(block, 'BY', Order.NONE) || '1';
let branch = generator.statementToCode(block, 'DO');
branch = generator.addLoopTrap(branch, block) || generator.PASS;
let code = '';
let range;
// Helper functions.
const defineUpRange = function() {
return pythonGenerator.provideFunction_('upRange', `
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(start, stop, step):
return generator.provideFunction_('upRange', `
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(start, stop, step):
while start <= stop:
yield start
start += abs(step)
`);
};
const defineDownRange = function() {
return pythonGenerator.provideFunction_('downRange', `
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(start, stop, step):
return generator.provideFunction_('downRange', `
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(start, stop, step):
while start >= stop:
yield start
start -= abs(step)
`);
};
// Arguments are legal pythonGenerator code (numbers or strings returned by scrub()).
// Arguments are legal generator code (numbers or strings returned by scrub()).
const generateUpDownRange = function(start, end, inc) {
return '(' + start + ' <= ' + end + ') and ' + defineUpRange() + '(' +
start + ', ' + end + ', ' + inc + ') or ' + defineDownRange() + '(' +
@@ -139,7 +139,7 @@ def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(start, stop, step):
arg = Number(arg);
} else if (!arg.match(/^\w+$/)) {
// Not a variable, it's complicated.
const varName = pythonGenerator.nameDB_.getDistinctName(
const varName = generator.nameDB_.getDistinctName(
variable0 + suffix, NameType.VARIABLE);
code += varName + ' = ' + arg + '\n';
arg = varName;
@@ -166,38 +166,38 @@ def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(start, stop, step):
return code;
};
pythonGenerator.forBlock['controls_forEach'] = function(block) {
pythonGenerator.forBlock['controls_forEach'] = function(block, generator) {
// For each loop.
const variable0 =
pythonGenerator.nameDB_.getName(
generator.nameDB_.getName(
block.getFieldValue('VAR'), NameType.VARIABLE);
const argument0 =
pythonGenerator.valueToCode(block, 'LIST', Order.RELATIONAL) || '[]';
let branch = pythonGenerator.statementToCode(block, 'DO');
branch = pythonGenerator.addLoopTrap(branch, block) || pythonGenerator.PASS;
generator.valueToCode(block, 'LIST', Order.RELATIONAL) || '[]';
let branch = generator.statementToCode(block, 'DO');
branch = generator.addLoopTrap(branch, block) || generator.PASS;
const code = 'for ' + variable0 + ' in ' + argument0 + ':\n' + branch;
return code;
};
pythonGenerator.forBlock['controls_flow_statements'] = function(block) {
pythonGenerator.forBlock['controls_flow_statements'] = function(block, generator) {
// Flow statements: continue, break.
let xfix = '';
if (pythonGenerator.STATEMENT_PREFIX) {
if (generator.STATEMENT_PREFIX) {
// Automatic prefix insertion is switched off for this block. Add manually.
xfix += pythonGenerator.injectId(pythonGenerator.STATEMENT_PREFIX, block);
xfix += generator.injectId(generator.STATEMENT_PREFIX, block);
}
if (pythonGenerator.STATEMENT_SUFFIX) {
if (generator.STATEMENT_SUFFIX) {
// Inject any statement suffix here since the regular one at the end
// will not get executed if the break/continue is triggered.
xfix += pythonGenerator.injectId(pythonGenerator.STATEMENT_SUFFIX, block);
xfix += generator.injectId(generator.STATEMENT_SUFFIX, block);
}
if (pythonGenerator.STATEMENT_PREFIX) {
if (generator.STATEMENT_PREFIX) {
const loop = block.getSurroundLoop();
if (loop && !loop.suppressPrefixSuffix) {
// Inject loop's statement prefix here since the regular one at the end
// of the loop will not get executed if 'continue' is triggered.
// In the case of 'break', a prefix is needed due to the loop's suffix.
xfix += pythonGenerator.injectId(pythonGenerator.STATEMENT_PREFIX, loop);
xfix += generator.injectId(generator.STATEMENT_PREFIX, loop);
}
}
switch (block.getFieldValue('FLOW')) {

View File

@@ -18,7 +18,7 @@ import {pythonGenerator, Order} from '../python.js';
// If any new block imports any library, add that library name here.
pythonGenerator.addReservedWords('math,random,Number');
pythonGenerator.forBlock['math_number'] = function(block) {
pythonGenerator.forBlock['math_number'] = function(block, generator) {
// Numeric value.
let code = Number(block.getFieldValue('NUM'));
let order;
@@ -34,7 +34,7 @@ pythonGenerator.forBlock['math_number'] = function(block) {
return [code, order];
};
pythonGenerator.forBlock['math_arithmetic'] = function(block) {
pythonGenerator.forBlock['math_arithmetic'] = function(block, generator) {
// Basic arithmetic operators, and power.
const OPERATORS = {
'ADD': [' + ', Order.ADDITIVE],
@@ -46,33 +46,33 @@ pythonGenerator.forBlock['math_arithmetic'] = function(block) {
const tuple = OPERATORS[block.getFieldValue('OP')];
const operator = tuple[0];
const order = tuple[1];
const argument0 = pythonGenerator.valueToCode(block, 'A', order) || '0';
const argument1 = pythonGenerator.valueToCode(block, 'B', order) || '0';
const argument0 = generator.valueToCode(block, 'A', order) || '0';
const argument1 = generator.valueToCode(block, 'B', order) || '0';
const code = argument0 + operator + argument1;
return [code, order];
// In case of 'DIVIDE', division between integers returns different results
// in pythonGenerator 2 and 3. However, is not an issue since Blockly does not
// in generator 2 and 3. However, is not an issue since Blockly does not
// guarantee identical results in all languages. To do otherwise would
// require every operator to be wrapped in a function call. This would kill
// legibility of the generated code.
};
pythonGenerator.forBlock['math_single'] = function(block) {
pythonGenerator.forBlock['math_single'] = function(block, generator) {
// Math operators with single operand.
const operator = block.getFieldValue('OP');
let code;
let arg;
if (operator === 'NEG') {
// Negation is a special case given its different operator precedence.
code = pythonGenerator.valueToCode(block, 'NUM', Order.UNARY_SIGN) || '0';
code = generator.valueToCode(block, 'NUM', Order.UNARY_SIGN) || '0';
return ['-' + code, Order.UNARY_SIGN];
}
pythonGenerator.definitions_['import_math'] = 'import math';
generator.definitions_['import_math'] = 'import math';
if (operator === 'SIN' || operator === 'COS' || operator === 'TAN') {
arg =
pythonGenerator.valueToCode(block, 'NUM', Order.MULTIPLICATIVE) || '0';
generator.valueToCode(block, 'NUM', Order.MULTIPLICATIVE) || '0';
} else {
arg = pythonGenerator.valueToCode(block, 'NUM', Order.NONE) || '0';
arg = generator.valueToCode(block, 'NUM', Order.NONE) || '0';
}
// First, handle cases which generate values that don't need parentheses
// wrapping the code.
@@ -135,7 +135,7 @@ pythonGenerator.forBlock['math_single'] = function(block) {
return [code, Order.MULTIPLICATIVE];
};
pythonGenerator.forBlock['math_constant'] = function(block) {
pythonGenerator.forBlock['math_constant'] = function(block, generator) {
// Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY.
const CONSTANTS = {
'PI': ['math.pi', Order.MEMBER],
@@ -147,12 +147,12 @@ pythonGenerator.forBlock['math_constant'] = function(block) {
};
const constant = block.getFieldValue('CONSTANT');
if (constant !== 'INFINITY') {
pythonGenerator.definitions_['import_math'] = 'import math';
generator.definitions_['import_math'] = 'import math';
}
return CONSTANTS[constant];
};
pythonGenerator.forBlock['math_number_property'] = function(block) {
pythonGenerator.forBlock['math_number_property'] = function(block, generator) {
// Check if a number is even, odd, prime, whole, positive, or negative
// or if it is divisible by certain number. Returns true or false.
const PROPERTIES = {
@@ -168,16 +168,16 @@ pythonGenerator.forBlock['math_number_property'] = function(block) {
}
const dropdownProperty = block.getFieldValue('PROPERTY');
const [suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty];
const numberToCheck = pythonGenerator.valueToCode(block, 'NUMBER_TO_CHECK',
const numberToCheck = generator.valueToCode(block, 'NUMBER_TO_CHECK',
inputOrder) || '0';
let code;
if (dropdownProperty === 'PRIME') {
// Prime is a special case as it is not a one-liner test.
pythonGenerator.definitions_['import_math'] = 'import math';
pythonGenerator.definitions_['from_numbers_import_Number'] =
generator.definitions_['import_math'] = 'import math';
generator.definitions_['from_numbers_import_Number'] =
'from numbers import Number';
const functionName = pythonGenerator.provideFunction_('math_isPrime', `
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(n):
const functionName = generator.provideFunction_('math_isPrime', `
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(n):
# https://en.wikipedia.org/wiki/Primality_test#Naive_methods
# If n is not a number but a string, try parsing it.
if not isinstance(n, Number):
@@ -198,9 +198,9 @@ def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(n):
`);
code = functionName + '(' + numberToCheck + ')';
} else if (dropdownProperty === 'DIVISIBLE_BY') {
const divisor = pythonGenerator.valueToCode(block, 'DIVISOR',
const divisor = generator.valueToCode(block, 'DIVISOR',
Order.MULTIPLICATIVE) || '0';
// If 'divisor' is some code that evals to 0, pythonGenerator will raise an error.
// If 'divisor' is some code that evals to 0, generator will raise an error.
if (divisor === '0') {
return ['False', Order.ATOMIC];
}
@@ -211,14 +211,14 @@ def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(n):
return [code, outputOrder];
};
pythonGenerator.forBlock['math_change'] = function(block) {
pythonGenerator.forBlock['math_change'] = function(block, generator) {
// Add to a variable in place.
pythonGenerator.definitions_['from_numbers_import_Number'] =
generator.definitions_['from_numbers_import_Number'] =
'from numbers import Number';
const argument0 =
pythonGenerator.valueToCode(block, 'DELTA', Order.ADDITIVE) || '0';
generator.valueToCode(block, 'DELTA', Order.ADDITIVE) || '0';
const varName =
pythonGenerator.nameDB_.getName(
generator.nameDB_.getName(
block.getFieldValue('VAR'), NameType.VARIABLE);
return varName + ' = (' + varName + ' if isinstance(' + varName +
', Number) else 0) + ' + argument0 + '\n';
@@ -231,10 +231,10 @@ pythonGenerator.forBlock['math_round'] =
pythonGenerator.forBlock['math_trig'] =
pythonGenerator.forBlock['math_single'];
pythonGenerator.forBlock['math_on_list'] = function(block) {
pythonGenerator.forBlock['math_on_list'] = function(block, generator) {
// Math functions for lists.
const func = block.getFieldValue('OP');
const list = pythonGenerator.valueToCode(block, 'LIST', Order.NONE) || '[]';
const list = generator.valueToCode(block, 'LIST', Order.NONE) || '[]';
let code;
switch (func) {
case 'SUM':
@@ -247,12 +247,12 @@ pythonGenerator.forBlock['math_on_list'] = function(block) {
code = 'max(' + list + ')';
break;
case 'AVERAGE': {
pythonGenerator.definitions_['from_numbers_import_Number'] =
generator.definitions_['from_numbers_import_Number'] =
'from numbers import Number';
// This operation excludes null and values that aren't int or float:
// math_mean([null, null, "aString", 1, 9]) -> 5.0
const functionName = pythonGenerator.provideFunction_('math_mean', `
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(myList):
const functionName = generator.provideFunction_('math_mean', `
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(myList):
localList = [e for e in myList if isinstance(e, Number)]
if not localList: return
return float(sum(localList)) / len(localList)
@@ -261,12 +261,12 @@ def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(myList):
break;
}
case 'MEDIAN': {
pythonGenerator.definitions_['from_numbers_import_Number'] =
generator.definitions_['from_numbers_import_Number'] =
'from numbers import Number';
// This operation excludes null values:
// math_median([null, null, 1, 3]) -> 2.0
const functionName = pythonGenerator.provideFunction_( 'math_median', `
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(myList):
const functionName = generator.provideFunction_( 'math_median', `
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(myList):
localList = sorted([e for e in myList if isinstance(e, Number)])
if not localList: return
if len(localList) % 2 == 0:
@@ -281,8 +281,8 @@ def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(myList):
// As a list of numbers can contain more than one mode,
// the returned result is provided as an array.
// Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1]
const functionName = pythonGenerator.provideFunction_('math_modes', `
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(some_list):
const functionName = generator.provideFunction_('math_modes', `
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(some_list):
modes = []
# Using a lists of [item, count] to keep count rather than dict
# to avoid "unhashable" errors when the counted item is itself a list or dict.
@@ -306,10 +306,10 @@ def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(some_list):
break;
}
case 'STD_DEV': {
pythonGenerator.definitions_['import_math'] = 'import math';
generator.definitions_['import_math'] = 'import math';
const functionName =
pythonGenerator.provideFunction_('math_standard_deviation', `
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(numbers):
generator.provideFunction_('math_standard_deviation', `
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(numbers):
n = len(numbers)
if n == 0: return
mean = float(sum(numbers)) / n
@@ -320,7 +320,7 @@ def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(numbers):
break;
}
case 'RANDOM':
pythonGenerator.definitions_['import_random'] = 'import random';
generator.definitions_['import_random'] = 'import random';
code = 'random.choice(' + list + ')';
break;
default:
@@ -329,54 +329,54 @@ def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(numbers):
return [code, Order.FUNCTION_CALL];
};
pythonGenerator.forBlock['math_modulo'] = function(block) {
pythonGenerator.forBlock['math_modulo'] = function(block, generator) {
// Remainder computation.
const argument0 =
pythonGenerator.valueToCode(block, 'DIVIDEND', Order.MULTIPLICATIVE) ||
generator.valueToCode(block, 'DIVIDEND', Order.MULTIPLICATIVE) ||
'0';
const argument1 =
pythonGenerator.valueToCode(block, 'DIVISOR', Order.MULTIPLICATIVE) ||
generator.valueToCode(block, 'DIVISOR', Order.MULTIPLICATIVE) ||
'0';
const code = argument0 + ' % ' + argument1;
return [code, Order.MULTIPLICATIVE];
};
pythonGenerator.forBlock['math_constrain'] = function(block) {
pythonGenerator.forBlock['math_constrain'] = function(block, generator) {
// Constrain a number between two limits.
const argument0 =
pythonGenerator.valueToCode(block, 'VALUE', Order.NONE) || '0';
generator.valueToCode(block, 'VALUE', Order.NONE) || '0';
const argument1 =
pythonGenerator.valueToCode(block, 'LOW', Order.NONE) || '0';
generator.valueToCode(block, 'LOW', Order.NONE) || '0';
const argument2 =
pythonGenerator.valueToCode(block, 'HIGH', Order.NONE) ||
generator.valueToCode(block, 'HIGH', Order.NONE) ||
'float(\'inf\')';
const code =
'min(max(' + argument0 + ', ' + argument1 + '), ' + argument2 + ')';
return [code, Order.FUNCTION_CALL];
};
pythonGenerator.forBlock['math_random_int'] = function(block) {
pythonGenerator.forBlock['math_random_int'] = function(block, generator) {
// Random integer between [X] and [Y].
pythonGenerator.definitions_['import_random'] = 'import random';
generator.definitions_['import_random'] = 'import random';
const argument0 =
pythonGenerator.valueToCode(block, 'FROM', Order.NONE) || '0';
generator.valueToCode(block, 'FROM', Order.NONE) || '0';
const argument1 =
pythonGenerator.valueToCode(block, 'TO', Order.NONE) || '0';
generator.valueToCode(block, 'TO', Order.NONE) || '0';
const code = 'random.randint(' + argument0 + ', ' + argument1 + ')';
return [code, Order.FUNCTION_CALL];
};
pythonGenerator.forBlock['math_random_float'] = function(block) {
pythonGenerator.forBlock['math_random_float'] = function(block, generator) {
// Random fraction between 0 and 1.
pythonGenerator.definitions_['import_random'] = 'import random';
generator.definitions_['import_random'] = 'import random';
return ['random.random()', Order.FUNCTION_CALL];
};
pythonGenerator.forBlock['math_atan2'] = function(block) {
pythonGenerator.forBlock['math_atan2'] = function(block, generator) {
// Arctangent of point (X, Y) in degrees from -180 to 180.
pythonGenerator.definitions_['import_math'] = 'import math';
const argument0 = pythonGenerator.valueToCode(block, 'X', Order.NONE) || '0';
const argument1 = pythonGenerator.valueToCode(block, 'Y', Order.NONE) || '0';
generator.definitions_['import_math'] = 'import math';
const argument0 = generator.valueToCode(block, 'X', Order.NONE) || '0';
const argument1 = generator.valueToCode(block, 'Y', Order.NONE) || '0';
return [
'math.atan2(' + argument1 + ', ' + argument0 + ') / math.pi * 180',
Order.MULTIPLICATIVE

View File

@@ -16,7 +16,7 @@ import {NameType} from '../../core/names.js';
import {pythonGenerator, Order} from '../python.js';
pythonGenerator.forBlock['procedures_defreturn'] = function(block) {
pythonGenerator.forBlock['procedures_defreturn'] = function(block, generator) {
// Define a procedure with a return value.
// First, add a 'global' statement for every variable that is not shadowed by
// a local parameter.
@@ -26,62 +26,62 @@ pythonGenerator.forBlock['procedures_defreturn'] = function(block) {
for (let i = 0, variable; (variable = usedVariables[i]); i++) {
const varName = variable.name;
if (block.getVars().indexOf(varName) === -1) {
globals.push(pythonGenerator.nameDB_.getName(varName, NameType.VARIABLE));
globals.push(generator.nameDB_.getName(varName, NameType.VARIABLE));
}
}
// Add developer variables.
const devVarList = Variables.allDeveloperVariables(workspace);
for (let i = 0; i < devVarList.length; i++) {
globals.push(
pythonGenerator.nameDB_.getName(
generator.nameDB_.getName(
devVarList[i], NameType.DEVELOPER_VARIABLE));
}
const globalString = globals.length ?
pythonGenerator.INDENT + 'global ' + globals.join(', ') + '\n' :
generator.INDENT + 'global ' + globals.join(', ') + '\n' :
'';
const funcName =
pythonGenerator.nameDB_.getName(
generator.nameDB_.getName(
block.getFieldValue('NAME'), NameType.PROCEDURE);
let xfix1 = '';
if (pythonGenerator.STATEMENT_PREFIX) {
xfix1 += pythonGenerator.injectId(pythonGenerator.STATEMENT_PREFIX, block);
if (generator.STATEMENT_PREFIX) {
xfix1 += generator.injectId(generator.STATEMENT_PREFIX, block);
}
if (pythonGenerator.STATEMENT_SUFFIX) {
xfix1 += pythonGenerator.injectId(pythonGenerator.STATEMENT_SUFFIX, block);
if (generator.STATEMENT_SUFFIX) {
xfix1 += generator.injectId(generator.STATEMENT_SUFFIX, block);
}
if (xfix1) {
xfix1 = pythonGenerator.prefixLines(xfix1, pythonGenerator.INDENT);
xfix1 = generator.prefixLines(xfix1, generator.INDENT);
}
let loopTrap = '';
if (pythonGenerator.INFINITE_LOOP_TRAP) {
loopTrap = pythonGenerator.prefixLines(
pythonGenerator.injectId(pythonGenerator.INFINITE_LOOP_TRAP, block),
pythonGenerator.INDENT);
if (generator.INFINITE_LOOP_TRAP) {
loopTrap = generator.prefixLines(
generator.injectId(generator.INFINITE_LOOP_TRAP, block),
generator.INDENT);
}
let branch = pythonGenerator.statementToCode(block, 'STACK');
let branch = generator.statementToCode(block, 'STACK');
let returnValue =
pythonGenerator.valueToCode(block, 'RETURN', Order.NONE) || '';
generator.valueToCode(block, 'RETURN', Order.NONE) || '';
let xfix2 = '';
if (branch && returnValue) {
// After executing the function body, revisit this block for the return.
xfix2 = xfix1;
}
if (returnValue) {
returnValue = pythonGenerator.INDENT + 'return ' + returnValue + '\n';
returnValue = generator.INDENT + 'return ' + returnValue + '\n';
} else if (!branch) {
branch = pythonGenerator.PASS;
branch = generator.PASS;
}
const args = [];
const variables = block.getVars();
for (let i = 0; i < variables.length; i++) {
args[i] = pythonGenerator.nameDB_.getName(variables[i], NameType.VARIABLE);
args[i] = generator.nameDB_.getName(variables[i], NameType.VARIABLE);
}
let code = 'def ' + funcName + '(' + args.join(', ') + '):\n' + globalString +
xfix1 + loopTrap + branch + xfix2 + returnValue;
code = pythonGenerator.scrub_(block, code);
code = generator.scrub_(block, code);
// Add % so as not to collide with helper functions in definitions list.
pythonGenerator.definitions_['%' + funcName] = code;
generator.definitions_['%' + funcName] = code;
return null;
};
@@ -90,47 +90,47 @@ pythonGenerator.forBlock['procedures_defreturn'] = function(block) {
pythonGenerator.forBlock['procedures_defnoreturn'] =
pythonGenerator.forBlock['procedures_defreturn'];
pythonGenerator.forBlock['procedures_callreturn'] = function(block) {
pythonGenerator.forBlock['procedures_callreturn'] = function(block, generator) {
// Call a procedure with a return value.
const funcName =
pythonGenerator.nameDB_.getName(
generator.nameDB_.getName(
block.getFieldValue('NAME'), NameType.PROCEDURE);
const args = [];
const variables = block.getVars();
for (let i = 0; i < variables.length; i++) {
args[i] =
pythonGenerator.valueToCode(block, 'ARG' + i, Order.NONE) || 'None';
generator.valueToCode(block, 'ARG' + i, Order.NONE) || 'None';
}
const code = funcName + '(' + args.join(', ') + ')';
return [code, Order.FUNCTION_CALL];
};
pythonGenerator.forBlock['procedures_callnoreturn'] = function(block) {
pythonGenerator.forBlock['procedures_callnoreturn'] = function(block, generator) {
// Call a procedure with no return value.
// Generated code is for a function call as a statement is the same as a
// function call as a value, with the addition of line ending.
const tuple = pythonGenerator.forBlock['procedures_callreturn'](block);
const tuple = generator.forBlock['procedures_callreturn'](block, generator);
return tuple[0] + '\n';
};
pythonGenerator.forBlock['procedures_ifreturn'] = function(block) {
pythonGenerator.forBlock['procedures_ifreturn'] = function(block, generator) {
// Conditionally return value from a procedure.
const condition =
pythonGenerator.valueToCode(block, 'CONDITION', Order.NONE) || 'False';
generator.valueToCode(block, 'CONDITION', Order.NONE) || 'False';
let code = 'if ' + condition + ':\n';
if (pythonGenerator.STATEMENT_SUFFIX) {
if (generator.STATEMENT_SUFFIX) {
// Inject any statement suffix here since the regular one at the end
// will not get executed if the return is triggered.
code += pythonGenerator.prefixLines(
pythonGenerator.injectId(
pythonGenerator.STATEMENT_SUFFIX, block), pythonGenerator.INDENT);
code += generator.prefixLines(
generator.injectId(
generator.STATEMENT_SUFFIX, block), generator.INDENT);
}
if (block.hasReturnValue_) {
const value =
pythonGenerator.valueToCode(block, 'VALUE', Order.NONE) || 'None';
code += pythonGenerator.INDENT + 'return ' + value + '\n';
generator.valueToCode(block, 'VALUE', Order.NONE) || 'None';
code += generator.INDENT + 'return ' + value + '\n';
} else {
code += pythonGenerator.INDENT + 'return\n';
code += generator.INDENT + 'return\n';
}
return code;
};

View File

@@ -16,15 +16,15 @@ import {NameType} from '../../core/names.js';
import {pythonGenerator, Order} from '../python.js';
pythonGenerator.forBlock['text'] = function(block) {
pythonGenerator.forBlock['text'] = function(block, generator) {
// Text value.
const code = pythonGenerator.quote_(block.getFieldValue('TEXT'));
const code = generator.quote_(block.getFieldValue('TEXT'));
return [code, Order.ATOMIC];
};
pythonGenerator.forBlock['text_multiline'] = function(block) {
pythonGenerator.forBlock['text_multiline'] = function(block, generator) {
// Text value.
const code = pythonGenerator.multiline_quote_(block.getFieldValue('TEXT'));
const code = generator.multiline_quote_(block.getFieldValue('TEXT'));
const order =
code.indexOf('+') !== -1 ? Order.ADDITIVE : Order.ATOMIC;
return [code, order];
@@ -50,7 +50,7 @@ const forceString = function(value) {
return ['str(' + value + ')', Order.FUNCTION_CALL];
};
pythonGenerator.forBlock['text_join'] = function(block) {
pythonGenerator.forBlock['text_join'] = function(block, generator) {
// Create a string made up of any number of elements of any type.
// Should we allow joining by '-' or ',' or any other characters?
switch (block.itemCount_) {
@@ -58,15 +58,15 @@ pythonGenerator.forBlock['text_join'] = function(block) {
return ["''", Order.ATOMIC];
case 1: {
const element =
pythonGenerator.valueToCode(block, 'ADD0', Order.NONE) || "''";
generator.valueToCode(block, 'ADD0', Order.NONE) || "''";
const codeAndOrder = forceString(element);
return codeAndOrder;
}
case 2: {
const element0 =
pythonGenerator.valueToCode(block, 'ADD0', Order.NONE) || "''";
generator.valueToCode(block, 'ADD0', Order.NONE) || "''";
const element1 =
pythonGenerator.valueToCode(block, 'ADD1', Order.NONE) || "''";
generator.valueToCode(block, 'ADD1', Order.NONE) || "''";
const code = forceString(element0)[0] + ' + ' + forceString(element1)[0];
return [code, Order.ADDITIVE];
}
@@ -74,10 +74,10 @@ pythonGenerator.forBlock['text_join'] = function(block) {
const elements = [];
for (let i = 0; i < block.itemCount_; i++) {
elements[i] =
pythonGenerator.valueToCode(block, 'ADD' + i, Order.NONE) || "''";
generator.valueToCode(block, 'ADD' + i, Order.NONE) || "''";
}
const tempVar =
pythonGenerator.nameDB_.getDistinctName('x', NameType.VARIABLE);
generator.nameDB_.getDistinctName('x', NameType.VARIABLE);
const code = '\'\'.join([str(' + tempVar + ') for ' + tempVar + ' in [' +
elements.join(', ') + ']])';
return [code, Order.FUNCTION_CALL];
@@ -85,36 +85,36 @@ pythonGenerator.forBlock['text_join'] = function(block) {
}
};
pythonGenerator.forBlock['text_append'] = function(block) {
pythonGenerator.forBlock['text_append'] = function(block, generator) {
// Append to a variable in place.
const varName =
pythonGenerator.nameDB_.getName(
generator.nameDB_.getName(
block.getFieldValue('VAR'), NameType.VARIABLE);
const value = pythonGenerator.valueToCode(block, 'TEXT', Order.NONE) || "''";
const value = generator.valueToCode(block, 'TEXT', Order.NONE) || "''";
return varName + ' = str(' + varName + ') + ' + forceString(value)[0] + '\n';
};
pythonGenerator.forBlock['text_length'] = function(block) {
pythonGenerator.forBlock['text_length'] = function(block, generator) {
// Is the string null or array empty?
const text = pythonGenerator.valueToCode(block, 'VALUE', Order.NONE) || "''";
const text = generator.valueToCode(block, 'VALUE', Order.NONE) || "''";
return ['len(' + text + ')', Order.FUNCTION_CALL];
};
pythonGenerator.forBlock['text_isEmpty'] = function(block) {
pythonGenerator.forBlock['text_isEmpty'] = function(block, generator) {
// Is the string null or array empty?
const text = pythonGenerator.valueToCode(block, 'VALUE', Order.NONE) || "''";
const text = generator.valueToCode(block, 'VALUE', Order.NONE) || "''";
const code = 'not len(' + text + ')';
return [code, Order.LOGICAL_NOT];
};
pythonGenerator.forBlock['text_indexOf'] = function(block) {
pythonGenerator.forBlock['text_indexOf'] = function(block, generator) {
// Search the text for a substring.
// Should we allow for non-case sensitive???
const operator = block.getFieldValue('END') === 'FIRST' ? 'find' : 'rfind';
const substring =
pythonGenerator.valueToCode(block, 'FIND', Order.NONE) || "''";
generator.valueToCode(block, 'FIND', Order.NONE) || "''";
const text =
pythonGenerator.valueToCode(block, 'VALUE', Order.MEMBER) || "''";
generator.valueToCode(block, 'VALUE', Order.MEMBER) || "''";
const code = text + '.' + operator + '(' + substring + ')';
if (block.workspace.options.oneBasedIndex) {
return [code + ' + 1', Order.ADDITIVE];
@@ -122,13 +122,13 @@ pythonGenerator.forBlock['text_indexOf'] = function(block) {
return [code, Order.FUNCTION_CALL];
};
pythonGenerator.forBlock['text_charAt'] = function(block) {
pythonGenerator.forBlock['text_charAt'] = function(block, generator) {
// Get letter at index.
// Note: Until January 2013 this block did not have the WHERE input.
const where = block.getFieldValue('WHERE') || 'FROM_START';
const textOrder =
(where === 'RANDOM') ? Order.NONE : Order.MEMBER;
const text = pythonGenerator.valueToCode(block, 'VALUE', textOrder) || "''";
const text = generator.valueToCode(block, 'VALUE', textOrder) || "''";
switch (where) {
case 'FIRST': {
const code = text + '[0]';
@@ -139,20 +139,20 @@ pythonGenerator.forBlock['text_charAt'] = function(block) {
return [code, Order.MEMBER];
}
case 'FROM_START': {
const at = pythonGenerator.getAdjustedInt(block, 'AT');
const at = generator.getAdjustedInt(block, 'AT');
const code = text + '[' + at + ']';
return [code, Order.MEMBER];
}
case 'FROM_END': {
const at = pythonGenerator.getAdjustedInt(block, 'AT', 1, true);
const at = generator.getAdjustedInt(block, 'AT', 1, true);
const code = text + '[' + at + ']';
return [code, Order.MEMBER];
}
case 'RANDOM': {
pythonGenerator.definitions_['import_random'] = 'import random';
generator.definitions_['import_random'] = 'import random';
const functionName =
pythonGenerator.provideFunction_('text_random_letter', `
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(text):
generator.provideFunction_('text_random_letter', `
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(text):
x = int(random.random() * len(text))
return text[x]
`);
@@ -163,22 +163,22 @@ def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(text):
throw Error('Unhandled option (text_charAt).');
};
pythonGenerator.forBlock['text_getSubstring'] = function(block) {
pythonGenerator.forBlock['text_getSubstring'] = function(block, generator) {
// Get substring.
const where1 = block.getFieldValue('WHERE1');
const where2 = block.getFieldValue('WHERE2');
const text =
pythonGenerator.valueToCode(block, 'STRING', Order.MEMBER) || "''";
generator.valueToCode(block, 'STRING', Order.MEMBER) || "''";
let at1;
switch (where1) {
case 'FROM_START':
at1 = pythonGenerator.getAdjustedInt(block, 'AT1');
at1 = generator.getAdjustedInt(block, 'AT1');
if (at1 === 0) {
at1 = '';
}
break;
case 'FROM_END':
at1 = pythonGenerator.getAdjustedInt(block, 'AT1', 1, true);
at1 = generator.getAdjustedInt(block, 'AT1', 1, true);
break;
case 'FIRST':
at1 = '';
@@ -190,14 +190,14 @@ pythonGenerator.forBlock['text_getSubstring'] = function(block) {
let at2;
switch (where2) {
case 'FROM_START':
at2 = pythonGenerator.getAdjustedInt(block, 'AT2', 1);
at2 = generator.getAdjustedInt(block, 'AT2', 1);
break;
case 'FROM_END':
at2 = pythonGenerator.getAdjustedInt(block, 'AT2', 0, true);
at2 = generator.getAdjustedInt(block, 'AT2', 0, true);
// Ensure that if the result calculated is 0 that sub-sequence will
// include all elements as expected.
if (!stringUtils.isNumber(String(at2))) {
pythonGenerator.definitions_['import_sys'] = 'import sys';
generator.definitions_['import_sys'] = 'import sys';
at2 += ' or sys.maxsize';
} else if (at2 === 0) {
at2 = '';
@@ -213,7 +213,7 @@ pythonGenerator.forBlock['text_getSubstring'] = function(block) {
return [code, Order.MEMBER];
};
pythonGenerator.forBlock['text_changeCase'] = function(block) {
pythonGenerator.forBlock['text_changeCase'] = function(block, generator) {
// Change capitalization.
const OPERATORS = {
'UPPERCASE': '.upper()',
@@ -221,12 +221,12 @@ pythonGenerator.forBlock['text_changeCase'] = function(block) {
'TITLECASE': '.title()'
};
const operator = OPERATORS[block.getFieldValue('CASE')];
const text = pythonGenerator.valueToCode(block, 'TEXT', Order.MEMBER) || "''";
const text = generator.valueToCode(block, 'TEXT', Order.MEMBER) || "''";
const code = text + operator;
return [code, Order.FUNCTION_CALL];
};
pythonGenerator.forBlock['text_trim'] = function(block) {
pythonGenerator.forBlock['text_trim'] = function(block, generator) {
// Trim spaces.
const OPERATORS = {
'LEFT': '.lstrip()',
@@ -234,21 +234,21 @@ pythonGenerator.forBlock['text_trim'] = function(block) {
'BOTH': '.strip()'
};
const operator = OPERATORS[block.getFieldValue('MODE')];
const text = pythonGenerator.valueToCode(block, 'TEXT', Order.MEMBER) || "''";
const text = generator.valueToCode(block, 'TEXT', Order.MEMBER) || "''";
const code = text + operator;
return [code, Order.FUNCTION_CALL];
};
pythonGenerator.forBlock['text_print'] = function(block) {
pythonGenerator.forBlock['text_print'] = function(block, generator) {
// Print statement.
const msg = pythonGenerator.valueToCode(block, 'TEXT', Order.NONE) || "''";
const msg = generator.valueToCode(block, 'TEXT', Order.NONE) || "''";
return 'print(' + msg + ')\n';
};
pythonGenerator.forBlock['text_prompt_ext'] = function(block) {
pythonGenerator.forBlock['text_prompt_ext'] = function(block, generator) {
// Prompt function.
const functionName = pythonGenerator.provideFunction_('text_prompt', `
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(msg):
const functionName = generator.provideFunction_('text_prompt', `
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(msg):
try:
return raw_input(msg)
except NameError:
@@ -257,10 +257,10 @@ def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(msg):
let msg;
if (block.getField('TEXT')) {
// Internal message.
msg = pythonGenerator.quote_(block.getFieldValue('TEXT'));
msg = generator.quote_(block.getFieldValue('TEXT'));
} else {
// External message.
msg = pythonGenerator.valueToCode(block, 'TEXT', Order.NONE) || "''";
msg = generator.valueToCode(block, 'TEXT', Order.NONE) || "''";
}
let code = functionName + '(' + msg + ')';
const toNumber = block.getFieldValue('TYPE') === 'NUMBER';
@@ -273,23 +273,23 @@ def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(msg):
pythonGenerator.forBlock['text_prompt'] =
pythonGenerator.forBlock['text_prompt_ext'];
pythonGenerator.forBlock['text_count'] = function(block) {
const text = pythonGenerator.valueToCode(block, 'TEXT', Order.MEMBER) || "''";
const sub = pythonGenerator.valueToCode(block, 'SUB', Order.NONE) || "''";
pythonGenerator.forBlock['text_count'] = function(block, generator) {
const text = generator.valueToCode(block, 'TEXT', Order.MEMBER) || "''";
const sub = generator.valueToCode(block, 'SUB', Order.NONE) || "''";
const code = text + '.count(' + sub + ')';
return [code, Order.FUNCTION_CALL];
};
pythonGenerator.forBlock['text_replace'] = function(block) {
const text = pythonGenerator.valueToCode(block, 'TEXT', Order.MEMBER) || "''";
const from = pythonGenerator.valueToCode(block, 'FROM', Order.NONE) || "''";
const to = pythonGenerator.valueToCode(block, 'TO', Order.NONE) || "''";
pythonGenerator.forBlock['text_replace'] = function(block, generator) {
const text = generator.valueToCode(block, 'TEXT', Order.MEMBER) || "''";
const from = generator.valueToCode(block, 'FROM', Order.NONE) || "''";
const to = generator.valueToCode(block, 'TO', Order.NONE) || "''";
const code = text + '.replace(' + from + ', ' + to + ')';
return [code, Order.MEMBER];
};
pythonGenerator.forBlock['text_reverse'] = function(block) {
const text = pythonGenerator.valueToCode(block, 'TEXT', Order.MEMBER) || "''";
pythonGenerator.forBlock['text_reverse'] = function(block, generator) {
const text = generator.valueToCode(block, 'TEXT', Order.MEMBER) || "''";
const code = text + '[::-1]';
return [code, Order.MEMBER];
};

View File

@@ -15,20 +15,20 @@ import {NameType} from '../../core/names.js';
import {pythonGenerator, Order} from '../python.js';
pythonGenerator.forBlock['variables_get'] = function(block) {
pythonGenerator.forBlock['variables_get'] = function(block, generator) {
// Variable getter.
const code =
pythonGenerator.nameDB_.getName(
generator.nameDB_.getName(
block.getFieldValue('VAR'), NameType.VARIABLE);
return [code, Order.ATOMIC];
};
pythonGenerator.forBlock['variables_set'] = function(block) {
pythonGenerator.forBlock['variables_set'] = function(block, generator) {
// Variable setter.
const argument0 =
pythonGenerator.valueToCode(block, 'VALUE', Order.NONE) || '0';
generator.valueToCode(block, 'VALUE', Order.NONE) || '0';
const varName =
pythonGenerator.nameDB_.getName(
generator.nameDB_.getName(
block.getFieldValue('VAR'), NameType.VARIABLE);
return varName + ' = ' + argument0 + '\n';
};

View File

@@ -15,6 +15,6 @@ import {pythonGenerator} from '../python.js';
import './variables.js';
// pythonGenerator is dynamically typed.
// generator is dynamically typed.
pythonGenerator.forBlock['variables_get_dynamic'] = pythonGenerator.forBlock['variables_get'];
pythonGenerator.forBlock['variables_set_dynamic'] = pythonGenerator.forBlock['variables_set'];