Files
blockly/generators/python/text.js
Rachel Fenichel 4db047ff32 chore: fix missing requires in generators (#5744)
* chore: fix some missing requires in generators

* chore: fix missing requires in dart block generators

* chore: replace Blockly.isNumber with Blockly.utils.string.isNumber in generators

* chore: fix more missing requires in block generators
2021-11-30 08:51:21 -08:00

310 lines
10 KiB
JavaScript

/**
* @license
* Copyright 2012 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Generating Python for text blocks.
* @suppress {missingRequire}
*/
'use strict';
goog.provide('Blockly.Python.texts');
goog.require('Blockly.Python');
goog.require('Blockly.utils.string');
Blockly.Python['text'] = function(block) {
// Text value.
const code = Blockly.Python.quote_(block.getFieldValue('TEXT'));
return [code, Blockly.Python.ORDER_ATOMIC];
};
Blockly.Python['text_multiline'] = function(block) {
// Text value.
const code = Blockly.Python.multiline_quote_(block.getFieldValue('TEXT'));
const order = code.indexOf('+') !== -1 ? Blockly.Python.ORDER_ADDITIVE :
Blockly.Python.ORDER_ATOMIC;
return [code, order];
};
/**
* 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]
* @private
*/
Blockly.Python.text.forceString_ = function(value) {
if (Blockly.Python.text.forceString_.strRegExp.test(value)) {
return [value, Blockly.Python.ORDER_ATOMIC];
}
return ['str(' + value + ')', Blockly.Python.ORDER_FUNCTION_CALL];
};
/**
* Regular expression to detect a single-quoted string literal.
*/
Blockly.Python.text.forceString_.strRegExp = /^\s*'([^']|\\')*'\s*$/;
Blockly.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 ['\'\'', Blockly.Python.ORDER_ATOMIC];
case 1: {
const element = Blockly.Python.valueToCode(block, 'ADD0',
Blockly.Python.ORDER_NONE) || '\'\'';
const codeAndOrder = Blockly.Python.text.forceString_(element);
return codeAndOrder;
}
case 2: {
const element0 = Blockly.Python.valueToCode(
block, 'ADD0', Blockly.Python.ORDER_NONE) ||
'\'\'';
const element1 = Blockly.Python.valueToCode(
block, 'ADD1', Blockly.Python.ORDER_NONE) ||
'\'\'';
const code = Blockly.Python.text.forceString_(element0)[0] + ' + ' +
Blockly.Python.text.forceString_(element1)[0];
return [code, Blockly.Python.ORDER_ADDITIVE];
}
default: {
const elements = [];
for (let i = 0; i < block.itemCount_; i++) {
elements[i] = Blockly.Python.valueToCode(block, 'ADD' + i,
Blockly.Python.ORDER_NONE) || '\'\'';
}
const tempVar = Blockly.Python.nameDB_.getDistinctName(
'x', Blockly.VARIABLE_CATEGORY_NAME);
const code = '\'\'.join([str(' + tempVar + ') for ' + tempVar + ' in [' +
elements.join(', ') + ']])';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
}
}
};
Blockly.Python['text_append'] = function(block) {
// Append to a variable in place.
const varName = Blockly.Python.nameDB_.getName(block.getFieldValue('VAR'),
Blockly.VARIABLE_CATEGORY_NAME);
const value = Blockly.Python.valueToCode(block, 'TEXT',
Blockly.Python.ORDER_NONE) || '\'\'';
return varName + ' = str(' + varName + ') + ' +
Blockly.Python.text.forceString_(value)[0] + '\n';
};
Blockly.Python['text_length'] = function(block) {
// Is the string null or array empty?
const text = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_NONE) || '\'\'';
return ['len(' + text + ')', Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['text_isEmpty'] = function(block) {
// Is the string null or array empty?
const text = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_NONE) || '\'\'';
const code = 'not len(' + text + ')';
return [code, Blockly.Python.ORDER_LOGICAL_NOT];
};
Blockly.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 = Blockly.Python.valueToCode(block, 'FIND',
Blockly.Python.ORDER_NONE) || '\'\'';
const text = Blockly.Python.valueToCode(block, 'VALUE',
Blockly.Python.ORDER_MEMBER) || '\'\'';
const code = text + '.' + operator + '(' + substring + ')';
if (block.workspace.options.oneBasedIndex) {
return [code + ' + 1', Blockly.Python.ORDER_ADDITIVE];
}
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.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') ? Blockly.Python.ORDER_NONE :
Blockly.Python.ORDER_MEMBER;
const text = Blockly.Python.valueToCode(block, 'VALUE', textOrder) || '\'\'';
switch (where) {
case 'FIRST': {
const code = text + '[0]';
return [code, Blockly.Python.ORDER_MEMBER];
}
case 'LAST': {
const code = text + '[-1]';
return [code, Blockly.Python.ORDER_MEMBER];
}
case 'FROM_START': {
const at = Blockly.Python.getAdjustedInt(block, 'AT');
const code = text + '[' + at + ']';
return [code, Blockly.Python.ORDER_MEMBER];
}
case 'FROM_END': {
const at = Blockly.Python.getAdjustedInt(block, 'AT', 1, true);
const code = text + '[' + at + ']';
return [code, Blockly.Python.ORDER_MEMBER];
}
case 'RANDOM': {
Blockly.Python.definitions_['import_random'] = 'import random';
const functionName =
Blockly.Python.provideFunction_('text_random_letter', [
'def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(text):',
' x = int(random.random() * len(text))', ' return text[x];'
]);
const code = functionName + '(' + text + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
}
}
throw Error('Unhandled option (text_charAt).');
};
Blockly.Python['text_getSubstring'] = function(block) {
// Get substring.
const where1 = block.getFieldValue('WHERE1');
const where2 = block.getFieldValue('WHERE2');
const text = Blockly.Python.valueToCode(block, 'STRING',
Blockly.Python.ORDER_MEMBER) || '\'\'';
let at1;
switch (where1) {
case 'FROM_START':
at1 = Blockly.Python.getAdjustedInt(block, 'AT1');
if (at1 === 0) {
at1 = '';
}
break;
case 'FROM_END':
at1 = Blockly.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 = Blockly.Python.getAdjustedInt(block, 'AT2', 1);
break;
case 'FROM_END':
at2 = Blockly.Python.getAdjustedInt(block, 'AT2', 0, true);
// Ensure that if the result calculated is 0 that sub-sequence will
// include all elements as expected.
if (!Blockly.utils.string.isNumber(String(at2))) {
Blockly.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, Blockly.Python.ORDER_MEMBER];
};
Blockly.Python['text_changeCase'] = function(block) {
// Change capitalization.
const OPERATORS = {
'UPPERCASE': '.upper()',
'LOWERCASE': '.lower()',
'TITLECASE': '.title()'
};
const operator = OPERATORS[block.getFieldValue('CASE')];
const text = Blockly.Python.valueToCode(block, 'TEXT',
Blockly.Python.ORDER_MEMBER) || '\'\'';
const code = text + operator;
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['text_trim'] = function(block) {
// Trim spaces.
const OPERATORS = {
'LEFT': '.lstrip()',
'RIGHT': '.rstrip()',
'BOTH': '.strip()'
};
const operator = OPERATORS[block.getFieldValue('MODE')];
const text = Blockly.Python.valueToCode(block, 'TEXT',
Blockly.Python.ORDER_MEMBER) || '\'\'';
const code = text + operator;
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['text_print'] = function(block) {
// Print statement.
const msg = Blockly.Python.valueToCode(block, 'TEXT',
Blockly.Python.ORDER_NONE) || '\'\'';
return 'print(' + msg + ')\n';
};
Blockly.Python['text_prompt_ext'] = function(block) {
// Prompt function.
const functionName = Blockly.Python.provideFunction_(
'text_prompt',
['def ' + Blockly.Python.FUNCTION_NAME_PLACEHOLDER_ + '(msg):',
' try:',
' return raw_input(msg)',
' except NameError:',
' return input(msg)']);
let msg;
if (block.getField('TEXT')) {
// Internal message.
msg = Blockly.Python.quote_(block.getFieldValue('TEXT'));
} else {
// External message.
msg = Blockly.Python.valueToCode(block, 'TEXT',
Blockly.Python.ORDER_NONE) || '\'\'';
}
let code = functionName + '(' + msg + ')';
const toNumber = block.getFieldValue('TYPE') === 'NUMBER';
if (toNumber) {
code = 'float(' + code + ')';
}
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['text_prompt'] = Blockly.Python['text_prompt_ext'];
Blockly.Python['text_count'] = function(block) {
const text = Blockly.Python.valueToCode(block, 'TEXT',
Blockly.Python.ORDER_MEMBER) || '\'\'';
const sub = Blockly.Python.valueToCode(block, 'SUB',
Blockly.Python.ORDER_NONE) || '\'\'';
const code = text + '.count(' + sub + ')';
return [code, Blockly.Python.ORDER_FUNCTION_CALL];
};
Blockly.Python['text_replace'] = function(block) {
const text = Blockly.Python.valueToCode(block, 'TEXT',
Blockly.Python.ORDER_MEMBER) || '\'\'';
const from = Blockly.Python.valueToCode(block, 'FROM',
Blockly.Python.ORDER_NONE) || '\'\'';
const to = Blockly.Python.valueToCode(block, 'TO',
Blockly.Python.ORDER_NONE) || '\'\'';
const code = text + '.replace(' + from + ', ' + to + ')';
return [code, Blockly.Python.ORDER_MEMBER];
};
Blockly.Python['text_reverse'] = function(block) {
const text = Blockly.Python.valueToCode(block, 'TEXT',
Blockly.Python.ORDER_MEMBER) || '\'\'';
const code = text + '[::-1]';
return [code, Blockly.Python.ORDER_MEMBER];
};