mirror of
https://github.com/google/blockly.git
synced 2026-01-10 10:27:08 +01:00
refactor(generators): Restructure generator modules to contain side effects (#7173)
* refactor(generators): Move lang.js -> lang/lang_gernator.js
Move the LangGenerator definitions into their respective
subdirectories and add a _generator suffix to their filenames,
i.e. generators/javascript.js becomes
generators/javascript/javascript_generator.js.
This is to keep related code together and allow the `lang/all.js`
entrypoints to be moved to the top level generators/ directory.
No goog module IDs were changed, so playground and test code
that accesses this modules by filename does not need to be modified.
* refactor(generators) Move lang/all.js -> lang.js
- Move the entrypoints in generators/*/all.js to correspondingly-named
files in generators/ instead—i.e., generators/javascript/all.js
becomes generators/javascript.js.
- Update build_tasks.js accordingly.
* fix(generators): Add missing exports for LuaGenerator, PhpGenerator
These were inadvertently omitted from #7161 and #7162, respectively.
* refactor(generators): Make block generator modules side-effect free
- Move declaration of <lang>Generator instance from
generators/<lang>/<lang>_generator.js to generators/<lang>.js.
- Move .addReservedWords() calls from generators/<lang>/*.js to
generators/<lang>.js
- Modify generators/<lang>/*.js to export block generator functions
individually, rather than installing on <lang>Generator instance.
- Modify generators/<lang>.js to import and install block generator
functions on <lang>Generator instance.
* fix(tests): Fix tests broken by restructuring of generators
Where these tests needed block generator functions preinstalled
they should have been importing the Blockly.<Lang>.all module.
Where they do not need the provided block generator functions
they can now create their own empty <Lang>Generator instances.
* chore: Update renamings file
- Fix a malformation in previous entries that was not detected by
the renaming file validator test.
- Add entries describing the work done in this and related recent
PRs.
* fix: Correct minor errors in PR #7173
- Fix a search-and-replace error in renamings.json5
- Fix an incorrect-but-usable import in generator_test.js
This commit is contained in:
committed by
GitHub
parent
021a560ef0
commit
130989763c
@@ -1,26 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2021 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Complete helper functions for generating Python for
|
||||
* blocks. This is the entrypoint for python_compressed.js.
|
||||
* @suppress {extraRequire}
|
||||
*/
|
||||
|
||||
import * as goog from '../../closure/goog/goog.js';
|
||||
goog.declareModuleId('Blockly.Python.all');
|
||||
|
||||
import './colour.js';
|
||||
import './lists.js';
|
||||
import './logic.js';
|
||||
import './loops.js';
|
||||
import './math.js';
|
||||
import './procedures.js';
|
||||
import './text.js';
|
||||
import './variables.js';
|
||||
import './variables_dynamic.js';
|
||||
|
||||
export * from '../python.js';
|
||||
@@ -11,23 +11,23 @@
|
||||
import * as goog from '../../closure/goog/goog.js';
|
||||
goog.declareModuleId('Blockly.Python.colour');
|
||||
|
||||
import {pythonGenerator, Order} from '../python.js';
|
||||
import {Order} from './python_generator.js';
|
||||
|
||||
|
||||
pythonGenerator.forBlock['colour_picker'] = function(block, generator) {
|
||||
export function colour_picker(block, generator) {
|
||||
// Colour picker.
|
||||
const code = generator.quote_(block.getFieldValue('COLOUR'));
|
||||
return [code, Order.ATOMIC];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['colour_random'] = function(block, generator) {
|
||||
export function colour_random(block, generator) {
|
||||
// Generate a random colour.
|
||||
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, generator) {
|
||||
export function colour_rgb(block, generator) {
|
||||
// Compose a colour from RGB components expressed as percentages.
|
||||
const functionName = generator.provideFunction_('colour_rgb', `
|
||||
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(r, g, b):
|
||||
@@ -43,7 +43,7 @@ def ${generator.FUNCTION_NAME_PLACEHOLDER_}(r, g, b):
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['colour_blend'] = function(block, generator) {
|
||||
export function colour_blend(block, generator) {
|
||||
// Blend two colours together.
|
||||
const functionName = generator.provideFunction_('colour_blend', `
|
||||
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(colour1, colour2, ratio):
|
||||
|
||||
@@ -13,15 +13,15 @@ goog.declareModuleId('Blockly.Python.lists');
|
||||
|
||||
import * as stringUtils from '../../core/utils/string.js';
|
||||
import {NameType} from '../../core/names.js';
|
||||
import {pythonGenerator, Order} from '../python.js';
|
||||
import {Order} from './python_generator.js';
|
||||
|
||||
|
||||
pythonGenerator.forBlock['lists_create_empty'] = function(block, generator) {
|
||||
export function lists_create_empty(block, generator) {
|
||||
// Create an empty list.
|
||||
return ['[]', Order.ATOMIC];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['lists_create_with'] = function(block, generator) {
|
||||
export function lists_create_with(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++) {
|
||||
@@ -32,7 +32,7 @@ pythonGenerator.forBlock['lists_create_with'] = function(block, generator) {
|
||||
return [code, Order.ATOMIC];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['lists_repeat'] = function(block, generator) {
|
||||
export function lists_repeat(block, generator) {
|
||||
// Create a list with one element repeated.
|
||||
const item = generator.valueToCode(block, 'ITEM', Order.NONE) || 'None';
|
||||
const times =
|
||||
@@ -41,20 +41,20 @@ pythonGenerator.forBlock['lists_repeat'] = function(block, generator) {
|
||||
return [code, Order.MULTIPLICATIVE];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['lists_length'] = function(block, generator) {
|
||||
export function lists_length(block, generator) {
|
||||
// String or array length.
|
||||
const list = generator.valueToCode(block, 'VALUE', Order.NONE) || '[]';
|
||||
return ['len(' + list + ')', Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['lists_isEmpty'] = function(block, generator) {
|
||||
export function lists_isEmpty(block, generator) {
|
||||
// Is the string null or array empty?
|
||||
const list = generator.valueToCode(block, 'VALUE', Order.NONE) || '[]';
|
||||
const code = 'not len(' + list + ')';
|
||||
return [code, Order.LOGICAL_NOT];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['lists_indexOf'] = function(block, generator) {
|
||||
export function lists_indexOf(block, generator) {
|
||||
// Find an item in the list.
|
||||
const item = generator.valueToCode(block, 'FIND', Order.NONE) || '[]';
|
||||
const list = generator.valueToCode(block, 'VALUE', Order.NONE) || "''";
|
||||
@@ -88,7 +88,7 @@ def ${generator.FUNCTION_NAME_PLACEHOLDER_}(my_list, elem):
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['lists_getIndex'] = function(block, generator) {
|
||||
export function lists_getIndex(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';
|
||||
@@ -170,7 +170,7 @@ def ${generator.FUNCTION_NAME_PLACEHOLDER_}(myList):
|
||||
throw Error('Unhandled combination (lists_getIndex).');
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['lists_setIndex'] = function(block, generator) {
|
||||
export function lists_setIndex(block, generator) {
|
||||
// Set element at index.
|
||||
// Note: Until February 2013 this block did not have MODE or WHERE inputs.
|
||||
let list = generator.valueToCode(block, 'LIST', Order.MEMBER) || '[]';
|
||||
@@ -242,7 +242,7 @@ pythonGenerator.forBlock['lists_setIndex'] = function(block, generator) {
|
||||
throw Error('Unhandled combination (lists_setIndex).');
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['lists_getSublist'] = function(block, generator) {
|
||||
export function lists_getSublist(block, generator) {
|
||||
// Get sublist.
|
||||
const list = generator.valueToCode(block, 'LIST', Order.MEMBER) || '[]';
|
||||
const where1 = block.getFieldValue('WHERE1');
|
||||
@@ -291,7 +291,7 @@ pythonGenerator.forBlock['lists_getSublist'] = function(block, generator) {
|
||||
return [code, Order.MEMBER];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['lists_sort'] = function(block, generator) {
|
||||
export function lists_sort(block, generator) {
|
||||
// Block for sorting a list.
|
||||
const list = (generator.valueToCode(block, 'LIST', Order.NONE) || '[]');
|
||||
const type = block.getFieldValue('TYPE');
|
||||
@@ -318,7 +318,7 @@ def ${generator.FUNCTION_NAME_PLACEHOLDER_}(my_list, type, reverse):
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['lists_split'] = function(block, generator) {
|
||||
export function lists_split(block, generator) {
|
||||
// Block for splitting text into a list, or joining a list into text.
|
||||
const mode = block.getFieldValue('MODE');
|
||||
let code;
|
||||
@@ -339,7 +339,7 @@ pythonGenerator.forBlock['lists_split'] = function(block, generator) {
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['lists_reverse'] = function(block, generator) {
|
||||
export function lists_reverse(block, generator) {
|
||||
// Block for reversing a list.
|
||||
const list = generator.valueToCode(block, 'LIST', Order.NONE) || '[]';
|
||||
const code = 'list(reversed(' + list + '))';
|
||||
|
||||
@@ -11,10 +11,10 @@
|
||||
import * as goog from '../../closure/goog/goog.js';
|
||||
goog.declareModuleId('Blockly.Python.logic');
|
||||
|
||||
import {pythonGenerator, Order} from '../python.js';
|
||||
import {Order} from './python_generator.js';
|
||||
|
||||
|
||||
pythonGenerator.forBlock['controls_if'] = function(block, generator) {
|
||||
export function controls_if(block, generator) {
|
||||
// If/elseif/else condition.
|
||||
let n = 0;
|
||||
let code = '', branchCode, conditionCode;
|
||||
@@ -55,10 +55,9 @@ pythonGenerator.forBlock['controls_if'] = function(block, generator) {
|
||||
return code;
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['controls_ifelse'] =
|
||||
pythonGenerator.forBlock['controls_if'];
|
||||
export const controls_ifelse = controls_if;
|
||||
|
||||
pythonGenerator.forBlock['logic_compare'] = function(block, generator) {
|
||||
export function logic_compare(block, generator) {
|
||||
// Comparison operator.
|
||||
const OPERATORS =
|
||||
{'EQ': '==', 'NEQ': '!=', 'LT': '<', 'LTE': '<=', 'GT': '>', 'GTE': '>='};
|
||||
@@ -70,7 +69,7 @@ pythonGenerator.forBlock['logic_compare'] = function(block, generator) {
|
||||
return [code, order];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['logic_operation'] = function(block, generator) {
|
||||
export function logic_operation(block, generator) {
|
||||
// Operations 'and', 'or'.
|
||||
const operator = (block.getFieldValue('OP') === 'AND') ? 'and' : 'or';
|
||||
const order =
|
||||
@@ -95,7 +94,7 @@ pythonGenerator.forBlock['logic_operation'] = function(block, generator) {
|
||||
return [code, order];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['logic_negate'] = function(block, generator) {
|
||||
export function logic_negate(block, generator) {
|
||||
// Negation.
|
||||
const argument0 =
|
||||
generator.valueToCode(block, 'BOOL', Order.LOGICAL_NOT) || 'True';
|
||||
@@ -103,18 +102,18 @@ pythonGenerator.forBlock['logic_negate'] = function(block, generator) {
|
||||
return [code, Order.LOGICAL_NOT];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['logic_boolean'] = function(block, generator) {
|
||||
export function logic_boolean(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, generator) {
|
||||
export function logic_null(block, generator) {
|
||||
// Null data type.
|
||||
return ['None', Order.ATOMIC];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['logic_ternary'] = function(block, generator) {
|
||||
export function logic_ternary(block, generator) {
|
||||
// Ternary operator.
|
||||
const value_if =
|
||||
generator.valueToCode(block, 'IF', Order.CONDITIONAL) || 'False';
|
||||
|
||||
@@ -13,10 +13,10 @@ goog.declareModuleId('Blockly.Python.loops');
|
||||
|
||||
import * as stringUtils from '../../core/utils/string.js';
|
||||
import {NameType} from '../../core/names.js';
|
||||
import {pythonGenerator, Order} from '../python.js';
|
||||
import {Order} from './python_generator.js';
|
||||
|
||||
|
||||
pythonGenerator.forBlock['controls_repeat_ext'] = function(block, generator) {
|
||||
export function controls_repeat_ext(block, generator) {
|
||||
// Repeat n times.
|
||||
let repeats;
|
||||
if (block.getField('TIMES')) {
|
||||
@@ -39,10 +39,9 @@ pythonGenerator.forBlock['controls_repeat_ext'] = function(block, generator) {
|
||||
return code;
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['controls_repeat'] =
|
||||
pythonGenerator.forBlock['controls_repeat_ext'];
|
||||
export const controls_repeat = controls_repeat_ext;
|
||||
|
||||
pythonGenerator.forBlock['controls_whileUntil'] = function(block, generator) {
|
||||
export function controls_whileUntil(block, generator) {
|
||||
// Do while/until loop.
|
||||
const until = block.getFieldValue('MODE') === 'UNTIL';
|
||||
let argument0 = generator.valueToCode(
|
||||
@@ -57,7 +56,7 @@ pythonGenerator.forBlock['controls_whileUntil'] = function(block, generator) {
|
||||
return 'while ' + argument0 + ':\n' + branch;
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['controls_for'] = function(block, generator) {
|
||||
export function controls_for(block, generator) {
|
||||
// For loop.
|
||||
const variable0 =
|
||||
generator.nameDB_.getName(
|
||||
@@ -166,7 +165,7 @@ def ${generator.FUNCTION_NAME_PLACEHOLDER_}(start, stop, step):
|
||||
return code;
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['controls_forEach'] = function(block, generator) {
|
||||
export function controls_forEach(block, generator) {
|
||||
// For each loop.
|
||||
const variable0 =
|
||||
generator.nameDB_.getName(
|
||||
@@ -179,7 +178,7 @@ pythonGenerator.forBlock['controls_forEach'] = function(block, generator) {
|
||||
return code;
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['controls_flow_statements'] = function(block, generator) {
|
||||
export function controls_flow_statements(block, generator) {
|
||||
// Flow statements: continue, break.
|
||||
let xfix = '';
|
||||
if (generator.STATEMENT_PREFIX) {
|
||||
|
||||
@@ -12,13 +12,13 @@ import * as goog from '../../closure/goog/goog.js';
|
||||
goog.declareModuleId('Blockly.Python.math');
|
||||
|
||||
import {NameType} from '../../core/names.js';
|
||||
import {pythonGenerator, Order} from '../python.js';
|
||||
import {Order} from './python_generator.js';
|
||||
|
||||
|
||||
// If any new block imports any library, add that library name here.
|
||||
pythonGenerator.addReservedWords('math,random,Number');
|
||||
// RESERVED WORDS: 'math,random,Number'
|
||||
|
||||
pythonGenerator.forBlock['math_number'] = function(block, generator) {
|
||||
export function math_number(block, generator) {
|
||||
// Numeric value.
|
||||
let code = Number(block.getFieldValue('NUM'));
|
||||
let order;
|
||||
@@ -34,7 +34,7 @@ pythonGenerator.forBlock['math_number'] = function(block, generator) {
|
||||
return [code, order];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['math_arithmetic'] = function(block, generator) {
|
||||
export function math_arithmetic(block, generator) {
|
||||
// Basic arithmetic operators, and power.
|
||||
const OPERATORS = {
|
||||
'ADD': [' + ', Order.ADDITIVE],
|
||||
@@ -57,7 +57,7 @@ pythonGenerator.forBlock['math_arithmetic'] = function(block, generator) {
|
||||
// legibility of the generated code.
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['math_single'] = function(block, generator) {
|
||||
export function math_single(block, generator) {
|
||||
// Math operators with single operand.
|
||||
const operator = block.getFieldValue('OP');
|
||||
let code;
|
||||
@@ -135,7 +135,7 @@ pythonGenerator.forBlock['math_single'] = function(block, generator) {
|
||||
return [code, Order.MULTIPLICATIVE];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['math_constant'] = function(block, generator) {
|
||||
export function math_constant(block, generator) {
|
||||
// Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY.
|
||||
const CONSTANTS = {
|
||||
'PI': ['math.pi', Order.MEMBER],
|
||||
@@ -152,7 +152,7 @@ pythonGenerator.forBlock['math_constant'] = function(block, generator) {
|
||||
return CONSTANTS[constant];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['math_number_property'] = function(block, generator) {
|
||||
export function math_number_property(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 = {
|
||||
@@ -211,7 +211,7 @@ def ${generator.FUNCTION_NAME_PLACEHOLDER_}(n):
|
||||
return [code, outputOrder];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['math_change'] = function(block, generator) {
|
||||
export function math_change(block, generator) {
|
||||
// Add to a variable in place.
|
||||
generator.definitions_['from_numbers_import_Number'] =
|
||||
'from numbers import Number';
|
||||
@@ -225,13 +225,11 @@ pythonGenerator.forBlock['math_change'] = function(block, generator) {
|
||||
};
|
||||
|
||||
// Rounding functions have a single operand.
|
||||
pythonGenerator.forBlock['math_round'] =
|
||||
pythonGenerator.forBlock['math_single'];
|
||||
export const math_round = math_single;
|
||||
// Trigonometry functions have a single operand.
|
||||
pythonGenerator.forBlock['math_trig'] =
|
||||
pythonGenerator.forBlock['math_single'];
|
||||
export const math_trig = math_single;
|
||||
|
||||
pythonGenerator.forBlock['math_on_list'] = function(block, generator) {
|
||||
export function math_on_list(block, generator) {
|
||||
// Math functions for lists.
|
||||
const func = block.getFieldValue('OP');
|
||||
const list = generator.valueToCode(block, 'LIST', Order.NONE) || '[]';
|
||||
@@ -329,7 +327,7 @@ def ${generator.FUNCTION_NAME_PLACEHOLDER_}(numbers):
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['math_modulo'] = function(block, generator) {
|
||||
export function math_modulo(block, generator) {
|
||||
// Remainder computation.
|
||||
const argument0 =
|
||||
generator.valueToCode(block, 'DIVIDEND', Order.MULTIPLICATIVE) ||
|
||||
@@ -341,7 +339,7 @@ pythonGenerator.forBlock['math_modulo'] = function(block, generator) {
|
||||
return [code, Order.MULTIPLICATIVE];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['math_constrain'] = function(block, generator) {
|
||||
export function math_constrain(block, generator) {
|
||||
// Constrain a number between two limits.
|
||||
const argument0 =
|
||||
generator.valueToCode(block, 'VALUE', Order.NONE) || '0';
|
||||
@@ -355,7 +353,7 @@ pythonGenerator.forBlock['math_constrain'] = function(block, generator) {
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['math_random_int'] = function(block, generator) {
|
||||
export function math_random_int(block, generator) {
|
||||
// Random integer between [X] and [Y].
|
||||
generator.definitions_['import_random'] = 'import random';
|
||||
const argument0 =
|
||||
@@ -366,13 +364,13 @@ pythonGenerator.forBlock['math_random_int'] = function(block, generator) {
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['math_random_float'] = function(block, generator) {
|
||||
export function math_random_float(block, generator) {
|
||||
// Random fraction between 0 and 1.
|
||||
generator.definitions_['import_random'] = 'import random';
|
||||
return ['random.random()', Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['math_atan2'] = function(block, generator) {
|
||||
export function math_atan2(block, generator) {
|
||||
// Arctangent of point (X, Y) in degrees from -180 to 180.
|
||||
generator.definitions_['import_math'] = 'import math';
|
||||
const argument0 = generator.valueToCode(block, 'X', Order.NONE) || '0';
|
||||
|
||||
@@ -13,10 +13,10 @@ goog.declareModuleId('Blockly.Python.procedures');
|
||||
|
||||
import * as Variables from '../../core/variables.js';
|
||||
import {NameType} from '../../core/names.js';
|
||||
import {pythonGenerator, Order} from '../python.js';
|
||||
import {Order} from './python_generator.js';
|
||||
|
||||
|
||||
pythonGenerator.forBlock['procedures_defreturn'] = function(block, generator) {
|
||||
export function procedures_defreturn(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.
|
||||
@@ -87,10 +87,9 @@ pythonGenerator.forBlock['procedures_defreturn'] = function(block, generator) {
|
||||
|
||||
// Defining a procedure without a return value uses the same generator as
|
||||
// a procedure with a return value.
|
||||
pythonGenerator.forBlock['procedures_defnoreturn'] =
|
||||
pythonGenerator.forBlock['procedures_defreturn'];
|
||||
export const procedures_defnoreturn = procedures_defreturn;
|
||||
|
||||
pythonGenerator.forBlock['procedures_callreturn'] = function(block, generator) {
|
||||
export function procedures_callreturn(block, generator) {
|
||||
// Call a procedure with a return value.
|
||||
const funcName =
|
||||
generator.nameDB_.getName(
|
||||
@@ -105,7 +104,7 @@ pythonGenerator.forBlock['procedures_callreturn'] = function(block, generator) {
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['procedures_callnoreturn'] = function(block, generator) {
|
||||
export function procedures_callnoreturn(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.
|
||||
@@ -113,7 +112,7 @@ pythonGenerator.forBlock['procedures_callnoreturn'] = function(block, generator)
|
||||
return tuple[0] + '\n';
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['procedures_ifreturn'] = function(block, generator) {
|
||||
export function procedures_ifreturn(block, generator) {
|
||||
// Conditionally return value from a procedure.
|
||||
const condition =
|
||||
generator.valueToCode(block, 'CONDITION', Order.NONE) || 'False';
|
||||
|
||||
340
generators/python/python_generator.js
Normal file
340
generators/python/python_generator.js
Normal file
@@ -0,0 +1,340 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2012 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Helper functions for generating Python for blocks.
|
||||
* @suppress {checkTypes|globalThis}
|
||||
*/
|
||||
|
||||
import * as goog from '../../closure/goog/goog.js';
|
||||
goog.declareModuleId('Blockly.Python');
|
||||
|
||||
import * as stringUtils from '../../core/utils/string.js';
|
||||
import * as Variables from '../../core/variables.js';
|
||||
// import type {Block} from '../../core/block.js';
|
||||
import {CodeGenerator} from '../../core/generator.js';
|
||||
import {Names, NameType} from '../../core/names.js';
|
||||
// import type {Workspace} from '../../core/workspace.js';
|
||||
import {inputTypes} from '../../core/inputs/input_types.js';
|
||||
|
||||
|
||||
/**
|
||||
* Order of operation ENUMs.
|
||||
* http://docs.python.org/reference/expressions.html#summary
|
||||
* @enum {number}
|
||||
*/
|
||||
export const Order = {
|
||||
ATOMIC: 0, // 0 "" ...
|
||||
COLLECTION: 1, // tuples, lists, dictionaries
|
||||
STRING_CONVERSION: 1, // `expression...`
|
||||
MEMBER: 2.1, // . []
|
||||
FUNCTION_CALL: 2.2, // ()
|
||||
EXPONENTIATION: 3, // **
|
||||
UNARY_SIGN: 4, // + -
|
||||
BITWISE_NOT: 4, // ~
|
||||
MULTIPLICATIVE: 5, // * / // %
|
||||
ADDITIVE: 6, // + -
|
||||
BITWISE_SHIFT: 7, // << >>
|
||||
BITWISE_AND: 8, // &
|
||||
BITWISE_XOR: 9, // ^
|
||||
BITWISE_OR: 10, // |
|
||||
RELATIONAL: 11, // in, not in, is, is not, >, >=, <>, !=, ==
|
||||
LOGICAL_NOT: 12, // not
|
||||
LOGICAL_AND: 13, // and
|
||||
LOGICAL_OR: 14, // or
|
||||
CONDITIONAL: 15, // if else
|
||||
LAMBDA: 16, // lambda
|
||||
NONE: 99, // (...)
|
||||
};
|
||||
|
||||
/**
|
||||
* PythonScript code generator class.
|
||||
*/
|
||||
export class PythonGenerator extends CodeGenerator {
|
||||
/**
|
||||
* List of outer-inner pairings that do NOT require parentheses.
|
||||
* @type {!Array<!Array<number>>}
|
||||
*/
|
||||
ORDER_OVERRIDES = [
|
||||
// (foo()).bar -> foo().bar
|
||||
// (foo())[0] -> foo()[0]
|
||||
[Order.FUNCTION_CALL, Order.MEMBER],
|
||||
// (foo())() -> foo()()
|
||||
[Order.FUNCTION_CALL, Order.FUNCTION_CALL],
|
||||
// (foo.bar).baz -> foo.bar.baz
|
||||
// (foo.bar)[0] -> foo.bar[0]
|
||||
// (foo[0]).bar -> foo[0].bar
|
||||
// (foo[0])[1] -> foo[0][1]
|
||||
[Order.MEMBER, Order.MEMBER],
|
||||
// (foo.bar)() -> foo.bar()
|
||||
// (foo[0])() -> foo[0]()
|
||||
[Order.MEMBER, Order.FUNCTION_CALL],
|
||||
|
||||
// not (not foo) -> not not foo
|
||||
[Order.LOGICAL_NOT, Order.LOGICAL_NOT],
|
||||
// a and (b and c) -> a and b and c
|
||||
[Order.LOGICAL_AND, Order.LOGICAL_AND],
|
||||
// a or (b or c) -> a or b or c
|
||||
[Order.LOGICAL_OR, Order.LOGICAL_OR]
|
||||
];
|
||||
|
||||
constructor(name) {
|
||||
super(name ?? 'Python');
|
||||
this.isInitialized = false;
|
||||
|
||||
// Copy Order values onto instance for backwards compatibility
|
||||
// while ensuring they are not part of the publically-advertised
|
||||
// API.
|
||||
//
|
||||
// TODO(#7085): deprecate these in due course. (Could initially
|
||||
// replace data properties with get accessors that call
|
||||
// deprecate.warn().)
|
||||
for (const key in Order) {
|
||||
this['ORDER_' + key] = Order[key];
|
||||
}
|
||||
|
||||
// List of illegal variable names. This is not intended to be a
|
||||
// security feature. Blockly is 100% client-side, so bypassing
|
||||
// this list is trivial. This is intended to prevent users from
|
||||
// accidentally clobbering a built-in object or function.
|
||||
this.addReservedWords(
|
||||
// import keyword
|
||||
// print(','.join(sorted(keyword.kwlist)))
|
||||
// https://docs.python.org/3/reference/lexical_analysis.html#keywords
|
||||
// https://docs.python.org/2/reference/lexical_analysis.html#keywords
|
||||
'False,None,True,and,as,assert,break,class,continue,def,del,elif,else,' +
|
||||
'except,exec,finally,for,from,global,if,import,in,is,lambda,nonlocal,' +
|
||||
'not,or,pass,print,raise,return,try,while,with,yield,' +
|
||||
// https://docs.python.org/3/library/constants.html
|
||||
// https://docs.python.org/2/library/constants.html
|
||||
'NotImplemented,Ellipsis,__debug__,quit,exit,copyright,license,credits,' +
|
||||
// >>> print(','.join(sorted(dir(__builtins__))))
|
||||
// https://docs.python.org/3/library/functions.html
|
||||
// https://docs.python.org/2/library/functions.html
|
||||
'ArithmeticError,AssertionError,AttributeError,BaseException,' +
|
||||
'BlockingIOError,BrokenPipeError,BufferError,BytesWarning,' +
|
||||
'ChildProcessError,ConnectionAbortedError,ConnectionError,' +
|
||||
'ConnectionRefusedError,ConnectionResetError,DeprecationWarning,' +
|
||||
'EOFError,Ellipsis,EnvironmentError,Exception,FileExistsError,' +
|
||||
'FileNotFoundError,FloatingPointError,FutureWarning,GeneratorExit,' +
|
||||
'IOError,ImportError,ImportWarning,IndentationError,IndexError,' +
|
||||
'InterruptedError,IsADirectoryError,KeyError,KeyboardInterrupt,' +
|
||||
'LookupError,MemoryError,ModuleNotFoundError,NameError,' +
|
||||
'NotADirectoryError,NotImplemented,NotImplementedError,OSError,' +
|
||||
'OverflowError,PendingDeprecationWarning,PermissionError,' +
|
||||
'ProcessLookupError,RecursionError,ReferenceError,ResourceWarning,' +
|
||||
'RuntimeError,RuntimeWarning,StandardError,StopAsyncIteration,' +
|
||||
'StopIteration,SyntaxError,SyntaxWarning,SystemError,SystemExit,' +
|
||||
'TabError,TimeoutError,TypeError,UnboundLocalError,UnicodeDecodeError,' +
|
||||
'UnicodeEncodeError,UnicodeError,UnicodeTranslateError,UnicodeWarning,' +
|
||||
'UserWarning,ValueError,Warning,ZeroDivisionError,_,__build_class__,' +
|
||||
'__debug__,__doc__,__import__,__loader__,__name__,__package__,__spec__,' +
|
||||
'abs,all,any,apply,ascii,basestring,bin,bool,buffer,bytearray,bytes,' +
|
||||
'callable,chr,classmethod,cmp,coerce,compile,complex,copyright,credits,' +
|
||||
'delattr,dict,dir,divmod,enumerate,eval,exec,execfile,exit,file,filter,' +
|
||||
'float,format,frozenset,getattr,globals,hasattr,hash,help,hex,id,input,' +
|
||||
'int,intern,isinstance,issubclass,iter,len,license,list,locals,long,' +
|
||||
'map,max,memoryview,min,next,object,oct,open,ord,pow,print,property,' +
|
||||
'quit,range,raw_input,reduce,reload,repr,reversed,round,set,setattr,' +
|
||||
'slice,sorted,staticmethod,str,sum,super,tuple,type,unichr,unicode,' +
|
||||
'vars,xrange,zip'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialise the database of variable names.
|
||||
* @param {!Workspace} workspace Workspace to generate code from.
|
||||
* @this {CodeGenerator}
|
||||
*/
|
||||
init(workspace) {
|
||||
super.init(workspace);
|
||||
|
||||
/**
|
||||
* Empty loops or conditionals are not allowed in Python.
|
||||
*/
|
||||
this.PASS = this.INDENT + 'pass\n';
|
||||
|
||||
if (!this.nameDB_) {
|
||||
this.nameDB_ = new Names(this.RESERVED_WORDS_);
|
||||
} else {
|
||||
this.nameDB_.reset();
|
||||
}
|
||||
|
||||
this.nameDB_.setVariableMap(workspace.getVariableMap());
|
||||
this.nameDB_.populateVariables(workspace);
|
||||
this.nameDB_.populateProcedures(workspace);
|
||||
|
||||
const defvars = [];
|
||||
// Add developer variables (not created or named by the user).
|
||||
const devVarList = Variables.allDeveloperVariables(workspace);
|
||||
for (let i = 0; i < devVarList.length; i++) {
|
||||
defvars.push(
|
||||
this.nameDB_.getName(devVarList[i], Names.DEVELOPER_VARIABLE_TYPE) +
|
||||
' = None');
|
||||
}
|
||||
|
||||
// Add user variables, but only ones that are being used.
|
||||
const variables = Variables.allUsedVarModels(workspace);
|
||||
for (let i = 0; i < variables.length; i++) {
|
||||
defvars.push(
|
||||
this.nameDB_.getName(variables[i].getId(), NameType.VARIABLE) +
|
||||
' = None');
|
||||
}
|
||||
|
||||
this.definitions_['variables'] = defvars.join('\n');
|
||||
this.isInitialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepend the generated code with import statements and variable definitions.
|
||||
* @param {string} code Generated code.
|
||||
* @return {string} Completed code.
|
||||
*/
|
||||
finish(code) {
|
||||
// Convert the definitions dictionary into a list.
|
||||
const imports = [];
|
||||
const definitions = [];
|
||||
for (let name in this.definitions_) {
|
||||
const def = this.definitions_[name];
|
||||
if (def.match(/^(from\s+\S+\s+)?import\s+\S+/)) {
|
||||
imports.push(def);
|
||||
} else {
|
||||
definitions.push(def);
|
||||
}
|
||||
}
|
||||
// Call Blockly.CodeGenerator's finish.
|
||||
code = super.finish(code);
|
||||
this.isInitialized = false;
|
||||
|
||||
this.nameDB_.reset();
|
||||
const allDefs = imports.join('\n') + '\n\n' + definitions.join('\n\n');
|
||||
return allDefs.replace(/\n\n+/g, '\n\n').replace(/\n*$/, '\n\n\n') + code;
|
||||
}
|
||||
|
||||
/**
|
||||
* Naked values are top-level blocks with outputs that aren't plugged into
|
||||
* anything.
|
||||
* @param {string} line Line of generated code.
|
||||
* @return {string} Legal line of code.
|
||||
*/
|
||||
scrubNakedValue(line) {
|
||||
return line + '\n';
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode a string as a properly escaped Python string, complete with quotes.
|
||||
* @param {string} string Text to encode.
|
||||
* @return {string} Python string.
|
||||
* @protected
|
||||
*/
|
||||
quote_(string) {
|
||||
string = string.replace(/\\/g, '\\\\').replace(/\n/g, '\\\n');
|
||||
|
||||
// Follow the CPython behaviour of repr() for a non-byte string.
|
||||
let quote = '\'';
|
||||
if (string.indexOf('\'') !== -1) {
|
||||
if (string.indexOf('"') === -1) {
|
||||
quote = '"';
|
||||
} else {
|
||||
string = string.replace(/'/g, '\\\'');
|
||||
}
|
||||
}
|
||||
return quote + string + quote;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode a string as a properly escaped multiline Python string, complete
|
||||
* with quotes.
|
||||
* @param {string} string Text to encode.
|
||||
* @return {string} Python string.
|
||||
* @protected
|
||||
*/
|
||||
multiline_quote_(string) {
|
||||
const lines = string.split(/\n/g).map(this.quote_);
|
||||
// Join with the following, plus a newline:
|
||||
// + '\n' +
|
||||
return lines.join(' + \'\\n\' + \n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Common tasks for generating Python from blocks.
|
||||
* Handles comments for the specified block and any connected value blocks.
|
||||
* Calls any statements following this block.
|
||||
* @param {!Block} block The current block.
|
||||
* @param {string} code The Python code created for this block.
|
||||
* @param {boolean=} opt_thisOnly True to generate code for only this statement.
|
||||
* @return {string} Python code with comments and subsequent blocks added.
|
||||
* @protected
|
||||
*/
|
||||
scrub_(block, code, opt_thisOnly) {
|
||||
let commentCode = '';
|
||||
// Only collect comments for blocks that aren't inline.
|
||||
if (!block.outputConnection || !block.outputConnection.targetConnection) {
|
||||
// Collect comment for this block.
|
||||
let comment = block.getCommentText();
|
||||
if (comment) {
|
||||
comment = stringUtils.wrap(comment, this.COMMENT_WRAP - 3);
|
||||
commentCode += this.prefixLines(comment + '\n', '# ');
|
||||
}
|
||||
// Collect comments for all value arguments.
|
||||
// Don't collect comments for nested statements.
|
||||
for (let i = 0; i < block.inputList.length; i++) {
|
||||
if (block.inputList[i].type === inputTypes.VALUE) {
|
||||
const childBlock = block.inputList[i].connection.targetBlock();
|
||||
if (childBlock) {
|
||||
comment = this.allNestedComments(childBlock);
|
||||
if (comment) {
|
||||
commentCode += this.prefixLines(comment, '# ');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const nextBlock = block.nextConnection && block.nextConnection.targetBlock();
|
||||
const nextCode = opt_thisOnly ? '' : this.blockToCode(nextBlock);
|
||||
return commentCode + code + nextCode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a property and adjusts the value, taking into account indexing.
|
||||
* If a static int, casts to an integer, otherwise returns a code string.
|
||||
* @param {!Block} block The block.
|
||||
* @param {string} atId The property ID of the element to get.
|
||||
* @param {number=} opt_delta Value to add.
|
||||
* @param {boolean=} opt_negate Whether to negate the value.
|
||||
* @return {string|number}
|
||||
*/
|
||||
getAdjustedInt(block, atId, opt_delta, opt_negate) {
|
||||
let delta = opt_delta || 0;
|
||||
if (block.workspace.options.oneBasedIndex) {
|
||||
delta--;
|
||||
}
|
||||
const defaultAtIndex = block.workspace.options.oneBasedIndex ? '1' : '0';
|
||||
const atOrder = delta ? this.ORDER_ADDITIVE : this.ORDER_NONE;
|
||||
let at = this.valueToCode(block, atId, atOrder) || defaultAtIndex;
|
||||
|
||||
if (stringUtils.isNumber(at)) {
|
||||
// If the index is a naked number, adjust it right now.
|
||||
at = parseInt(at, 10) + delta;
|
||||
if (opt_negate) {
|
||||
at = -at;
|
||||
}
|
||||
} else {
|
||||
// If the index is dynamic, adjust it in code.
|
||||
if (delta > 0) {
|
||||
at = 'int(' + at + ' + ' + delta + ')';
|
||||
} else if (delta < 0) {
|
||||
at = 'int(' + at + ' - ' + -delta + ')';
|
||||
} else {
|
||||
at = 'int(' + at + ')';
|
||||
}
|
||||
if (opt_negate) {
|
||||
at = '-' + at;
|
||||
}
|
||||
}
|
||||
return at;
|
||||
}
|
||||
}
|
||||
@@ -13,16 +13,16 @@ goog.declareModuleId('Blockly.Python.texts');
|
||||
|
||||
import * as stringUtils from '../../core/utils/string.js';
|
||||
import {NameType} from '../../core/names.js';
|
||||
import {pythonGenerator, Order} from '../python.js';
|
||||
import {Order} from './python_generator.js';
|
||||
|
||||
|
||||
pythonGenerator.forBlock['text'] = function(block, generator) {
|
||||
export function text(block, generator) {
|
||||
// Text value.
|
||||
const code = generator.quote_(block.getFieldValue('TEXT'));
|
||||
return [code, Order.ATOMIC];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['text_multiline'] = function(block, generator) {
|
||||
export function text_multiline(block, generator) {
|
||||
// Text value.
|
||||
const code = generator.multiline_quote_(block.getFieldValue('TEXT'));
|
||||
const order =
|
||||
@@ -50,7 +50,7 @@ const forceString = function(value) {
|
||||
return ['str(' + value + ')', Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['text_join'] = function(block, generator) {
|
||||
export function text_join(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_) {
|
||||
@@ -85,7 +85,7 @@ pythonGenerator.forBlock['text_join'] = function(block, generator) {
|
||||
}
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['text_append'] = function(block, generator) {
|
||||
export function text_append(block, generator) {
|
||||
// Append to a variable in place.
|
||||
const varName =
|
||||
generator.nameDB_.getName(
|
||||
@@ -94,20 +94,20 @@ pythonGenerator.forBlock['text_append'] = function(block, generator) {
|
||||
return varName + ' = str(' + varName + ') + ' + forceString(value)[0] + '\n';
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['text_length'] = function(block, generator) {
|
||||
export function text_length(block, generator) {
|
||||
// Is the string null or array empty?
|
||||
const text = generator.valueToCode(block, 'VALUE', Order.NONE) || "''";
|
||||
return ['len(' + text + ')', Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['text_isEmpty'] = function(block, generator) {
|
||||
export function text_isEmpty(block, generator) {
|
||||
// Is the string null or array empty?
|
||||
const text = generator.valueToCode(block, 'VALUE', Order.NONE) || "''";
|
||||
const code = 'not len(' + text + ')';
|
||||
return [code, Order.LOGICAL_NOT];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['text_indexOf'] = function(block, generator) {
|
||||
export function text_indexOf(block, generator) {
|
||||
// Search the text for a substring.
|
||||
// Should we allow for non-case sensitive???
|
||||
const operator = block.getFieldValue('END') === 'FIRST' ? 'find' : 'rfind';
|
||||
@@ -122,7 +122,7 @@ pythonGenerator.forBlock['text_indexOf'] = function(block, generator) {
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['text_charAt'] = function(block, generator) {
|
||||
export function text_charAt(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';
|
||||
@@ -163,7 +163,7 @@ def ${generator.FUNCTION_NAME_PLACEHOLDER_}(text):
|
||||
throw Error('Unhandled option (text_charAt).');
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['text_getSubstring'] = function(block, generator) {
|
||||
export function text_getSubstring(block, generator) {
|
||||
// Get substring.
|
||||
const where1 = block.getFieldValue('WHERE1');
|
||||
const where2 = block.getFieldValue('WHERE2');
|
||||
@@ -213,7 +213,7 @@ pythonGenerator.forBlock['text_getSubstring'] = function(block, generator) {
|
||||
return [code, Order.MEMBER];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['text_changeCase'] = function(block, generator) {
|
||||
export function text_changeCase(block, generator) {
|
||||
// Change capitalization.
|
||||
const OPERATORS = {
|
||||
'UPPERCASE': '.upper()',
|
||||
@@ -226,7 +226,7 @@ pythonGenerator.forBlock['text_changeCase'] = function(block, generator) {
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['text_trim'] = function(block, generator) {
|
||||
export function text_trim(block, generator) {
|
||||
// Trim spaces.
|
||||
const OPERATORS = {
|
||||
'LEFT': '.lstrip()',
|
||||
@@ -239,13 +239,13 @@ pythonGenerator.forBlock['text_trim'] = function(block, generator) {
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['text_print'] = function(block, generator) {
|
||||
export function text_print(block, generator) {
|
||||
// Print statement.
|
||||
const msg = generator.valueToCode(block, 'TEXT', Order.NONE) || "''";
|
||||
return 'print(' + msg + ')\n';
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['text_prompt_ext'] = function(block, generator) {
|
||||
export function text_prompt_ext(block, generator) {
|
||||
// Prompt function.
|
||||
const functionName = generator.provideFunction_('text_prompt', `
|
||||
def ${generator.FUNCTION_NAME_PLACEHOLDER_}(msg):
|
||||
@@ -270,17 +270,16 @@ def ${generator.FUNCTION_NAME_PLACEHOLDER_}(msg):
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['text_prompt'] =
|
||||
pythonGenerator.forBlock['text_prompt_ext'];
|
||||
export const text_prompt = text_prompt_ext;
|
||||
|
||||
pythonGenerator.forBlock['text_count'] = function(block, generator) {
|
||||
export function text_count(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, generator) {
|
||||
export function text_replace(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) || "''";
|
||||
@@ -288,7 +287,7 @@ pythonGenerator.forBlock['text_replace'] = function(block, generator) {
|
||||
return [code, Order.MEMBER];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['text_reverse'] = function(block, generator) {
|
||||
export function text_reverse(block, generator) {
|
||||
const text = generator.valueToCode(block, 'TEXT', Order.MEMBER) || "''";
|
||||
const code = text + '[::-1]';
|
||||
return [code, Order.MEMBER];
|
||||
|
||||
@@ -12,10 +12,10 @@ import * as goog from '../../closure/goog/goog.js';
|
||||
goog.declareModuleId('Blockly.Python.variables');
|
||||
|
||||
import {NameType} from '../../core/names.js';
|
||||
import {pythonGenerator, Order} from '../python.js';
|
||||
import {Order} from './python_generator.js';
|
||||
|
||||
|
||||
pythonGenerator.forBlock['variables_get'] = function(block, generator) {
|
||||
export function variables_get(block, generator) {
|
||||
// Variable getter.
|
||||
const code =
|
||||
generator.nameDB_.getName(
|
||||
@@ -23,7 +23,7 @@ pythonGenerator.forBlock['variables_get'] = function(block, generator) {
|
||||
return [code, Order.ATOMIC];
|
||||
};
|
||||
|
||||
pythonGenerator.forBlock['variables_set'] = function(block, generator) {
|
||||
export function variables_set(block, generator) {
|
||||
// Variable setter.
|
||||
const argument0 =
|
||||
generator.valueToCode(block, 'VALUE', Order.NONE) || '0';
|
||||
|
||||
@@ -11,10 +11,9 @@
|
||||
import * as goog from '../../closure/goog/goog.js';
|
||||
goog.declareModuleId('Blockly.Python.variablesDynamic');
|
||||
|
||||
import {pythonGenerator} from '../python.js';
|
||||
import './variables.js';
|
||||
|
||||
|
||||
// generator is dynamically typed.
|
||||
pythonGenerator.forBlock['variables_get_dynamic'] = pythonGenerator.forBlock['variables_get'];
|
||||
pythonGenerator.forBlock['variables_set_dynamic'] = pythonGenerator.forBlock['variables_set'];
|
||||
export {
|
||||
variables_get as variables_get_dynamic,
|
||||
variables_set as variables_set_dynamic,
|
||||
} from './variables.js';
|
||||
|
||||
Reference in New Issue
Block a user