mirror of
https://github.com/google/blockly.git
synced 2026-01-05 08:00:09 +01:00
* chore(build): Add "all" modules for blocks & generators
These modules (Blockly.blocks.all and Blockly.<Generator>.all) will
be the entry points for the corresponding chunks.
They also make it easier to pull in all the modules in each package
(e.g. for playground and tests).
It is necessary to set the Closure Compiler dependency_mode to
SORT_ONLY as otherwise it tries to compile the "all" modules before
their dependencies, which fails.
The only impact on the _compressed.js files is the addition of a short
string to the very end of each file, e.g.:
var module$exports$Blockly$JavaScript$all={};
* chore(deps): Add devDependency on closure-calculate-chunks
* feat(build): First pass at chunked complation
Add a new buildCompiled gulp target (npm run build:compiled) that
uses closure-calculate-chunks to do chunked compliation of core/,
blocks/ and generators/ all in a single pass.
This work is incomplete: the resulting *_compressed.js files don't
(yet) have UMD wrappers.
* chore(build): Generate chunk wrappers
A first pass; this does not have support for a namespace object yet.
* refactor(build): Use chunked compilation by default
Remove old "compressed" gulp tasks in favour of new "compiled" task.
* chore(build): Remove cruft from buildCompiled
Remove unneeded `done` parameter and commented-out options that had
been cargo-culted from the old build pipeline.
* fix(build): Fix test failures caused by new build pipeline
- Exclude closure/goog/base.js from compiler input; use
externs/goog-externs.js instead.
- Have the build:debug and build:strict targets only build the first
chunk (blockly_compressed.js).
- Fix namespace entries for blocks and generators.
* fix(build): Fix build failures on node v12
closure-calculate-chunks requires node.js v14 or later.
When running on node.js v14 or later have getChunkOptions save
the output of closure-calculate-chunks to
scripts/gulpfiles/chunks.json. When running on older versions of
node.js have it use this checked-in, cached output instead of
attempting to run closure-calculate-chunks.
* chore(build): enable --rename_prefix_namespace
This will allow modules in blocks/ and generators/ to use
goog.require to obtain the exports object of goog.modules from
core/.
* fix(build): Always build all chunks
The previous commit enabled --rename_prefix_namespace option to
Closure Compiler, and this causes the buildCompressed target to
work fine when run without --debug or --strict, but adding either
of those flags (as for example when `npm test` runs
`npm run build:debug`) causes an issue:
- Because of many compiler errors in blocks/ and generators/,
a previous commit added a hack to only build the first chunk
when doing debug/strict builds.
- When asked to build only one chunk, Closure Compiler ignores the
--rename_prefix_namespace flag, because it 'correctly' infers
that there are no later chunks that will need to access global
variables from the first chunk.
- This causes a test failure, because `npm test` first runs
`npm run build`, which generates a valid blockly_compressed.js,
but this is then overrwritten by an invalid one when it next runs
`npm run build:debug`.
(The invalid one is missing all `$.` prefixes on 'global' variables,
including on Blockly, so the wrapper's last two lines -
"$.Blockly.internal_ = $;" and "return $.Blockly" - fail.)
The fix is to add appropriate @suppress annotations to blocks/*.js and
generators/**/*.js and then remove the first-chunk-only hack.
* refactor(build): Just build once
Since the previous commit caused `npm run build:debug` to do
everything that `... build:compressed` does - and to produce
byte-for-byte identical output - it doesn't make sense to run
both when testing. To that end:
- Replace the build:debug and build:strict package scripts that
did `gulp buildCompressed --...` with new scripts build-debug
and build-strict that do `gulp build --...` instead.
(The target names are changed so as to extend our existing naming
convention as follows: a target named "foo:bar" does some sub-part
of the job done by target "foo", but a target named "foo-bar" does
all the work of the target "foo" with some extra options.)
- build:debug:log and build:strict:log are similarly replaced with
build-debug-log and build-strict-log.
- Modify run_all_tests.js to just do `npm run build-debug` instead of
doing both `npm run build` and `npm run build:debug`.
- Also remove the 'build:blocks' script that should have been removed
when the buildBlocks gulp task was deleted previously.
* refactor(build): Compile with base_minimal.js instead of base.js
Introduce a (very!) cut-down version of closure/goog/base.js named
base_minimal.js that is used as input to the compiler as an
alternative to using externs/goog-externs.js (which will be deleted
once the buildAdvancedCompilationTest target has been updated).
This will allow use of goog.setTestOnly since it will now exist in
compiled mode, and allows the changes made in 5b112db to filter
base.js out of the files for the first chunk to be reverted.
(It also obliges a change to the compiled-mode check in blockly.js.)
* fix(build): Fix buildAdvanceCompilationTest
- In build_tasks.js:
- Replace the old compile() function with a new one factored out of
buildCompiled().
- Update buildAdvancedCompilationTest to use the new compile()
and other helpers created in the meantime.
- Remove no-longer-used maybeAddClosureLibrary().
- Remove externs/{block,generator,goog}-externs.js, which are no longer
used by any compile pipeline.
- Update core/blockly.js to fix issue with detection of compiled mode
when using ADVANCED_OPTIMISATIONS.
- Update only other use of globalThis, in core/utils/xml.js, to
consistently treat it as a dictionary object.
- Update instructions in tests/compile/index.html.
This commit is sort-of-a-prerequisite to #5602; test:compile:advanced
was previously working but the generated `main_compresed.js` would
throw errors upon loading.
391 lines
14 KiB
JavaScript
391 lines
14 KiB
JavaScript
/**
|
|
* @license
|
|
* Copyright 2012 Google LLC
|
|
* SPDX-License-Identifier: Apache-2.0
|
|
*/
|
|
|
|
/**
|
|
* @fileoverview Generating Python for math blocks.
|
|
* @suppress {missingRequire}
|
|
*/
|
|
'use strict';
|
|
|
|
goog.provide('Blockly.Python.math');
|
|
|
|
goog.require('Blockly.Python');
|
|
|
|
|
|
// If any new block imports any library, add that library name here.
|
|
Blockly.Python.addReservedWords('math,random,Number');
|
|
|
|
Blockly.Python['math_number'] = function(block) {
|
|
// Numeric value.
|
|
let code = Number(block.getFieldValue('NUM'));
|
|
let order;
|
|
if (code === Infinity) {
|
|
code = 'float("inf")';
|
|
order = Blockly.Python.ORDER_FUNCTION_CALL;
|
|
} else if (code === -Infinity) {
|
|
code = '-float("inf")';
|
|
order = Blockly.Python.ORDER_UNARY_SIGN;
|
|
} else {
|
|
order = code < 0 ? Blockly.Python.ORDER_UNARY_SIGN :
|
|
Blockly.Python.ORDER_ATOMIC;
|
|
}
|
|
return [code, order];
|
|
};
|
|
|
|
Blockly.Python['math_arithmetic'] = function(block) {
|
|
// Basic arithmetic operators, and power.
|
|
const OPERATORS = {
|
|
'ADD': [' + ', Blockly.Python.ORDER_ADDITIVE],
|
|
'MINUS': [' - ', Blockly.Python.ORDER_ADDITIVE],
|
|
'MULTIPLY': [' * ', Blockly.Python.ORDER_MULTIPLICATIVE],
|
|
'DIVIDE': [' / ', Blockly.Python.ORDER_MULTIPLICATIVE],
|
|
'POWER': [' ** ', Blockly.Python.ORDER_EXPONENTIATION]
|
|
};
|
|
const tuple = OPERATORS[block.getFieldValue('OP')];
|
|
const operator = tuple[0];
|
|
const order = tuple[1];
|
|
const argument0 = Blockly.Python.valueToCode(block, 'A', order) || '0';
|
|
const argument1 = Blockly.Python.valueToCode(block, 'B', order) || '0';
|
|
const code = argument0 + operator + argument1;
|
|
return [code, order];
|
|
// In case of 'DIVIDE', division between integers returns different results
|
|
// in Python 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.
|
|
};
|
|
|
|
Blockly.Python['math_single'] = function(block) {
|
|
// 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 = Blockly.Python.valueToCode(block, 'NUM',
|
|
Blockly.Python.ORDER_UNARY_SIGN) || '0';
|
|
return ['-' + code, Blockly.Python.ORDER_UNARY_SIGN];
|
|
}
|
|
Blockly.Python.definitions_['import_math'] = 'import math';
|
|
if (operator === 'SIN' || operator === 'COS' || operator === 'TAN') {
|
|
arg = Blockly.Python.valueToCode(block, 'NUM',
|
|
Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
|
|
} else {
|
|
arg = Blockly.Python.valueToCode(block, 'NUM',
|
|
Blockly.Python.ORDER_NONE) || '0';
|
|
}
|
|
// First, handle cases which generate values that don't need parentheses
|
|
// wrapping the code.
|
|
switch (operator) {
|
|
case 'ABS':
|
|
code = 'math.fabs(' + arg + ')';
|
|
break;
|
|
case 'ROOT':
|
|
code = 'math.sqrt(' + arg + ')';
|
|
break;
|
|
case 'LN':
|
|
code = 'math.log(' + arg + ')';
|
|
break;
|
|
case 'LOG10':
|
|
code = 'math.log10(' + arg + ')';
|
|
break;
|
|
case 'EXP':
|
|
code = 'math.exp(' + arg + ')';
|
|
break;
|
|
case 'POW10':
|
|
code = 'math.pow(10,' + arg + ')';
|
|
break;
|
|
case 'ROUND':
|
|
code = 'round(' + arg + ')';
|
|
break;
|
|
case 'ROUNDUP':
|
|
code = 'math.ceil(' + arg + ')';
|
|
break;
|
|
case 'ROUNDDOWN':
|
|
code = 'math.floor(' + arg + ')';
|
|
break;
|
|
case 'SIN':
|
|
code = 'math.sin(' + arg + ' / 180.0 * math.pi)';
|
|
break;
|
|
case 'COS':
|
|
code = 'math.cos(' + arg + ' / 180.0 * math.pi)';
|
|
break;
|
|
case 'TAN':
|
|
code = 'math.tan(' + arg + ' / 180.0 * math.pi)';
|
|
break;
|
|
}
|
|
if (code) {
|
|
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
|
|
}
|
|
// Second, handle cases which generate values that may need parentheses
|
|
// wrapping the code.
|
|
switch (operator) {
|
|
case 'ASIN':
|
|
code = 'math.asin(' + arg + ') / math.pi * 180';
|
|
break;
|
|
case 'ACOS':
|
|
code = 'math.acos(' + arg + ') / math.pi * 180';
|
|
break;
|
|
case 'ATAN':
|
|
code = 'math.atan(' + arg + ') / math.pi * 180';
|
|
break;
|
|
default:
|
|
throw Error('Unknown math operator: ' + operator);
|
|
}
|
|
return [code, Blockly.Python.ORDER_MULTIPLICATIVE];
|
|
};
|
|
|
|
Blockly.Python['math_constant'] = function(block) {
|
|
// Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY.
|
|
const CONSTANTS = {
|
|
'PI': ['math.pi', Blockly.Python.ORDER_MEMBER],
|
|
'E': ['math.e', Blockly.Python.ORDER_MEMBER],
|
|
'GOLDEN_RATIO': ['(1 + math.sqrt(5)) / 2',
|
|
Blockly.Python.ORDER_MULTIPLICATIVE],
|
|
'SQRT2': ['math.sqrt(2)', Blockly.Python.ORDER_MEMBER],
|
|
'SQRT1_2': ['math.sqrt(1.0 / 2)', Blockly.Python.ORDER_MEMBER],
|
|
'INFINITY': ['float(\'inf\')', Blockly.Python.ORDER_ATOMIC]
|
|
};
|
|
const constant = block.getFieldValue('CONSTANT');
|
|
if (constant !== 'INFINITY') {
|
|
Blockly.Python.definitions_['import_math'] = 'import math';
|
|
}
|
|
return CONSTANTS[constant];
|
|
};
|
|
|
|
Blockly.Python['math_number_property'] = function(block) {
|
|
// 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 number_to_check = Blockly.Python.valueToCode(block, 'NUMBER_TO_CHECK',
|
|
Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
|
|
const dropdown_property = block.getFieldValue('PROPERTY');
|
|
let code;
|
|
if (dropdown_property === 'PRIME') {
|
|
Blockly.Python.definitions_['import_math'] = 'import math';
|
|
Blockly.Python.definitions_['from_numbers_import_Number'] =
|
|
'from numbers import Number';
|
|
const functionName = Blockly.Python.provideFunction_(
|
|
'math_isPrime',
|
|
['def ' + Blockly.Python.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):',
|
|
' try:',
|
|
' n = float(n)',
|
|
' except:',
|
|
' return False',
|
|
' if n == 2 or n == 3:',
|
|
' return True',
|
|
' # False if n is negative, is 1, or not whole,' +
|
|
' or if n is divisible by 2 or 3.',
|
|
' if n <= 1 or n % 1 != 0 or n % 2 == 0 or n % 3 == 0:',
|
|
' return False',
|
|
' # Check all the numbers of form 6k +/- 1, up to sqrt(n).',
|
|
' for x in range(6, int(math.sqrt(n)) + 2, 6):',
|
|
' if n % (x - 1) == 0 or n % (x + 1) == 0:',
|
|
' return False',
|
|
' return True']);
|
|
code = functionName + '(' + number_to_check + ')';
|
|
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
|
|
}
|
|
switch (dropdown_property) {
|
|
case 'EVEN':
|
|
code = number_to_check + ' % 2 == 0';
|
|
break;
|
|
case 'ODD':
|
|
code = number_to_check + ' % 2 == 1';
|
|
break;
|
|
case 'WHOLE':
|
|
code = number_to_check + ' % 1 == 0';
|
|
break;
|
|
case 'POSITIVE':
|
|
code = number_to_check + ' > 0';
|
|
break;
|
|
case 'NEGATIVE':
|
|
code = number_to_check + ' < 0';
|
|
break;
|
|
case 'DIVISIBLE_BY': {
|
|
const divisor = Blockly.Python.valueToCode(block, 'DIVISOR',
|
|
Blockly.Python.ORDER_MULTIPLICATIVE);
|
|
// If 'divisor' is some code that evals to 0, Python will raise an error.
|
|
if (!divisor || divisor === '0') {
|
|
return ['False', Blockly.Python.ORDER_ATOMIC];
|
|
}
|
|
code = number_to_check + ' % ' + divisor + ' == 0';
|
|
break;
|
|
}
|
|
}
|
|
return [code, Blockly.Python.ORDER_RELATIONAL];
|
|
};
|
|
|
|
Blockly.Python['math_change'] = function(block) {
|
|
// Add to a variable in place.
|
|
Blockly.Python.definitions_['from_numbers_import_Number'] =
|
|
'from numbers import Number';
|
|
const argument0 = Blockly.Python.valueToCode(block, 'DELTA',
|
|
Blockly.Python.ORDER_ADDITIVE) || '0';
|
|
const varName = Blockly.Python.nameDB_.getName(block.getFieldValue('VAR'),
|
|
Blockly.VARIABLE_CATEGORY_NAME);
|
|
return varName + ' = (' + varName + ' if isinstance(' + varName +
|
|
', Number) else 0) + ' + argument0 + '\n';
|
|
};
|
|
|
|
// Rounding functions have a single operand.
|
|
Blockly.Python['math_round'] = Blockly.Python['math_single'];
|
|
// Trigonometry functions have a single operand.
|
|
Blockly.Python['math_trig'] = Blockly.Python['math_single'];
|
|
|
|
Blockly.Python['math_on_list'] = function(block) {
|
|
// Math functions for lists.
|
|
const func = block.getFieldValue('OP');
|
|
const list = Blockly.Python.valueToCode(block, 'LIST',
|
|
Blockly.Python.ORDER_NONE) || '[]';
|
|
let code;
|
|
switch (func) {
|
|
case 'SUM':
|
|
code = 'sum(' + list + ')';
|
|
break;
|
|
case 'MIN':
|
|
code = 'min(' + list + ')';
|
|
break;
|
|
case 'MAX':
|
|
code = 'max(' + list + ')';
|
|
break;
|
|
case 'AVERAGE': {
|
|
Blockly.Python.definitions_['from_numbers_import_Number'] =
|
|
'from numbers import Number';
|
|
const functionName = Blockly.Python.provideFunction_(
|
|
'math_mean',
|
|
// This operation excludes null and values that aren't int or float:
|
|
// math_mean([null, null, "aString", 1, 9]) -> 5.0
|
|
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList):',
|
|
' localList = [e for e in myList if isinstance(e, Number)]',
|
|
' if not localList: return',
|
|
' return float(sum(localList)) / len(localList)']);
|
|
code = functionName + '(' + list + ')';
|
|
break;
|
|
}
|
|
case 'MEDIAN': {
|
|
Blockly.Python.definitions_['from_numbers_import_Number'] =
|
|
'from numbers import Number';
|
|
const functionName = Blockly.Python.provideFunction_(
|
|
'math_median',
|
|
// This operation excludes null values:
|
|
// math_median([null, null, 1, 3]) -> 2.0
|
|
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(myList):',
|
|
' localList = sorted([e for e in myList if isinstance(e, Number)])',
|
|
' if not localList: return',
|
|
' if len(localList) % 2 == 0:',
|
|
' return (localList[len(localList) // 2 - 1] + ' +
|
|
'localList[len(localList) // 2]) / 2.0',
|
|
' else:',
|
|
' return localList[(len(localList) - 1) // 2]']);
|
|
code = functionName + '(' + list + ')';
|
|
break;
|
|
}
|
|
case 'MODE': {
|
|
const functionName = Blockly.Python.provideFunction_(
|
|
'math_modes',
|
|
// 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]
|
|
['def ' + Blockly.Python.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.',
|
|
' counts = []',
|
|
' maxCount = 1',
|
|
' for item in some_list:',
|
|
' found = False',
|
|
' for count in counts:',
|
|
' if count[0] == item:',
|
|
' count[1] += 1',
|
|
' maxCount = max(maxCount, count[1])',
|
|
' found = True',
|
|
' if not found:',
|
|
' counts.append([item, 1])',
|
|
' for counted_item, item_count in counts:',
|
|
' if item_count == maxCount:',
|
|
' modes.append(counted_item)',
|
|
' return modes']);
|
|
code = functionName + '(' + list + ')';
|
|
break;
|
|
}
|
|
case 'STD_DEV': {
|
|
Blockly.Python.definitions_['import_math'] = 'import math';
|
|
const functionName = Blockly.Python.provideFunction_(
|
|
'math_standard_deviation',
|
|
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(numbers):',
|
|
' n = len(numbers)',
|
|
' if n == 0: return',
|
|
' mean = float(sum(numbers)) / n',
|
|
' variance = sum((x - mean) ** 2 for x in numbers) / n',
|
|
' return math.sqrt(variance)']);
|
|
code = functionName + '(' + list + ')';
|
|
break;
|
|
}
|
|
case 'RANDOM':
|
|
Blockly.Python.definitions_['import_random'] = 'import random';
|
|
code = 'random.choice(' + list + ')';
|
|
break;
|
|
default:
|
|
throw Error('Unknown operator: ' + func);
|
|
}
|
|
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
|
|
};
|
|
|
|
Blockly.Python['math_modulo'] = function(block) {
|
|
// Remainder computation.
|
|
const argument0 = Blockly.Python.valueToCode(block, 'DIVIDEND',
|
|
Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
|
|
const argument1 = Blockly.Python.valueToCode(block, 'DIVISOR',
|
|
Blockly.Python.ORDER_MULTIPLICATIVE) || '0';
|
|
const code = argument0 + ' % ' + argument1;
|
|
return [code, Blockly.Python.ORDER_MULTIPLICATIVE];
|
|
};
|
|
|
|
Blockly.Python['math_constrain'] = function(block) {
|
|
// Constrain a number between two limits.
|
|
const argument0 = Blockly.Python.valueToCode(block, 'VALUE',
|
|
Blockly.Python.ORDER_NONE) || '0';
|
|
const argument1 = Blockly.Python.valueToCode(block, 'LOW',
|
|
Blockly.Python.ORDER_NONE) || '0';
|
|
const argument2 = Blockly.Python.valueToCode(block, 'HIGH',
|
|
Blockly.Python.ORDER_NONE) || 'float(\'inf\')';
|
|
const code = 'min(max(' + argument0 + ', ' + argument1 + '), ' +
|
|
argument2 + ')';
|
|
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
|
|
};
|
|
|
|
Blockly.Python['math_random_int'] = function(block) {
|
|
// Random integer between [X] and [Y].
|
|
Blockly.Python.definitions_['import_random'] = 'import random';
|
|
const argument0 = Blockly.Python.valueToCode(block, 'FROM',
|
|
Blockly.Python.ORDER_NONE) || '0';
|
|
const argument1 = Blockly.Python.valueToCode(block, 'TO',
|
|
Blockly.Python.ORDER_NONE) || '0';
|
|
const code = 'random.randint(' + argument0 + ', ' + argument1 + ')';
|
|
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
|
|
};
|
|
|
|
Blockly.Python['math_random_float'] = function(block) {
|
|
// Random fraction between 0 and 1.
|
|
Blockly.Python.definitions_['import_random'] = 'import random';
|
|
return ['random.random()', Blockly.Python.ORDER_FUNCTION_CALL];
|
|
};
|
|
|
|
Blockly.Python['math_atan2'] = function(block) {
|
|
// Arctangent of point (X, Y) in degrees from -180 to 180.
|
|
Blockly.Python.definitions_['import_math'] = 'import math';
|
|
const argument0 = Blockly.Python.valueToCode(block, 'X',
|
|
Blockly.Python.ORDER_NONE) || '0';
|
|
const argument1 = Blockly.Python.valueToCode(block, 'Y',
|
|
Blockly.Python.ORDER_NONE) || '0';
|
|
return ['math.atan2(' + argument1 + ', ' + argument0 + ') / math.pi * 180',
|
|
Blockly.Python.ORDER_MULTIPLICATIVE];
|
|
};
|