mirror of
https://github.com/google/blockly.git
synced 2026-01-04 23:50:12 +01:00
* fix(build): Minor corrections to build_tasks.js
- Use TSC_OUTPUT_DIR to find goog/goog.js when suppressing warnings.
- Remove unnecessary trailing semicolons.
* refactor(blocks): Remove declareLegacyNamespace
Remove the call to goog.module.declareLegacyNamespace from
Blockly.libraryBlocks. This entails:
- Changes to the UMD wrapper to be able to find the exports object.
- Changes to tests/bootstrap_helper.js to save the exports object
in the libraryBlocks global variable.
- As a precaution, renaming the tests/compile/test_blocks.js module
so that goog.provide does not touch Blockly or
Blockly.libraryBlocks, which may not exist / be writable.
* feat(build): Add support named exports from chunks
We need to convert the generators to named exports. For backwards
compatibility we still want e.g. Blockly.JavaScript to point at
the generator object when the chunk is loaded using a script tag.
Modify chunkWrapper to honour a .reexportOnly property in the
chunks table and generate suitable additional code in the UMD
wrapper.
* refactor(generators): Migrate JavaScript generator to named export
- Export the JavaScript generator object as javascriptGenerator
from the Blockly.JavaScript module(generators/javascript.js).
- Modify the Blockly.JavaScript.all module
(generators/javascript/all.js) to reexport the exports from
Blockly.JavaScript.
- Update chunk configuration so the generator object remains
available as Blockly.JavaScript when loading
javascript_compressed.js via a <script> tag.
(N.B. it is otherwise necessary to destructure the require
/ import.)
- Modify bootstrap_helper.js to store that export as
window.javascriptGenerator for use in test code.
- Modify test code to use javascriptGenerator instead of
Blockly.JavaScript.
- Modify .eslintrc.json so that javascriptGenerator is allowed
as a global in test/. (Also restrict use of Blockly global
to test/.)
N.B. that demo code in demos/code/code.js uses <script> tag
loading and so will continue to access Blockly.JavaScript.
* refactor(generators): Migrate Lua generator to named export
* refactor(generators): Migrate PHP generator to named export
* refactor(generators): Migrate Python generator to named export
* refactor(generators): Remove declareLegacyNamespace calls
Remove the goog.module.declareLegacyNamespace calls from the
generators.
This turns out to have the unexpected side-effect of causing the
compiler to rename the core/blockly.js exports object from
$.Blockly to just Blockly in blockly_compressed.js - presumably
because it no longer needs to be accessed in any subsequent chunk
because they no longer add properties to it. This requires
some changes (mainly simplification) to the chunkWrapper function
in build_tasks.js.
* refactor(core): Remove declareLegacyNamespace from blockly.js
So easy to do _now_: just need to:
- Make sure the UMD wrapper for the first chunk knows where the
exports object is.
- Use that same value to set the Blockly.VERSION @define.
- Have bootstrap_helper.js set window.Blockly to the exports
object.
- Fix tests/compile/test_blocks.js to not assume a Blockly
global variable, by converting it to a goog.module so we
can use a named require.
292 lines
9.1 KiB
JavaScript
292 lines
9.1 KiB
JavaScript
/**
|
|
* @license
|
|
* Copyright 2012 Google LLC
|
|
* SPDX-License-Identifier: Apache-2.0
|
|
*/
|
|
|
|
/**
|
|
* @fileoverview Generating Python for text blocks.
|
|
*/
|
|
'use strict';
|
|
|
|
goog.module('Blockly.Python.texts');
|
|
|
|
const stringUtils = goog.require('Blockly.utils.string');
|
|
const {NameType} = goog.require('Blockly.Names');
|
|
const {pythonGenerator: Python} = goog.require('Blockly.Python');
|
|
|
|
|
|
Python['text'] = function(block) {
|
|
// Text value.
|
|
const code = Python.quote_(block.getFieldValue('TEXT'));
|
|
return [code, Python.ORDER_ATOMIC];
|
|
};
|
|
|
|
Python['text_multiline'] = function(block) {
|
|
// Text value.
|
|
const code = Python.multiline_quote_(block.getFieldValue('TEXT'));
|
|
const order =
|
|
code.indexOf('+') !== -1 ? Python.ORDER_ADDITIVE : Python.ORDER_ATOMIC;
|
|
return [code, order];
|
|
};
|
|
|
|
/**
|
|
* Regular expression to detect a single-quoted string literal.
|
|
*/
|
|
const strRegExp = /^\s*'([^']|\\')*'\s*$/;
|
|
|
|
/**
|
|
* Enclose the provided value in 'str(...)' function.
|
|
* Leave string literals alone.
|
|
* @param {string} value Code evaluating to a value.
|
|
* @return {Array<string|number>} Array containing code evaluating to a string
|
|
* and
|
|
* the order of the returned code.[string, number]
|
|
*/
|
|
const forceString = function(value) {
|
|
if (strRegExp.test(value)) {
|
|
return [value, Python.ORDER_ATOMIC];
|
|
}
|
|
return ['str(' + value + ')', Python.ORDER_FUNCTION_CALL];
|
|
};
|
|
|
|
Python['text_join'] = function(block) {
|
|
// 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_) {
|
|
case 0:
|
|
return ["''", Python.ORDER_ATOMIC];
|
|
case 1: {
|
|
const element =
|
|
Python.valueToCode(block, 'ADD0', Python.ORDER_NONE) || "''";
|
|
const codeAndOrder = forceString(element);
|
|
return codeAndOrder;
|
|
}
|
|
case 2: {
|
|
const element0 =
|
|
Python.valueToCode(block, 'ADD0', Python.ORDER_NONE) || "''";
|
|
const element1 =
|
|
Python.valueToCode(block, 'ADD1', Python.ORDER_NONE) || "''";
|
|
const code = forceString(element0)[0] + ' + ' + forceString(element1)[0];
|
|
return [code, Python.ORDER_ADDITIVE];
|
|
}
|
|
default: {
|
|
const elements = [];
|
|
for (let i = 0; i < block.itemCount_; i++) {
|
|
elements[i] =
|
|
Python.valueToCode(block, 'ADD' + i, Python.ORDER_NONE) || "''";
|
|
}
|
|
const tempVar = Python.nameDB_.getDistinctName('x', NameType.VARIABLE);
|
|
const code = '\'\'.join([str(' + tempVar + ') for ' + tempVar + ' in [' +
|
|
elements.join(', ') + ']])';
|
|
return [code, Python.ORDER_FUNCTION_CALL];
|
|
}
|
|
}
|
|
};
|
|
|
|
Python['text_append'] = function(block) {
|
|
// Append to a variable in place.
|
|
const varName =
|
|
Python.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
|
|
const value = Python.valueToCode(block, 'TEXT', Python.ORDER_NONE) || "''";
|
|
return varName + ' = str(' + varName + ') + ' + forceString(value)[0] + '\n';
|
|
};
|
|
|
|
Python['text_length'] = function(block) {
|
|
// Is the string null or array empty?
|
|
const text = Python.valueToCode(block, 'VALUE', Python.ORDER_NONE) || "''";
|
|
return ['len(' + text + ')', Python.ORDER_FUNCTION_CALL];
|
|
};
|
|
|
|
Python['text_isEmpty'] = function(block) {
|
|
// Is the string null or array empty?
|
|
const text = Python.valueToCode(block, 'VALUE', Python.ORDER_NONE) || "''";
|
|
const code = 'not len(' + text + ')';
|
|
return [code, Python.ORDER_LOGICAL_NOT];
|
|
};
|
|
|
|
Python['text_indexOf'] = function(block) {
|
|
// Search the text for a substring.
|
|
// Should we allow for non-case sensitive???
|
|
const operator = block.getFieldValue('END') === 'FIRST' ? 'find' : 'rfind';
|
|
const substring =
|
|
Python.valueToCode(block, 'FIND', Python.ORDER_NONE) || "''";
|
|
const text =
|
|
Python.valueToCode(block, 'VALUE', Python.ORDER_MEMBER) || "''";
|
|
const code = text + '.' + operator + '(' + substring + ')';
|
|
if (block.workspace.options.oneBasedIndex) {
|
|
return [code + ' + 1', Python.ORDER_ADDITIVE];
|
|
}
|
|
return [code, Python.ORDER_FUNCTION_CALL];
|
|
};
|
|
|
|
Python['text_charAt'] = function(block) {
|
|
// 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') ? Python.ORDER_NONE : Python.ORDER_MEMBER;
|
|
const text = Python.valueToCode(block, 'VALUE', textOrder) || "''";
|
|
switch (where) {
|
|
case 'FIRST': {
|
|
const code = text + '[0]';
|
|
return [code, Python.ORDER_MEMBER];
|
|
}
|
|
case 'LAST': {
|
|
const code = text + '[-1]';
|
|
return [code, Python.ORDER_MEMBER];
|
|
}
|
|
case 'FROM_START': {
|
|
const at = Python.getAdjustedInt(block, 'AT');
|
|
const code = text + '[' + at + ']';
|
|
return [code, Python.ORDER_MEMBER];
|
|
}
|
|
case 'FROM_END': {
|
|
const at = Python.getAdjustedInt(block, 'AT', 1, true);
|
|
const code = text + '[' + at + ']';
|
|
return [code, Python.ORDER_MEMBER];
|
|
}
|
|
case 'RANDOM': {
|
|
Python.definitions_['import_random'] = 'import random';
|
|
const functionName = Python.provideFunction_('text_random_letter', `
|
|
def ${Python.FUNCTION_NAME_PLACEHOLDER_}(text):
|
|
x = int(random.random() * len(text))
|
|
return text[x]
|
|
`);
|
|
const code = functionName + '(' + text + ')';
|
|
return [code, Python.ORDER_FUNCTION_CALL];
|
|
}
|
|
}
|
|
throw Error('Unhandled option (text_charAt).');
|
|
};
|
|
|
|
Python['text_getSubstring'] = function(block) {
|
|
// Get substring.
|
|
const where1 = block.getFieldValue('WHERE1');
|
|
const where2 = block.getFieldValue('WHERE2');
|
|
const text =
|
|
Python.valueToCode(block, 'STRING', Python.ORDER_MEMBER) || "''";
|
|
let at1;
|
|
switch (where1) {
|
|
case 'FROM_START':
|
|
at1 = Python.getAdjustedInt(block, 'AT1');
|
|
if (at1 === 0) {
|
|
at1 = '';
|
|
}
|
|
break;
|
|
case 'FROM_END':
|
|
at1 = Python.getAdjustedInt(block, 'AT1', 1, true);
|
|
break;
|
|
case 'FIRST':
|
|
at1 = '';
|
|
break;
|
|
default:
|
|
throw Error('Unhandled option (text_getSubstring)');
|
|
}
|
|
|
|
let at2;
|
|
switch (where2) {
|
|
case 'FROM_START':
|
|
at2 = Python.getAdjustedInt(block, 'AT2', 1);
|
|
break;
|
|
case 'FROM_END':
|
|
at2 = Python.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))) {
|
|
Python.definitions_['import_sys'] = 'import sys';
|
|
at2 += ' or sys.maxsize';
|
|
} else if (at2 === 0) {
|
|
at2 = '';
|
|
}
|
|
break;
|
|
case 'LAST':
|
|
at2 = '';
|
|
break;
|
|
default:
|
|
throw Error('Unhandled option (text_getSubstring)');
|
|
}
|
|
const code = text + '[' + at1 + ' : ' + at2 + ']';
|
|
return [code, Python.ORDER_MEMBER];
|
|
};
|
|
|
|
Python['text_changeCase'] = function(block) {
|
|
// Change capitalization.
|
|
const OPERATORS = {
|
|
'UPPERCASE': '.upper()',
|
|
'LOWERCASE': '.lower()',
|
|
'TITLECASE': '.title()'
|
|
};
|
|
const operator = OPERATORS[block.getFieldValue('CASE')];
|
|
const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || "''";
|
|
const code = text + operator;
|
|
return [code, Python.ORDER_FUNCTION_CALL];
|
|
};
|
|
|
|
Python['text_trim'] = function(block) {
|
|
// Trim spaces.
|
|
const OPERATORS = {
|
|
'LEFT': '.lstrip()',
|
|
'RIGHT': '.rstrip()',
|
|
'BOTH': '.strip()'
|
|
};
|
|
const operator = OPERATORS[block.getFieldValue('MODE')];
|
|
const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || "''";
|
|
const code = text + operator;
|
|
return [code, Python.ORDER_FUNCTION_CALL];
|
|
};
|
|
|
|
Python['text_print'] = function(block) {
|
|
// Print statement.
|
|
const msg = Python.valueToCode(block, 'TEXT', Python.ORDER_NONE) || "''";
|
|
return 'print(' + msg + ')\n';
|
|
};
|
|
|
|
Python['text_prompt_ext'] = function(block) {
|
|
// Prompt function.
|
|
const functionName = Python.provideFunction_('text_prompt', `
|
|
def ${Python.FUNCTION_NAME_PLACEHOLDER_}(msg):
|
|
try:
|
|
return raw_input(msg)
|
|
except NameError:
|
|
return input(msg)
|
|
`);
|
|
let msg;
|
|
if (block.getField('TEXT')) {
|
|
// Internal message.
|
|
msg = Python.quote_(block.getFieldValue('TEXT'));
|
|
} else {
|
|
// External message.
|
|
msg = Python.valueToCode(block, 'TEXT', Python.ORDER_NONE) || "''";
|
|
}
|
|
let code = functionName + '(' + msg + ')';
|
|
const toNumber = block.getFieldValue('TYPE') === 'NUMBER';
|
|
if (toNumber) {
|
|
code = 'float(' + code + ')';
|
|
}
|
|
return [code, Python.ORDER_FUNCTION_CALL];
|
|
};
|
|
|
|
Python['text_prompt'] = Python['text_prompt_ext'];
|
|
|
|
Python['text_count'] = function(block) {
|
|
const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || "''";
|
|
const sub = Python.valueToCode(block, 'SUB', Python.ORDER_NONE) || "''";
|
|
const code = text + '.count(' + sub + ')';
|
|
return [code, Python.ORDER_FUNCTION_CALL];
|
|
};
|
|
|
|
Python['text_replace'] = function(block) {
|
|
const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || "''";
|
|
const from = Python.valueToCode(block, 'FROM', Python.ORDER_NONE) || "''";
|
|
const to = Python.valueToCode(block, 'TO', Python.ORDER_NONE) || "''";
|
|
const code = text + '.replace(' + from + ', ' + to + ')';
|
|
return [code, Python.ORDER_MEMBER];
|
|
};
|
|
|
|
Python['text_reverse'] = function(block) {
|
|
const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || "''";
|
|
const code = text + '[::-1]';
|
|
return [code, Python.ORDER_MEMBER];
|
|
};
|