mirror of
https://github.com/google/blockly.git
synced 2026-01-09 01:50:11 +01:00
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:
committed by
GitHub
parent
12b91ae49c
commit
a3458871db
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user