mirror of
https://github.com/google/blockly.git
synced 2026-01-04 15:40:08 +01:00
refactor(generators): Introduce PythonGenerator class, Order enum (#7163)
* refactor(generators): Introduce PhpGenerator class, Order enum * refactor(generators): Use Order.* instead of .ORDER_* * refactor(generators): Don't rename pythonGenerator
This commit is contained in:
committed by
GitHub
parent
26901654ea
commit
2f89c0dd09
@@ -16,317 +16,333 @@ 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 {inputTypes} from '../core/inputs/input_types.js';
|
||||
import {Names, NameType} from '../core/names.js';
|
||||
// import type {Workspace} from '../core/workspace.js';
|
||||
import {inputTypes} from '../core/inputs/input_types.js';
|
||||
|
||||
|
||||
/**
|
||||
* Python code generator.
|
||||
* @type {!CodeGenerator}
|
||||
*/
|
||||
const Python = new CodeGenerator('Python');
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
Python.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');
|
||||
|
||||
/**
|
||||
* Order of operation ENUMs.
|
||||
* http://docs.python.org/reference/expressions.html#summary
|
||||
* @enum {number}
|
||||
*/
|
||||
Python.ORDER_ATOMIC = 0; // 0 "" ...
|
||||
Python.ORDER_COLLECTION = 1; // tuples, lists, dictionaries
|
||||
Python.ORDER_STRING_CONVERSION = 1; // `expression...`
|
||||
Python.ORDER_MEMBER = 2.1; // . []
|
||||
Python.ORDER_FUNCTION_CALL = 2.2; // ()
|
||||
Python.ORDER_EXPONENTIATION = 3; // **
|
||||
Python.ORDER_UNARY_SIGN = 4; // + -
|
||||
Python.ORDER_BITWISE_NOT = 4; // ~
|
||||
Python.ORDER_MULTIPLICATIVE = 5; // * / // %
|
||||
Python.ORDER_ADDITIVE = 6; // + -
|
||||
Python.ORDER_BITWISE_SHIFT = 7; // << >>
|
||||
Python.ORDER_BITWISE_AND = 8; // &
|
||||
Python.ORDER_BITWISE_XOR = 9; // ^
|
||||
Python.ORDER_BITWISE_OR = 10; // |
|
||||
Python.ORDER_RELATIONAL = 11; // in, not in, is, is not,
|
||||
// <, <=, >, >=, <>, !=, ==
|
||||
Python.ORDER_LOGICAL_NOT = 12; // not
|
||||
Python.ORDER_LOGICAL_AND = 13; // and
|
||||
Python.ORDER_LOGICAL_OR = 14; // or
|
||||
Python.ORDER_CONDITIONAL = 15; // if else
|
||||
Python.ORDER_LAMBDA = 16; // lambda
|
||||
Python.ORDER_NONE = 99; // (...)
|
||||
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, // (...)
|
||||
};
|
||||
|
||||
/**
|
||||
* List of outer-inner pairings that do NOT require parentheses.
|
||||
* @type {!Array<!Array<number>>}
|
||||
* PythonScript code generator class.
|
||||
*/
|
||||
Python.ORDER_OVERRIDES = [
|
||||
// (foo()).bar -> foo().bar
|
||||
// (foo())[0] -> foo()[0]
|
||||
[Python.ORDER_FUNCTION_CALL, Python.ORDER_MEMBER],
|
||||
// (foo())() -> foo()()
|
||||
[Python.ORDER_FUNCTION_CALL, Python.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]
|
||||
[Python.ORDER_MEMBER, Python.ORDER_MEMBER],
|
||||
// (foo.bar)() -> foo.bar()
|
||||
// (foo[0])() -> foo[0]()
|
||||
[Python.ORDER_MEMBER, Python.ORDER_FUNCTION_CALL],
|
||||
|
||||
// not (not foo) -> not not foo
|
||||
[Python.ORDER_LOGICAL_NOT, Python.ORDER_LOGICAL_NOT],
|
||||
// a and (b and c) -> a and b and c
|
||||
[Python.ORDER_LOGICAL_AND, Python.ORDER_LOGICAL_AND],
|
||||
// a or (b or c) -> a or b or c
|
||||
[Python.ORDER_LOGICAL_OR, Python.ORDER_LOGICAL_OR]
|
||||
];
|
||||
|
||||
/**
|
||||
* Whether the init method has been called.
|
||||
* @type {?boolean}
|
||||
*/
|
||||
Python.isInitialized = false;
|
||||
|
||||
/**
|
||||
* Initialise the database of variable names.
|
||||
* @param {!Workspace} workspace Workspace to generate code from.
|
||||
* @this {CodeGenerator}
|
||||
*/
|
||||
Python.init = function(workspace) {
|
||||
// Call Blockly.CodeGenerator's init.
|
||||
Object.getPrototypeOf(this).init.call(this);
|
||||
|
||||
export class PythonGenerator extends CodeGenerator {
|
||||
/**
|
||||
* Empty loops or conditionals are not allowed in Python.
|
||||
* List of outer-inner pairings that do NOT require parentheses.
|
||||
* @type {!Array<!Array<number>>}
|
||||
*/
|
||||
this.PASS = this.INDENT + 'pass\n';
|
||||
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;
|
||||
|
||||
if (!this.nameDB_) {
|
||||
this.nameDB_ = new Names(this.RESERVED_WORDS_);
|
||||
} else {
|
||||
// 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;
|
||||
}
|
||||
|
||||
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');
|
||||
|
||||
/**
|
||||
* 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';
|
||||
}
|
||||
|
||||
// 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.
|
||||
*/
|
||||
Python.finish = function(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);
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
// Can't use goog.string.quote since % must also be escaped.
|
||||
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;
|
||||
}
|
||||
// Call Blockly.CodeGenerator's finish.
|
||||
code = Object.getPrototypeOf(this).finish.call(this, 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.
|
||||
*/
|
||||
Python.scrubNakedValue = function(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
|
||||
*/
|
||||
Python.quote_ = function(string) {
|
||||
// Can't use goog.string.quote since % must also be escaped.
|
||||
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, '\\\'');
|
||||
}
|
||||
|
||||
/**
|
||||
* 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');
|
||||
}
|
||||
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
|
||||
*/
|
||||
Python.multiline_quote_ = function(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
|
||||
*/
|
||||
Python.scrub_ = function(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, '# ');
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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}
|
||||
* Python code generator.
|
||||
* @type {!PythonGenerator}
|
||||
*/
|
||||
Python.getAdjustedInt = function(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;
|
||||
};
|
||||
export {Python as pythonGenerator};
|
||||
export const pythonGenerator = new PythonGenerator();
|
||||
|
||||
|
||||
@@ -11,42 +11,42 @@
|
||||
import * as goog from '../../closure/goog/goog.js';
|
||||
goog.declareModuleId('Blockly.Python.colour');
|
||||
|
||||
import {pythonGenerator as Python} from '../python.js';
|
||||
import {pythonGenerator, Order} from '../python.js';
|
||||
|
||||
|
||||
Python.forBlock['colour_picker'] = function(block) {
|
||||
pythonGenerator.forBlock['colour_picker'] = function(block) {
|
||||
// Colour picker.
|
||||
const code = Python.quote_(block.getFieldValue('COLOUR'));
|
||||
return [code, Python.ORDER_ATOMIC];
|
||||
const code = pythonGenerator.quote_(block.getFieldValue('COLOUR'));
|
||||
return [code, Order.ATOMIC];
|
||||
};
|
||||
|
||||
Python.forBlock['colour_random'] = function(block) {
|
||||
pythonGenerator.forBlock['colour_random'] = function(block) {
|
||||
// Generate a random colour.
|
||||
Python.definitions_['import_random'] = 'import random';
|
||||
pythonGenerator.definitions_['import_random'] = 'import random';
|
||||
const code = '\'#%06x\' % random.randint(0, 2**24 - 1)';
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['colour_rgb'] = function(block) {
|
||||
pythonGenerator.forBlock['colour_rgb'] = function(block) {
|
||||
// Compose a colour from RGB components expressed as percentages.
|
||||
const functionName = Python.provideFunction_('colour_rgb', `
|
||||
def ${Python.FUNCTION_NAME_PLACEHOLDER_}(r, g, b):
|
||||
const functionName = pythonGenerator.provideFunction_('colour_rgb', `
|
||||
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(r, g, b):
|
||||
r = round(min(100, max(0, r)) * 2.55)
|
||||
g = round(min(100, max(0, g)) * 2.55)
|
||||
b = round(min(100, max(0, b)) * 2.55)
|
||||
return '#%02x%02x%02x' % (r, g, b)
|
||||
`);
|
||||
const r = Python.valueToCode(block, 'RED', Python.ORDER_NONE) || 0;
|
||||
const g = Python.valueToCode(block, 'GREEN', Python.ORDER_NONE) || 0;
|
||||
const b = Python.valueToCode(block, 'BLUE', Python.ORDER_NONE) || 0;
|
||||
const r = pythonGenerator.valueToCode(block, 'RED', Order.NONE) || 0;
|
||||
const g = pythonGenerator.valueToCode(block, 'GREEN', Order.NONE) || 0;
|
||||
const b = pythonGenerator.valueToCode(block, 'BLUE', Order.NONE) || 0;
|
||||
const code = functionName + '(' + r + ', ' + g + ', ' + b + ')';
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['colour_blend'] = function(block) {
|
||||
pythonGenerator.forBlock['colour_blend'] = function(block) {
|
||||
// Blend two colours together.
|
||||
const functionName = Python.provideFunction_('colour_blend', `
|
||||
def ${Python.FUNCTION_NAME_PLACEHOLDER_}(colour1, colour2, ratio):
|
||||
const functionName = pythonGenerator.provideFunction_('colour_blend', `
|
||||
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(colour1, colour2, ratio):
|
||||
r1, r2 = int(colour1[1:3], 16), int(colour2[1:3], 16)
|
||||
g1, g2 = int(colour1[3:5], 16), int(colour2[3:5], 16)
|
||||
b1, b2 = int(colour1[5:7], 16), int(colour2[5:7], 16)
|
||||
@@ -57,11 +57,13 @@ def ${Python.FUNCTION_NAME_PLACEHOLDER_}(colour1, colour2, ratio):
|
||||
return '#%02x%02x%02x' % (r, g, b)
|
||||
`);
|
||||
const colour1 =
|
||||
Python.valueToCode(block, 'COLOUR1', Python.ORDER_NONE) || '\'#000000\'';
|
||||
pythonGenerator.valueToCode(block, 'COLOUR1', Order.NONE)
|
||||
|| '\'#000000\'';
|
||||
const colour2 =
|
||||
Python.valueToCode(block, 'COLOUR2', Python.ORDER_NONE) || '\'#000000\'';
|
||||
const ratio = Python.valueToCode(block, 'RATIO', Python.ORDER_NONE) || 0;
|
||||
pythonGenerator.valueToCode(block, 'COLOUR2', Order.NONE)
|
||||
|| '\'#000000\'';
|
||||
const ratio = pythonGenerator.valueToCode(block, 'RATIO', Order.NONE) || 0;
|
||||
const code =
|
||||
functionName + '(' + colour1 + ', ' + colour2 + ', ' + ratio + ')';
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
@@ -13,51 +13,51 @@ goog.declareModuleId('Blockly.Python.lists');
|
||||
|
||||
import * as stringUtils from '../../core/utils/string.js';
|
||||
import {NameType} from '../../core/names.js';
|
||||
import {pythonGenerator as Python} from '../python.js';
|
||||
import {pythonGenerator, Order} from '../python.js';
|
||||
|
||||
|
||||
Python.forBlock['lists_create_empty'] = function(block) {
|
||||
pythonGenerator.forBlock['lists_create_empty'] = function(block) {
|
||||
// Create an empty list.
|
||||
return ['[]', Python.ORDER_ATOMIC];
|
||||
return ['[]', Order.ATOMIC];
|
||||
};
|
||||
|
||||
Python.forBlock['lists_create_with'] = function(block) {
|
||||
pythonGenerator.forBlock['lists_create_with'] = function(block) {
|
||||
// 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++) {
|
||||
elements[i] =
|
||||
Python.valueToCode(block, 'ADD' + i, Python.ORDER_NONE) || 'None';
|
||||
pythonGenerator.valueToCode(block, 'ADD' + i, Order.NONE) || 'None';
|
||||
}
|
||||
const code = '[' + elements.join(', ') + ']';
|
||||
return [code, Python.ORDER_ATOMIC];
|
||||
return [code, Order.ATOMIC];
|
||||
};
|
||||
|
||||
Python.forBlock['lists_repeat'] = function(block) {
|
||||
pythonGenerator.forBlock['lists_repeat'] = function(block) {
|
||||
// Create a list with one element repeated.
|
||||
const item = Python.valueToCode(block, 'ITEM', Python.ORDER_NONE) || 'None';
|
||||
const item = pythonGenerator.valueToCode(block, 'ITEM', Order.NONE) || 'None';
|
||||
const times =
|
||||
Python.valueToCode(block, 'NUM', Python.ORDER_MULTIPLICATIVE) || '0';
|
||||
pythonGenerator.valueToCode(block, 'NUM', Order.MULTIPLICATIVE) || '0';
|
||||
const code = '[' + item + '] * ' + times;
|
||||
return [code, Python.ORDER_MULTIPLICATIVE];
|
||||
return [code, Order.MULTIPLICATIVE];
|
||||
};
|
||||
|
||||
Python.forBlock['lists_length'] = function(block) {
|
||||
pythonGenerator.forBlock['lists_length'] = function(block) {
|
||||
// String or array length.
|
||||
const list = Python.valueToCode(block, 'VALUE', Python.ORDER_NONE) || '[]';
|
||||
return ['len(' + list + ')', Python.ORDER_FUNCTION_CALL];
|
||||
const list = pythonGenerator.valueToCode(block, 'VALUE', Order.NONE) || '[]';
|
||||
return ['len(' + list + ')', Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['lists_isEmpty'] = function(block) {
|
||||
pythonGenerator.forBlock['lists_isEmpty'] = function(block) {
|
||||
// Is the string null or array empty?
|
||||
const list = Python.valueToCode(block, 'VALUE', Python.ORDER_NONE) || '[]';
|
||||
const list = pythonGenerator.valueToCode(block, 'VALUE', Order.NONE) || '[]';
|
||||
const code = 'not len(' + list + ')';
|
||||
return [code, Python.ORDER_LOGICAL_NOT];
|
||||
return [code, Order.LOGICAL_NOT];
|
||||
};
|
||||
|
||||
Python.forBlock['lists_indexOf'] = function(block) {
|
||||
pythonGenerator.forBlock['lists_indexOf'] = function(block) {
|
||||
// Find an item in the list.
|
||||
const item = Python.valueToCode(block, 'FIND', Python.ORDER_NONE) || '[]';
|
||||
const list = Python.valueToCode(block, 'VALUE', Python.ORDER_NONE) || "''";
|
||||
const item = pythonGenerator.valueToCode(block, 'FIND', Order.NONE) || '[]';
|
||||
const list = pythonGenerator.valueToCode(block, 'VALUE', Order.NONE) || "''";
|
||||
let errorIndex = ' -1';
|
||||
let firstIndexAdjustment = '';
|
||||
let lastIndexAdjustment = ' - 1';
|
||||
@@ -70,41 +70,41 @@ Python.forBlock['lists_indexOf'] = function(block) {
|
||||
|
||||
let functionName;
|
||||
if (block.getFieldValue('END') === 'FIRST') {
|
||||
functionName = Python.provideFunction_('first_index', `
|
||||
def ${Python.FUNCTION_NAME_PLACEHOLDER_}(my_list, elem):
|
||||
functionName = pythonGenerator.provideFunction_('first_index', `
|
||||
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(my_list, elem):
|
||||
try: index = my_list.index(elem)${firstIndexAdjustment}
|
||||
except: index =${errorIndex}
|
||||
return index
|
||||
`);
|
||||
} else {
|
||||
functionName = Python.provideFunction_('last_index', `
|
||||
def ${Python.FUNCTION_NAME_PLACEHOLDER_}(my_list, elem):
|
||||
functionName = pythonGenerator.provideFunction_('last_index', `
|
||||
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(my_list, elem):
|
||||
try: index = len(my_list) - my_list[::-1].index(elem)${lastIndexAdjustment}
|
||||
except: index =${errorIndex}
|
||||
return index
|
||||
`);
|
||||
}
|
||||
const code = functionName + '(' + list + ', ' + item + ')';
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['lists_getIndex'] = function(block) {
|
||||
pythonGenerator.forBlock['lists_getIndex'] = function(block) {
|
||||
// Get element at index.
|
||||
// Note: Until January 2013 this block did not have MODE or WHERE inputs.
|
||||
const mode = block.getFieldValue('MODE') || 'GET';
|
||||
const where = block.getFieldValue('WHERE') || 'FROM_START';
|
||||
const listOrder =
|
||||
(where === 'RANDOM') ? Python.ORDER_NONE : Python.ORDER_MEMBER;
|
||||
const list = Python.valueToCode(block, 'VALUE', listOrder) || '[]';
|
||||
(where === 'RANDOM') ? Order.NONE : Order.MEMBER;
|
||||
const list = pythonGenerator.valueToCode(block, 'VALUE', listOrder) || '[]';
|
||||
|
||||
switch (where) {
|
||||
case 'FIRST':
|
||||
if (mode === 'GET') {
|
||||
const code = list + '[0]';
|
||||
return [code, Python.ORDER_MEMBER];
|
||||
return [code, Order.MEMBER];
|
||||
} else if (mode === 'GET_REMOVE') {
|
||||
const code = list + '.pop(0)';
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
} else if (mode === 'REMOVE') {
|
||||
return list + '.pop(0)\n';
|
||||
}
|
||||
@@ -112,55 +112,55 @@ Python.forBlock['lists_getIndex'] = function(block) {
|
||||
case 'LAST':
|
||||
if (mode === 'GET') {
|
||||
const code = list + '[-1]';
|
||||
return [code, Python.ORDER_MEMBER];
|
||||
return [code, Order.MEMBER];
|
||||
} else if (mode === 'GET_REMOVE') {
|
||||
const code = list + '.pop()';
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
} else if (mode === 'REMOVE') {
|
||||
return list + '.pop()\n';
|
||||
}
|
||||
break;
|
||||
case 'FROM_START': {
|
||||
const at = Python.getAdjustedInt(block, 'AT');
|
||||
const at = pythonGenerator.getAdjustedInt(block, 'AT');
|
||||
if (mode === 'GET') {
|
||||
const code = list + '[' + at + ']';
|
||||
return [code, Python.ORDER_MEMBER];
|
||||
return [code, Order.MEMBER];
|
||||
} else if (mode === 'GET_REMOVE') {
|
||||
const code = list + '.pop(' + at + ')';
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
} else if (mode === 'REMOVE') {
|
||||
return list + '.pop(' + at + ')\n';
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'FROM_END': {
|
||||
const at = Python.getAdjustedInt(block, 'AT', 1, true);
|
||||
const at = pythonGenerator.getAdjustedInt(block, 'AT', 1, true);
|
||||
if (mode === 'GET') {
|
||||
const code = list + '[' + at + ']';
|
||||
return [code, Python.ORDER_MEMBER];
|
||||
return [code, Order.MEMBER];
|
||||
} else if (mode === 'GET_REMOVE') {
|
||||
const code = list + '.pop(' + at + ')';
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
} else if (mode === 'REMOVE') {
|
||||
return list + '.pop(' + at + ')\n';
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'RANDOM':
|
||||
Python.definitions_['import_random'] = 'import random';
|
||||
pythonGenerator.definitions_['import_random'] = 'import random';
|
||||
if (mode === 'GET') {
|
||||
const code = 'random.choice(' + list + ')';
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
} else {
|
||||
const functionName =
|
||||
Python.provideFunction_('lists_remove_random_item', `
|
||||
def ${Python.FUNCTION_NAME_PLACEHOLDER_}(myList):
|
||||
pythonGenerator.provideFunction_('lists_remove_random_item', `
|
||||
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(myList):
|
||||
x = int(random.random() * len(myList))
|
||||
return myList.pop(x)
|
||||
`);
|
||||
const code = functionName + '(' + list + ')';
|
||||
if (mode === 'GET_REMOVE') {
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
} else if (mode === 'REMOVE') {
|
||||
return code + '\n';
|
||||
}
|
||||
@@ -170,13 +170,13 @@ def ${Python.FUNCTION_NAME_PLACEHOLDER_}(myList):
|
||||
throw Error('Unhandled combination (lists_getIndex).');
|
||||
};
|
||||
|
||||
Python.forBlock['lists_setIndex'] = function(block) {
|
||||
pythonGenerator.forBlock['lists_setIndex'] = function(block) {
|
||||
// Set element at index.
|
||||
// Note: Until February 2013 this block did not have MODE or WHERE inputs.
|
||||
let list = Python.valueToCode(block, 'LIST', Python.ORDER_MEMBER) || '[]';
|
||||
let list = pythonGenerator.valueToCode(block, 'LIST', Order.MEMBER) || '[]';
|
||||
const mode = block.getFieldValue('MODE') || 'GET';
|
||||
const where = block.getFieldValue('WHERE') || 'FROM_START';
|
||||
const value = Python.valueToCode(block, 'TO', Python.ORDER_NONE) || 'None';
|
||||
const value = pythonGenerator.valueToCode(block, 'TO', Order.NONE) || 'None';
|
||||
// Cache non-trivial values to variables to prevent repeated look-ups.
|
||||
// Closure, which accesses and modifies 'list'.
|
||||
function cacheList() {
|
||||
@@ -184,7 +184,7 @@ Python.forBlock['lists_setIndex'] = function(block) {
|
||||
return '';
|
||||
}
|
||||
const listVar =
|
||||
Python.nameDB_.getDistinctName('tmp_list', NameType.VARIABLE);
|
||||
pythonGenerator.nameDB_.getDistinctName('tmp_list', NameType.VARIABLE);
|
||||
const code = listVar + ' = ' + list + '\n';
|
||||
list = listVar;
|
||||
return code;
|
||||
@@ -206,7 +206,7 @@ Python.forBlock['lists_setIndex'] = function(block) {
|
||||
}
|
||||
break;
|
||||
case 'FROM_START': {
|
||||
const at = Python.getAdjustedInt(block, 'AT');
|
||||
const at = pythonGenerator.getAdjustedInt(block, 'AT');
|
||||
if (mode === 'SET') {
|
||||
return list + '[' + at + '] = ' + value + '\n';
|
||||
} else if (mode === 'INSERT') {
|
||||
@@ -215,7 +215,7 @@ Python.forBlock['lists_setIndex'] = function(block) {
|
||||
break;
|
||||
}
|
||||
case 'FROM_END': {
|
||||
const at = Python.getAdjustedInt(block, 'AT', 1, true);
|
||||
const at = pythonGenerator.getAdjustedInt(block, 'AT', 1, true);
|
||||
if (mode === 'SET') {
|
||||
return list + '[' + at + '] = ' + value + '\n';
|
||||
} else if (mode === 'INSERT') {
|
||||
@@ -224,9 +224,10 @@ Python.forBlock['lists_setIndex'] = function(block) {
|
||||
break;
|
||||
}
|
||||
case 'RANDOM': {
|
||||
Python.definitions_['import_random'] = 'import random';
|
||||
pythonGenerator.definitions_['import_random'] = 'import random';
|
||||
let code = cacheList();
|
||||
const xVar = Python.nameDB_.getDistinctName('tmp_x', NameType.VARIABLE);
|
||||
const xVar =
|
||||
pythonGenerator.nameDB_.getDistinctName('tmp_x', NameType.VARIABLE);
|
||||
code += xVar + ' = int(random.random() * len(' + list + '))\n';
|
||||
if (mode === 'SET') {
|
||||
code += list + '[' + xVar + '] = ' + value + '\n';
|
||||
@@ -241,21 +242,21 @@ Python.forBlock['lists_setIndex'] = function(block) {
|
||||
throw Error('Unhandled combination (lists_setIndex).');
|
||||
};
|
||||
|
||||
Python.forBlock['lists_getSublist'] = function(block) {
|
||||
pythonGenerator.forBlock['lists_getSublist'] = function(block) {
|
||||
// Get sublist.
|
||||
const list = Python.valueToCode(block, 'LIST', Python.ORDER_MEMBER) || '[]';
|
||||
const list = pythonGenerator.valueToCode(block, 'LIST', Order.MEMBER) || '[]';
|
||||
const where1 = block.getFieldValue('WHERE1');
|
||||
const where2 = block.getFieldValue('WHERE2');
|
||||
let at1;
|
||||
switch (where1) {
|
||||
case 'FROM_START':
|
||||
at1 = Python.getAdjustedInt(block, 'AT1');
|
||||
at1 = pythonGenerator.getAdjustedInt(block, 'AT1');
|
||||
if (at1 === 0) {
|
||||
at1 = '';
|
||||
}
|
||||
break;
|
||||
case 'FROM_END':
|
||||
at1 = Python.getAdjustedInt(block, 'AT1', 1, true);
|
||||
at1 = pythonGenerator.getAdjustedInt(block, 'AT1', 1, true);
|
||||
break;
|
||||
case 'FIRST':
|
||||
at1 = '';
|
||||
@@ -267,14 +268,14 @@ Python.forBlock['lists_getSublist'] = function(block) {
|
||||
let at2;
|
||||
switch (where2) {
|
||||
case 'FROM_START':
|
||||
at2 = Python.getAdjustedInt(block, 'AT2', 1);
|
||||
at2 = pythonGenerator.getAdjustedInt(block, 'AT2', 1);
|
||||
break;
|
||||
case 'FROM_END':
|
||||
at2 = Python.getAdjustedInt(block, 'AT2', 0, true);
|
||||
at2 = pythonGenerator.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';
|
||||
pythonGenerator.definitions_['import_sys'] = 'import sys';
|
||||
at2 += ' or sys.maxsize';
|
||||
} else if (at2 === 0) {
|
||||
at2 = '';
|
||||
@@ -287,16 +288,16 @@ Python.forBlock['lists_getSublist'] = function(block) {
|
||||
throw Error('Unhandled option (lists_getSublist)');
|
||||
}
|
||||
const code = list + '[' + at1 + ' : ' + at2 + ']';
|
||||
return [code, Python.ORDER_MEMBER];
|
||||
return [code, Order.MEMBER];
|
||||
};
|
||||
|
||||
Python.forBlock['lists_sort'] = function(block) {
|
||||
pythonGenerator.forBlock['lists_sort'] = function(block) {
|
||||
// Block for sorting a list.
|
||||
const list = (Python.valueToCode(block, 'LIST', Python.ORDER_NONE) || '[]');
|
||||
const list = (pythonGenerator.valueToCode(block, 'LIST', Order.NONE) || '[]');
|
||||
const type = block.getFieldValue('TYPE');
|
||||
const reverse = block.getFieldValue('DIRECTION') === '1' ? 'False' : 'True';
|
||||
const sortFunctionName = Python.provideFunction_('lists_sort', `
|
||||
def ${Python.FUNCTION_NAME_PLACEHOLDER_}(my_list, type, reverse):
|
||||
const sortFunctionName = pythonGenerator.provideFunction_('lists_sort', `
|
||||
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(my_list, type, reverse):
|
||||
def try_float(s):
|
||||
try:
|
||||
return float(s)
|
||||
@@ -314,33 +315,33 @@ def ${Python.FUNCTION_NAME_PLACEHOLDER_}(my_list, type, reverse):
|
||||
|
||||
const code =
|
||||
sortFunctionName + '(' + list + ', "' + type + '", ' + reverse + ')';
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['lists_split'] = function(block) {
|
||||
pythonGenerator.forBlock['lists_split'] = function(block) {
|
||||
// Block for splitting text into a list, or joining a list into text.
|
||||
const mode = block.getFieldValue('MODE');
|
||||
let code;
|
||||
if (mode === 'SPLIT') {
|
||||
const value_input =
|
||||
Python.valueToCode(block, 'INPUT', Python.ORDER_MEMBER) || "''";
|
||||
const value_delim = Python.valueToCode(block, 'DELIM', Python.ORDER_NONE);
|
||||
pythonGenerator.valueToCode(block, 'INPUT', Order.MEMBER) || "''";
|
||||
const value_delim = pythonGenerator.valueToCode(block, 'DELIM', Order.NONE);
|
||||
code = value_input + '.split(' + value_delim + ')';
|
||||
} else if (mode === 'JOIN') {
|
||||
const value_input =
|
||||
Python.valueToCode(block, 'INPUT', Python.ORDER_NONE) || '[]';
|
||||
pythonGenerator.valueToCode(block, 'INPUT', Order.NONE) || '[]';
|
||||
const value_delim =
|
||||
Python.valueToCode(block, 'DELIM', Python.ORDER_MEMBER) || "''";
|
||||
pythonGenerator.valueToCode(block, 'DELIM', Order.MEMBER) || "''";
|
||||
code = value_delim + '.join(' + value_input + ')';
|
||||
} else {
|
||||
throw Error('Unknown mode: ' + mode);
|
||||
}
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['lists_reverse'] = function(block) {
|
||||
pythonGenerator.forBlock['lists_reverse'] = function(block) {
|
||||
// Block for reversing a list.
|
||||
const list = Python.valueToCode(block, 'LIST', Python.ORDER_NONE) || '[]';
|
||||
const list = pythonGenerator.valueToCode(block, 'LIST', Order.NONE) || '[]';
|
||||
const code = 'list(reversed(' + list + '))';
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
@@ -11,37 +11,43 @@
|
||||
import * as goog from '../../closure/goog/goog.js';
|
||||
goog.declareModuleId('Blockly.Python.logic');
|
||||
|
||||
import {pythonGenerator as Python} from '../python.js';
|
||||
import {pythonGenerator, Order} from '../python.js';
|
||||
|
||||
|
||||
Python.forBlock['controls_if'] = function(block) {
|
||||
pythonGenerator.forBlock['controls_if'] = function(block) {
|
||||
// If/elseif/else condition.
|
||||
let n = 0;
|
||||
let code = '', branchCode, conditionCode;
|
||||
if (Python.STATEMENT_PREFIX) {
|
||||
if (pythonGenerator.STATEMENT_PREFIX) {
|
||||
// Automatic prefix insertion is switched off for this block. Add manually.
|
||||
code += Python.injectId(Python.STATEMENT_PREFIX, block);
|
||||
code += pythonGenerator.injectId(pythonGenerator.STATEMENT_PREFIX, block);
|
||||
}
|
||||
do {
|
||||
conditionCode =
|
||||
Python.valueToCode(block, 'IF' + n, Python.ORDER_NONE) || 'False';
|
||||
branchCode = Python.statementToCode(block, 'DO' + n) || Python.PASS;
|
||||
if (Python.STATEMENT_SUFFIX) {
|
||||
pythonGenerator.valueToCode(block, 'IF' + n, Order.NONE) || 'False';
|
||||
branchCode =
|
||||
pythonGenerator.statementToCode(block, 'DO' + n) ||
|
||||
pythonGenerator.PASS;
|
||||
if (pythonGenerator.STATEMENT_SUFFIX) {
|
||||
branchCode =
|
||||
Python.prefixLines(
|
||||
Python.injectId(Python.STATEMENT_SUFFIX, block), Python.INDENT) +
|
||||
pythonGenerator.prefixLines(
|
||||
pythonGenerator.injectId(pythonGenerator.STATEMENT_SUFFIX, block),
|
||||
pythonGenerator.INDENT) +
|
||||
branchCode;
|
||||
}
|
||||
code += (n === 0 ? 'if ' : 'elif ') + conditionCode + ':\n' + branchCode;
|
||||
n++;
|
||||
} while (block.getInput('IF' + n));
|
||||
|
||||
if (block.getInput('ELSE') || Python.STATEMENT_SUFFIX) {
|
||||
branchCode = Python.statementToCode(block, 'ELSE') || Python.PASS;
|
||||
if (Python.STATEMENT_SUFFIX) {
|
||||
if (block.getInput('ELSE') || pythonGenerator.STATEMENT_SUFFIX) {
|
||||
branchCode =
|
||||
pythonGenerator.statementToCode(block, 'ELSE') || pythonGenerator.PASS;
|
||||
if (pythonGenerator.STATEMENT_SUFFIX) {
|
||||
branchCode =
|
||||
Python.prefixLines(
|
||||
Python.injectId(Python.STATEMENT_SUFFIX, block), Python.INDENT) +
|
||||
pythonGenerator.prefixLines(
|
||||
pythonGenerator.injectId(
|
||||
pythonGenerator.STATEMENT_SUFFIX, block),
|
||||
pythonGenerator.INDENT) +
|
||||
branchCode;
|
||||
}
|
||||
code += 'else:\n' + branchCode;
|
||||
@@ -49,27 +55,28 @@ Python.forBlock['controls_if'] = function(block) {
|
||||
return code;
|
||||
};
|
||||
|
||||
Python.forBlock['controls_ifelse'] = Python.forBlock['controls_if'];
|
||||
pythonGenerator.forBlock['controls_ifelse'] =
|
||||
pythonGenerator.forBlock['controls_if'];
|
||||
|
||||
Python.forBlock['logic_compare'] = function(block) {
|
||||
pythonGenerator.forBlock['logic_compare'] = function(block) {
|
||||
// Comparison operator.
|
||||
const OPERATORS =
|
||||
{'EQ': '==', 'NEQ': '!=', 'LT': '<', 'LTE': '<=', 'GT': '>', 'GTE': '>='};
|
||||
const operator = OPERATORS[block.getFieldValue('OP')];
|
||||
const order = Python.ORDER_RELATIONAL;
|
||||
const argument0 = Python.valueToCode(block, 'A', order) || '0';
|
||||
const argument1 = Python.valueToCode(block, 'B', order) || '0';
|
||||
const order = Order.RELATIONAL;
|
||||
const argument0 = pythonGenerator.valueToCode(block, 'A', order) || '0';
|
||||
const argument1 = pythonGenerator.valueToCode(block, 'B', order) || '0';
|
||||
const code = argument0 + ' ' + operator + ' ' + argument1;
|
||||
return [code, order];
|
||||
};
|
||||
|
||||
Python.forBlock['logic_operation'] = function(block) {
|
||||
pythonGenerator.forBlock['logic_operation'] = function(block) {
|
||||
// Operations 'and', 'or'.
|
||||
const operator = (block.getFieldValue('OP') === 'AND') ? 'and' : 'or';
|
||||
const order =
|
||||
(operator === 'and') ? Python.ORDER_LOGICAL_AND : Python.ORDER_LOGICAL_OR;
|
||||
let argument0 = Python.valueToCode(block, 'A', order);
|
||||
let argument1 = Python.valueToCode(block, 'B', order);
|
||||
(operator === 'and') ? Order.LOGICAL_AND : Order.LOGICAL_OR;
|
||||
let argument0 = pythonGenerator.valueToCode(block, 'A', order);
|
||||
let argument1 = pythonGenerator.valueToCode(block, 'B', order);
|
||||
if (!argument0 && !argument1) {
|
||||
// If there are no arguments, then the return value is false.
|
||||
argument0 = 'False';
|
||||
@@ -88,33 +95,33 @@ Python.forBlock['logic_operation'] = function(block) {
|
||||
return [code, order];
|
||||
};
|
||||
|
||||
Python.forBlock['logic_negate'] = function(block) {
|
||||
pythonGenerator.forBlock['logic_negate'] = function(block) {
|
||||
// Negation.
|
||||
const argument0 =
|
||||
Python.valueToCode(block, 'BOOL', Python.ORDER_LOGICAL_NOT) || 'True';
|
||||
pythonGenerator.valueToCode(block, 'BOOL', Order.LOGICAL_NOT) || 'True';
|
||||
const code = 'not ' + argument0;
|
||||
return [code, Python.ORDER_LOGICAL_NOT];
|
||||
return [code, Order.LOGICAL_NOT];
|
||||
};
|
||||
|
||||
Python.forBlock['logic_boolean'] = function(block) {
|
||||
pythonGenerator.forBlock['logic_boolean'] = function(block) {
|
||||
// Boolean values true and false.
|
||||
const code = (block.getFieldValue('BOOL') === 'TRUE') ? 'True' : 'False';
|
||||
return [code, Python.ORDER_ATOMIC];
|
||||
return [code, Order.ATOMIC];
|
||||
};
|
||||
|
||||
Python.forBlock['logic_null'] = function(block) {
|
||||
pythonGenerator.forBlock['logic_null'] = function(block) {
|
||||
// Null data type.
|
||||
return ['None', Python.ORDER_ATOMIC];
|
||||
return ['None', Order.ATOMIC];
|
||||
};
|
||||
|
||||
Python.forBlock['logic_ternary'] = function(block) {
|
||||
pythonGenerator.forBlock['logic_ternary'] = function(block) {
|
||||
// Ternary operator.
|
||||
const value_if =
|
||||
Python.valueToCode(block, 'IF', Python.ORDER_CONDITIONAL) || 'False';
|
||||
pythonGenerator.valueToCode(block, 'IF', Order.CONDITIONAL) || 'False';
|
||||
const value_then =
|
||||
Python.valueToCode(block, 'THEN', Python.ORDER_CONDITIONAL) || 'None';
|
||||
pythonGenerator.valueToCode(block, 'THEN', Order.CONDITIONAL) || 'None';
|
||||
const value_else =
|
||||
Python.valueToCode(block, 'ELSE', Python.ORDER_CONDITIONAL) || 'None';
|
||||
pythonGenerator.valueToCode(block, 'ELSE', Order.CONDITIONAL) || 'None';
|
||||
const code = value_then + ' if ' + value_if + ' else ' + value_else;
|
||||
return [code, Python.ORDER_CONDITIONAL];
|
||||
return [code, Order.CONDITIONAL];
|
||||
};
|
||||
|
||||
@@ -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 as Python} from '../python.js';
|
||||
import {pythonGenerator, Order} from '../python.js';
|
||||
|
||||
|
||||
Python.forBlock['controls_repeat_ext'] = function(block) {
|
||||
pythonGenerator.forBlock['controls_repeat_ext'] = function(block) {
|
||||
// Repeat n times.
|
||||
let repeats;
|
||||
if (block.getField('TIMES')) {
|
||||
@@ -24,68 +24,71 @@ Python.forBlock['controls_repeat_ext'] = function(block) {
|
||||
repeats = String(parseInt(block.getFieldValue('TIMES'), 10));
|
||||
} else {
|
||||
// External number.
|
||||
repeats = Python.valueToCode(block, 'TIMES', Python.ORDER_NONE) || '0';
|
||||
repeats = pythonGenerator.valueToCode(block, 'TIMES', Order.NONE) || '0';
|
||||
}
|
||||
if (stringUtils.isNumber(repeats)) {
|
||||
repeats = parseInt(repeats, 10);
|
||||
} else {
|
||||
repeats = 'int(' + repeats + ')';
|
||||
}
|
||||
let branch = Python.statementToCode(block, 'DO');
|
||||
branch = Python.addLoopTrap(branch, block) || Python.PASS;
|
||||
const loopVar = Python.nameDB_.getDistinctName('count', NameType.VARIABLE);
|
||||
let branch = pythonGenerator.statementToCode(block, 'DO');
|
||||
branch = pythonGenerator.addLoopTrap(branch, block) || pythonGenerator.PASS;
|
||||
const loopVar =
|
||||
pythonGenerator.nameDB_.getDistinctName('count', NameType.VARIABLE);
|
||||
const code = 'for ' + loopVar + ' in range(' + repeats + '):\n' + branch;
|
||||
return code;
|
||||
};
|
||||
|
||||
Python.forBlock['controls_repeat'] = Python.forBlock['controls_repeat_ext'];
|
||||
pythonGenerator.forBlock['controls_repeat'] =
|
||||
pythonGenerator.forBlock['controls_repeat_ext'];
|
||||
|
||||
Python.forBlock['controls_whileUntil'] = function(block) {
|
||||
pythonGenerator.forBlock['controls_whileUntil'] = function(block) {
|
||||
// Do while/until loop.
|
||||
const until = block.getFieldValue('MODE') === 'UNTIL';
|
||||
let argument0 = Python.valueToCode(
|
||||
let argument0 = pythonGenerator.valueToCode(
|
||||
block, 'BOOL',
|
||||
until ? Python.ORDER_LOGICAL_NOT : Python.ORDER_NONE) ||
|
||||
until ? Order.LOGICAL_NOT : Order.NONE) ||
|
||||
'False';
|
||||
let branch = Python.statementToCode(block, 'DO');
|
||||
branch = Python.addLoopTrap(branch, block) || Python.PASS;
|
||||
let branch = pythonGenerator.statementToCode(block, 'DO');
|
||||
branch = pythonGenerator.addLoopTrap(branch, block) || pythonGenerator.PASS;
|
||||
if (until) {
|
||||
argument0 = 'not ' + argument0;
|
||||
}
|
||||
return 'while ' + argument0 + ':\n' + branch;
|
||||
};
|
||||
|
||||
Python.forBlock['controls_for'] = function(block) {
|
||||
pythonGenerator.forBlock['controls_for'] = function(block) {
|
||||
// For loop.
|
||||
const variable0 =
|
||||
Python.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
|
||||
let argument0 = Python.valueToCode(block, 'FROM', Python.ORDER_NONE) || '0';
|
||||
let argument1 = Python.valueToCode(block, 'TO', Python.ORDER_NONE) || '0';
|
||||
let increment = Python.valueToCode(block, 'BY', Python.ORDER_NONE) || '1';
|
||||
let branch = Python.statementToCode(block, 'DO');
|
||||
branch = Python.addLoopTrap(branch, block) || Python.PASS;
|
||||
pythonGenerator.nameDB_.getName(
|
||||
block.getFieldValue('VAR'), NameType.VARIABLE);
|
||||
let argument0 = pythonGenerator.valueToCode(block, 'FROM', Order.NONE) || '0';
|
||||
let argument1 = pythonGenerator.valueToCode(block, 'TO', Order.NONE) || '0';
|
||||
let increment = pythonGenerator.valueToCode(block, 'BY', Order.NONE) || '1';
|
||||
let branch = pythonGenerator.statementToCode(block, 'DO');
|
||||
branch = pythonGenerator.addLoopTrap(branch, block) || pythonGenerator.PASS;
|
||||
|
||||
let code = '';
|
||||
let range;
|
||||
|
||||
// Helper functions.
|
||||
const defineUpRange = function() {
|
||||
return Python.provideFunction_('upRange', `
|
||||
def ${Python.FUNCTION_NAME_PLACEHOLDER_}(start, stop, step):
|
||||
return pythonGenerator.provideFunction_('upRange', `
|
||||
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(start, stop, step):
|
||||
while start <= stop:
|
||||
yield start
|
||||
start += abs(step)
|
||||
`);
|
||||
};
|
||||
const defineDownRange = function() {
|
||||
return Python.provideFunction_('downRange', `
|
||||
def ${Python.FUNCTION_NAME_PLACEHOLDER_}(start, stop, step):
|
||||
return pythonGenerator.provideFunction_('downRange', `
|
||||
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(start, stop, step):
|
||||
while start >= stop:
|
||||
yield start
|
||||
start -= abs(step)
|
||||
`);
|
||||
};
|
||||
// Arguments are legal Python code (numbers or strings returned by scrub()).
|
||||
// Arguments are legal pythonGenerator code (numbers or strings returned by scrub()).
|
||||
const generateUpDownRange = function(start, end, inc) {
|
||||
return '(' + start + ' <= ' + end + ') and ' + defineUpRange() + '(' +
|
||||
start + ', ' + end + ', ' + inc + ') or ' + defineDownRange() + '(' +
|
||||
@@ -136,7 +139,7 @@ def ${Python.FUNCTION_NAME_PLACEHOLDER_}(start, stop, step):
|
||||
arg = Number(arg);
|
||||
} else if (!arg.match(/^\w+$/)) {
|
||||
// Not a variable, it's complicated.
|
||||
const varName = Python.nameDB_.getDistinctName(
|
||||
const varName = pythonGenerator.nameDB_.getDistinctName(
|
||||
variable0 + suffix, NameType.VARIABLE);
|
||||
code += varName + ' = ' + arg + '\n';
|
||||
arg = varName;
|
||||
@@ -163,37 +166,38 @@ def ${Python.FUNCTION_NAME_PLACEHOLDER_}(start, stop, step):
|
||||
return code;
|
||||
};
|
||||
|
||||
Python.forBlock['controls_forEach'] = function(block) {
|
||||
pythonGenerator.forBlock['controls_forEach'] = function(block) {
|
||||
// For each loop.
|
||||
const variable0 =
|
||||
Python.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
|
||||
pythonGenerator.nameDB_.getName(
|
||||
block.getFieldValue('VAR'), NameType.VARIABLE);
|
||||
const argument0 =
|
||||
Python.valueToCode(block, 'LIST', Python.ORDER_RELATIONAL) || '[]';
|
||||
let branch = Python.statementToCode(block, 'DO');
|
||||
branch = Python.addLoopTrap(branch, block) || Python.PASS;
|
||||
pythonGenerator.valueToCode(block, 'LIST', Order.RELATIONAL) || '[]';
|
||||
let branch = pythonGenerator.statementToCode(block, 'DO');
|
||||
branch = pythonGenerator.addLoopTrap(branch, block) || pythonGenerator.PASS;
|
||||
const code = 'for ' + variable0 + ' in ' + argument0 + ':\n' + branch;
|
||||
return code;
|
||||
};
|
||||
|
||||
Python.forBlock['controls_flow_statements'] = function(block) {
|
||||
pythonGenerator.forBlock['controls_flow_statements'] = function(block) {
|
||||
// Flow statements: continue, break.
|
||||
let xfix = '';
|
||||
if (Python.STATEMENT_PREFIX) {
|
||||
if (pythonGenerator.STATEMENT_PREFIX) {
|
||||
// Automatic prefix insertion is switched off for this block. Add manually.
|
||||
xfix += Python.injectId(Python.STATEMENT_PREFIX, block);
|
||||
xfix += pythonGenerator.injectId(pythonGenerator.STATEMENT_PREFIX, block);
|
||||
}
|
||||
if (Python.STATEMENT_SUFFIX) {
|
||||
if (pythonGenerator.STATEMENT_SUFFIX) {
|
||||
// Inject any statement suffix here since the regular one at the end
|
||||
// will not get executed if the break/continue is triggered.
|
||||
xfix += Python.injectId(Python.STATEMENT_SUFFIX, block);
|
||||
xfix += pythonGenerator.injectId(pythonGenerator.STATEMENT_SUFFIX, block);
|
||||
}
|
||||
if (Python.STATEMENT_PREFIX) {
|
||||
if (pythonGenerator.STATEMENT_PREFIX) {
|
||||
const loop = block.getSurroundLoop();
|
||||
if (loop && !loop.suppressPrefixSuffix) {
|
||||
// Inject loop's statement prefix here since the regular one at the end
|
||||
// of the loop will not get executed if 'continue' is triggered.
|
||||
// In the case of 'break', a prefix is needed due to the loop's suffix.
|
||||
xfix += Python.injectId(Python.STATEMENT_PREFIX, loop);
|
||||
xfix += pythonGenerator.injectId(pythonGenerator.STATEMENT_PREFIX, loop);
|
||||
}
|
||||
}
|
||||
switch (block.getFieldValue('FLOW')) {
|
||||
|
||||
@@ -12,66 +12,67 @@ import * as goog from '../../closure/goog/goog.js';
|
||||
goog.declareModuleId('Blockly.Python.math');
|
||||
|
||||
import {NameType} from '../../core/names.js';
|
||||
import {pythonGenerator as Python} from '../python.js';
|
||||
import {pythonGenerator, Order} from '../python.js';
|
||||
|
||||
|
||||
// If any new block imports any library, add that library name here.
|
||||
Python.addReservedWords('math,random,Number');
|
||||
pythonGenerator.addReservedWords('math,random,Number');
|
||||
|
||||
Python.forBlock['math_number'] = function(block) {
|
||||
pythonGenerator.forBlock['math_number'] = function(block) {
|
||||
// Numeric value.
|
||||
let code = Number(block.getFieldValue('NUM'));
|
||||
let order;
|
||||
if (code === Infinity) {
|
||||
code = 'float("inf")';
|
||||
order = Python.ORDER_FUNCTION_CALL;
|
||||
order = Order.FUNCTION_CALL;
|
||||
} else if (code === -Infinity) {
|
||||
code = '-float("inf")';
|
||||
order = Python.ORDER_UNARY_SIGN;
|
||||
order = Order.UNARY_SIGN;
|
||||
} else {
|
||||
order = code < 0 ? Python.ORDER_UNARY_SIGN : Python.ORDER_ATOMIC;
|
||||
order = code < 0 ? Order.UNARY_SIGN : Order.ATOMIC;
|
||||
}
|
||||
return [code, order];
|
||||
};
|
||||
|
||||
Python.forBlock['math_arithmetic'] = function(block) {
|
||||
pythonGenerator.forBlock['math_arithmetic'] = function(block) {
|
||||
// Basic arithmetic operators, and power.
|
||||
const OPERATORS = {
|
||||
'ADD': [' + ', Python.ORDER_ADDITIVE],
|
||||
'MINUS': [' - ', Python.ORDER_ADDITIVE],
|
||||
'MULTIPLY': [' * ', Python.ORDER_MULTIPLICATIVE],
|
||||
'DIVIDE': [' / ', Python.ORDER_MULTIPLICATIVE],
|
||||
'POWER': [' ** ', Python.ORDER_EXPONENTIATION],
|
||||
'ADD': [' + ', Order.ADDITIVE],
|
||||
'MINUS': [' - ', Order.ADDITIVE],
|
||||
'MULTIPLY': [' * ', Order.MULTIPLICATIVE],
|
||||
'DIVIDE': [' / ', Order.MULTIPLICATIVE],
|
||||
'POWER': [' ** ', Order.EXPONENTIATION],
|
||||
};
|
||||
const tuple = OPERATORS[block.getFieldValue('OP')];
|
||||
const operator = tuple[0];
|
||||
const order = tuple[1];
|
||||
const argument0 = Python.valueToCode(block, 'A', order) || '0';
|
||||
const argument1 = Python.valueToCode(block, 'B', order) || '0';
|
||||
const argument0 = pythonGenerator.valueToCode(block, 'A', order) || '0';
|
||||
const argument1 = pythonGenerator.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
|
||||
// in pythonGenerator 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.
|
||||
};
|
||||
|
||||
Python.forBlock['math_single'] = function(block) {
|
||||
pythonGenerator.forBlock['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 = Python.valueToCode(block, 'NUM', Python.ORDER_UNARY_SIGN) || '0';
|
||||
return ['-' + code, Python.ORDER_UNARY_SIGN];
|
||||
code = pythonGenerator.valueToCode(block, 'NUM', Order.UNARY_SIGN) || '0';
|
||||
return ['-' + code, Order.UNARY_SIGN];
|
||||
}
|
||||
Python.definitions_['import_math'] = 'import math';
|
||||
pythonGenerator.definitions_['import_math'] = 'import math';
|
||||
if (operator === 'SIN' || operator === 'COS' || operator === 'TAN') {
|
||||
arg = Python.valueToCode(block, 'NUM', Python.ORDER_MULTIPLICATIVE) || '0';
|
||||
arg =
|
||||
pythonGenerator.valueToCode(block, 'NUM', Order.MULTIPLICATIVE) || '0';
|
||||
} else {
|
||||
arg = Python.valueToCode(block, 'NUM', Python.ORDER_NONE) || '0';
|
||||
arg = pythonGenerator.valueToCode(block, 'NUM', Order.NONE) || '0';
|
||||
}
|
||||
// First, handle cases which generate values that don't need parentheses
|
||||
// wrapping the code.
|
||||
@@ -114,7 +115,7 @@ Python.forBlock['math_single'] = function(block) {
|
||||
break;
|
||||
}
|
||||
if (code) {
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
}
|
||||
// Second, handle cases which generate values that may need parentheses
|
||||
// wrapping the code.
|
||||
@@ -131,52 +132,52 @@ Python.forBlock['math_single'] = function(block) {
|
||||
default:
|
||||
throw Error('Unknown math operator: ' + operator);
|
||||
}
|
||||
return [code, Python.ORDER_MULTIPLICATIVE];
|
||||
return [code, Order.MULTIPLICATIVE];
|
||||
};
|
||||
|
||||
Python.forBlock['math_constant'] = function(block) {
|
||||
pythonGenerator.forBlock['math_constant'] = function(block) {
|
||||
// Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY.
|
||||
const CONSTANTS = {
|
||||
'PI': ['math.pi', Python.ORDER_MEMBER],
|
||||
'E': ['math.e', Python.ORDER_MEMBER],
|
||||
'GOLDEN_RATIO': ['(1 + math.sqrt(5)) / 2', Python.ORDER_MULTIPLICATIVE],
|
||||
'SQRT2': ['math.sqrt(2)', Python.ORDER_MEMBER],
|
||||
'SQRT1_2': ['math.sqrt(1.0 / 2)', Python.ORDER_MEMBER],
|
||||
'INFINITY': ['float(\'inf\')', Python.ORDER_ATOMIC],
|
||||
'PI': ['math.pi', Order.MEMBER],
|
||||
'E': ['math.e', Order.MEMBER],
|
||||
'GOLDEN_RATIO': ['(1 + math.sqrt(5)) / 2', Order.MULTIPLICATIVE],
|
||||
'SQRT2': ['math.sqrt(2)', Order.MEMBER],
|
||||
'SQRT1_2': ['math.sqrt(1.0 / 2)', Order.MEMBER],
|
||||
'INFINITY': ['float(\'inf\')', Order.ATOMIC],
|
||||
};
|
||||
const constant = block.getFieldValue('CONSTANT');
|
||||
if (constant !== 'INFINITY') {
|
||||
Python.definitions_['import_math'] = 'import math';
|
||||
pythonGenerator.definitions_['import_math'] = 'import math';
|
||||
}
|
||||
return CONSTANTS[constant];
|
||||
};
|
||||
|
||||
Python.forBlock['math_number_property'] = function(block) {
|
||||
pythonGenerator.forBlock['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 PROPERTIES = {
|
||||
'EVEN': [' % 2 == 0', Python.ORDER_MULTIPLICATIVE, Python.ORDER_RELATIONAL],
|
||||
'ODD': [' % 2 == 1', Python.ORDER_MULTIPLICATIVE, Python.ORDER_RELATIONAL],
|
||||
'WHOLE': [' % 1 == 0', Python.ORDER_MULTIPLICATIVE,
|
||||
Python.ORDER_RELATIONAL],
|
||||
'POSITIVE': [' > 0', Python.ORDER_RELATIONAL, Python.ORDER_RELATIONAL],
|
||||
'NEGATIVE': [' < 0', Python.ORDER_RELATIONAL, Python.ORDER_RELATIONAL],
|
||||
'DIVISIBLE_BY': [null, Python.ORDER_MULTIPLICATIVE,
|
||||
Python.ORDER_RELATIONAL],
|
||||
'PRIME': [null, Python.ORDER_NONE, Python.ORDER_FUNCTION_CALL],
|
||||
'EVEN': [' % 2 == 0', Order.MULTIPLICATIVE, Order.RELATIONAL],
|
||||
'ODD': [' % 2 == 1', Order.MULTIPLICATIVE, Order.RELATIONAL],
|
||||
'WHOLE': [' % 1 == 0', Order.MULTIPLICATIVE,
|
||||
Order.RELATIONAL],
|
||||
'POSITIVE': [' > 0', Order.RELATIONAL, Order.RELATIONAL],
|
||||
'NEGATIVE': [' < 0', Order.RELATIONAL, Order.RELATIONAL],
|
||||
'DIVISIBLE_BY': [null, Order.MULTIPLICATIVE,
|
||||
Order.RELATIONAL],
|
||||
'PRIME': [null, Order.NONE, Order.FUNCTION_CALL],
|
||||
}
|
||||
const dropdownProperty = block.getFieldValue('PROPERTY');
|
||||
const [suffix, inputOrder, outputOrder] = PROPERTIES[dropdownProperty];
|
||||
const numberToCheck = Python.valueToCode(block, 'NUMBER_TO_CHECK',
|
||||
const numberToCheck = pythonGenerator.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.
|
||||
Python.definitions_['import_math'] = 'import math';
|
||||
Python.definitions_['from_numbers_import_Number'] =
|
||||
pythonGenerator.definitions_['import_math'] = 'import math';
|
||||
pythonGenerator.definitions_['from_numbers_import_Number'] =
|
||||
'from numbers import Number';
|
||||
const functionName = Python.provideFunction_('math_isPrime', `
|
||||
def ${Python.FUNCTION_NAME_PLACEHOLDER_}(n):
|
||||
const functionName = pythonGenerator.provideFunction_('math_isPrime', `
|
||||
def ${pythonGenerator.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):
|
||||
@@ -197,11 +198,11 @@ def ${Python.FUNCTION_NAME_PLACEHOLDER_}(n):
|
||||
`);
|
||||
code = functionName + '(' + numberToCheck + ')';
|
||||
} else if (dropdownProperty === 'DIVISIBLE_BY') {
|
||||
const divisor = Python.valueToCode(block, 'DIVISOR',
|
||||
Python.ORDER_MULTIPLICATIVE) || '0';
|
||||
// If 'divisor' is some code that evals to 0, Python will raise an error.
|
||||
const divisor = pythonGenerator.valueToCode(block, 'DIVISOR',
|
||||
Order.MULTIPLICATIVE) || '0';
|
||||
// If 'divisor' is some code that evals to 0, pythonGenerator will raise an error.
|
||||
if (divisor === '0') {
|
||||
return ['False', Python.ORDER_ATOMIC];
|
||||
return ['False', Order.ATOMIC];
|
||||
}
|
||||
code = numberToCheck + ' % ' + divisor + ' == 0';
|
||||
} else {
|
||||
@@ -210,27 +211,30 @@ def ${Python.FUNCTION_NAME_PLACEHOLDER_}(n):
|
||||
return [code, outputOrder];
|
||||
};
|
||||
|
||||
Python.forBlock['math_change'] = function(block) {
|
||||
pythonGenerator.forBlock['math_change'] = function(block) {
|
||||
// Add to a variable in place.
|
||||
Python.definitions_['from_numbers_import_Number'] =
|
||||
pythonGenerator.definitions_['from_numbers_import_Number'] =
|
||||
'from numbers import Number';
|
||||
const argument0 =
|
||||
Python.valueToCode(block, 'DELTA', Python.ORDER_ADDITIVE) || '0';
|
||||
pythonGenerator.valueToCode(block, 'DELTA', Order.ADDITIVE) || '0';
|
||||
const varName =
|
||||
Python.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
|
||||
pythonGenerator.nameDB_.getName(
|
||||
block.getFieldValue('VAR'), NameType.VARIABLE);
|
||||
return varName + ' = (' + varName + ' if isinstance(' + varName +
|
||||
', Number) else 0) + ' + argument0 + '\n';
|
||||
};
|
||||
|
||||
// Rounding functions have a single operand.
|
||||
Python.forBlock['math_round'] = Python.forBlock['math_single'];
|
||||
pythonGenerator.forBlock['math_round'] =
|
||||
pythonGenerator.forBlock['math_single'];
|
||||
// Trigonometry functions have a single operand.
|
||||
Python.forBlock['math_trig'] = Python.forBlock['math_single'];
|
||||
pythonGenerator.forBlock['math_trig'] =
|
||||
pythonGenerator.forBlock['math_single'];
|
||||
|
||||
Python.forBlock['math_on_list'] = function(block) {
|
||||
pythonGenerator.forBlock['math_on_list'] = function(block) {
|
||||
// Math functions for lists.
|
||||
const func = block.getFieldValue('OP');
|
||||
const list = Python.valueToCode(block, 'LIST', Python.ORDER_NONE) || '[]';
|
||||
const list = pythonGenerator.valueToCode(block, 'LIST', Order.NONE) || '[]';
|
||||
let code;
|
||||
switch (func) {
|
||||
case 'SUM':
|
||||
@@ -243,12 +247,12 @@ Python.forBlock['math_on_list'] = function(block) {
|
||||
code = 'max(' + list + ')';
|
||||
break;
|
||||
case 'AVERAGE': {
|
||||
Python.definitions_['from_numbers_import_Number'] =
|
||||
pythonGenerator.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 = Python.provideFunction_('math_mean', `
|
||||
def ${Python.FUNCTION_NAME_PLACEHOLDER_}(myList):
|
||||
const functionName = pythonGenerator.provideFunction_('math_mean', `
|
||||
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(myList):
|
||||
localList = [e for e in myList if isinstance(e, Number)]
|
||||
if not localList: return
|
||||
return float(sum(localList)) / len(localList)
|
||||
@@ -257,12 +261,12 @@ def ${Python.FUNCTION_NAME_PLACEHOLDER_}(myList):
|
||||
break;
|
||||
}
|
||||
case 'MEDIAN': {
|
||||
Python.definitions_['from_numbers_import_Number'] =
|
||||
pythonGenerator.definitions_['from_numbers_import_Number'] =
|
||||
'from numbers import Number';
|
||||
// This operation excludes null values:
|
||||
// math_median([null, null, 1, 3]) -> 2.0
|
||||
const functionName = Python.provideFunction_( 'math_median', `
|
||||
def ${Python.FUNCTION_NAME_PLACEHOLDER_}(myList):
|
||||
const functionName = pythonGenerator.provideFunction_( 'math_median', `
|
||||
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(myList):
|
||||
localList = sorted([e for e in myList if isinstance(e, Number)])
|
||||
if not localList: return
|
||||
if len(localList) % 2 == 0:
|
||||
@@ -277,8 +281,8 @@ def ${Python.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 = Python.provideFunction_('math_modes', `
|
||||
def ${Python.FUNCTION_NAME_PLACEHOLDER_}(some_list):
|
||||
const functionName = pythonGenerator.provideFunction_('math_modes', `
|
||||
def ${pythonGenerator.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.
|
||||
@@ -302,9 +306,10 @@ def ${Python.FUNCTION_NAME_PLACEHOLDER_}(some_list):
|
||||
break;
|
||||
}
|
||||
case 'STD_DEV': {
|
||||
Python.definitions_['import_math'] = 'import math';
|
||||
const functionName = Python.provideFunction_('math_standard_deviation', `
|
||||
def ${Python.FUNCTION_NAME_PLACEHOLDER_}(numbers):
|
||||
pythonGenerator.definitions_['import_math'] = 'import math';
|
||||
const functionName =
|
||||
pythonGenerator.provideFunction_('math_standard_deviation', `
|
||||
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(numbers):
|
||||
n = len(numbers)
|
||||
if n == 0: return
|
||||
mean = float(sum(numbers)) / n
|
||||
@@ -315,59 +320,65 @@ def ${Python.FUNCTION_NAME_PLACEHOLDER_}(numbers):
|
||||
break;
|
||||
}
|
||||
case 'RANDOM':
|
||||
Python.definitions_['import_random'] = 'import random';
|
||||
pythonGenerator.definitions_['import_random'] = 'import random';
|
||||
code = 'random.choice(' + list + ')';
|
||||
break;
|
||||
default:
|
||||
throw Error('Unknown operator: ' + func);
|
||||
}
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['math_modulo'] = function(block) {
|
||||
pythonGenerator.forBlock['math_modulo'] = function(block) {
|
||||
// Remainder computation.
|
||||
const argument0 =
|
||||
Python.valueToCode(block, 'DIVIDEND', Python.ORDER_MULTIPLICATIVE) || '0';
|
||||
pythonGenerator.valueToCode(block, 'DIVIDEND', Order.MULTIPLICATIVE) ||
|
||||
'0';
|
||||
const argument1 =
|
||||
Python.valueToCode(block, 'DIVISOR', Python.ORDER_MULTIPLICATIVE) || '0';
|
||||
pythonGenerator.valueToCode(block, 'DIVISOR', Order.MULTIPLICATIVE) ||
|
||||
'0';
|
||||
const code = argument0 + ' % ' + argument1;
|
||||
return [code, Python.ORDER_MULTIPLICATIVE];
|
||||
return [code, Order.MULTIPLICATIVE];
|
||||
};
|
||||
|
||||
Python.forBlock['math_constrain'] = function(block) {
|
||||
pythonGenerator.forBlock['math_constrain'] = function(block) {
|
||||
// Constrain a number between two limits.
|
||||
const argument0 =
|
||||
Python.valueToCode(block, 'VALUE', Python.ORDER_NONE) || '0';
|
||||
const argument1 = Python.valueToCode(block, 'LOW', Python.ORDER_NONE) || '0';
|
||||
pythonGenerator.valueToCode(block, 'VALUE', Order.NONE) || '0';
|
||||
const argument1 =
|
||||
pythonGenerator.valueToCode(block, 'LOW', Order.NONE) || '0';
|
||||
const argument2 =
|
||||
Python.valueToCode(block, 'HIGH', Python.ORDER_NONE) || 'float(\'inf\')';
|
||||
pythonGenerator.valueToCode(block, 'HIGH', Order.NONE) ||
|
||||
'float(\'inf\')';
|
||||
const code =
|
||||
'min(max(' + argument0 + ', ' + argument1 + '), ' + argument2 + ')';
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['math_random_int'] = function(block) {
|
||||
pythonGenerator.forBlock['math_random_int'] = function(block) {
|
||||
// Random integer between [X] and [Y].
|
||||
Python.definitions_['import_random'] = 'import random';
|
||||
const argument0 = Python.valueToCode(block, 'FROM', Python.ORDER_NONE) || '0';
|
||||
const argument1 = Python.valueToCode(block, 'TO', Python.ORDER_NONE) || '0';
|
||||
pythonGenerator.definitions_['import_random'] = 'import random';
|
||||
const argument0 =
|
||||
pythonGenerator.valueToCode(block, 'FROM', Order.NONE) || '0';
|
||||
const argument1 =
|
||||
pythonGenerator.valueToCode(block, 'TO', Order.NONE) || '0';
|
||||
const code = 'random.randint(' + argument0 + ', ' + argument1 + ')';
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['math_random_float'] = function(block) {
|
||||
pythonGenerator.forBlock['math_random_float'] = function(block) {
|
||||
// Random fraction between 0 and 1.
|
||||
Python.definitions_['import_random'] = 'import random';
|
||||
return ['random.random()', Python.ORDER_FUNCTION_CALL];
|
||||
pythonGenerator.definitions_['import_random'] = 'import random';
|
||||
return ['random.random()', Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['math_atan2'] = function(block) {
|
||||
pythonGenerator.forBlock['math_atan2'] = function(block) {
|
||||
// Arctangent of point (X, Y) in degrees from -180 to 180.
|
||||
Python.definitions_['import_math'] = 'import math';
|
||||
const argument0 = Python.valueToCode(block, 'X', Python.ORDER_NONE) || '0';
|
||||
const argument1 = Python.valueToCode(block, 'Y', Python.ORDER_NONE) || '0';
|
||||
pythonGenerator.definitions_['import_math'] = 'import math';
|
||||
const argument0 = pythonGenerator.valueToCode(block, 'X', Order.NONE) || '0';
|
||||
const argument1 = pythonGenerator.valueToCode(block, 'Y', Order.NONE) || '0';
|
||||
return [
|
||||
'math.atan2(' + argument1 + ', ' + argument0 + ') / math.pi * 180',
|
||||
Python.ORDER_MULTIPLICATIVE
|
||||
Order.MULTIPLICATIVE
|
||||
];
|
||||
};
|
||||
|
||||
@@ -13,10 +13,10 @@ goog.declareModuleId('Blockly.Python.procedures');
|
||||
|
||||
import * as Variables from '../../core/variables.js';
|
||||
import {NameType} from '../../core/names.js';
|
||||
import {pythonGenerator as Python} from '../python.js';
|
||||
import {pythonGenerator, Order} from '../python.js';
|
||||
|
||||
|
||||
Python.forBlock['procedures_defreturn'] = function(block) {
|
||||
pythonGenerator.forBlock['procedures_defreturn'] = function(block) {
|
||||
// Define a procedure with a return value.
|
||||
// First, add a 'global' statement for every variable that is not shadowed by
|
||||
// a local parameter.
|
||||
@@ -26,104 +26,111 @@ Python.forBlock['procedures_defreturn'] = function(block) {
|
||||
for (let i = 0, variable; (variable = usedVariables[i]); i++) {
|
||||
const varName = variable.name;
|
||||
if (block.getVars().indexOf(varName) === -1) {
|
||||
globals.push(Python.nameDB_.getName(varName, NameType.VARIABLE));
|
||||
globals.push(pythonGenerator.nameDB_.getName(varName, NameType.VARIABLE));
|
||||
}
|
||||
}
|
||||
// Add developer variables.
|
||||
const devVarList = Variables.allDeveloperVariables(workspace);
|
||||
for (let i = 0; i < devVarList.length; i++) {
|
||||
globals.push(
|
||||
Python.nameDB_.getName(devVarList[i], NameType.DEVELOPER_VARIABLE));
|
||||
pythonGenerator.nameDB_.getName(
|
||||
devVarList[i], NameType.DEVELOPER_VARIABLE));
|
||||
}
|
||||
|
||||
const globalString = globals.length ?
|
||||
Python.INDENT + 'global ' + globals.join(', ') + '\n' :
|
||||
pythonGenerator.INDENT + 'global ' + globals.join(', ') + '\n' :
|
||||
'';
|
||||
const funcName =
|
||||
Python.nameDB_.getName(block.getFieldValue('NAME'), NameType.PROCEDURE);
|
||||
pythonGenerator.nameDB_.getName(
|
||||
block.getFieldValue('NAME'), NameType.PROCEDURE);
|
||||
let xfix1 = '';
|
||||
if (Python.STATEMENT_PREFIX) {
|
||||
xfix1 += Python.injectId(Python.STATEMENT_PREFIX, block);
|
||||
if (pythonGenerator.STATEMENT_PREFIX) {
|
||||
xfix1 += pythonGenerator.injectId(pythonGenerator.STATEMENT_PREFIX, block);
|
||||
}
|
||||
if (Python.STATEMENT_SUFFIX) {
|
||||
xfix1 += Python.injectId(Python.STATEMENT_SUFFIX, block);
|
||||
if (pythonGenerator.STATEMENT_SUFFIX) {
|
||||
xfix1 += pythonGenerator.injectId(pythonGenerator.STATEMENT_SUFFIX, block);
|
||||
}
|
||||
if (xfix1) {
|
||||
xfix1 = Python.prefixLines(xfix1, Python.INDENT);
|
||||
xfix1 = pythonGenerator.prefixLines(xfix1, pythonGenerator.INDENT);
|
||||
}
|
||||
let loopTrap = '';
|
||||
if (Python.INFINITE_LOOP_TRAP) {
|
||||
loopTrap = Python.prefixLines(
|
||||
Python.injectId(Python.INFINITE_LOOP_TRAP, block), Python.INDENT);
|
||||
if (pythonGenerator.INFINITE_LOOP_TRAP) {
|
||||
loopTrap = pythonGenerator.prefixLines(
|
||||
pythonGenerator.injectId(pythonGenerator.INFINITE_LOOP_TRAP, block),
|
||||
pythonGenerator.INDENT);
|
||||
}
|
||||
let branch = Python.statementToCode(block, 'STACK');
|
||||
let branch = pythonGenerator.statementToCode(block, 'STACK');
|
||||
let returnValue =
|
||||
Python.valueToCode(block, 'RETURN', Python.ORDER_NONE) || '';
|
||||
pythonGenerator.valueToCode(block, 'RETURN', Order.NONE) || '';
|
||||
let xfix2 = '';
|
||||
if (branch && returnValue) {
|
||||
// After executing the function body, revisit this block for the return.
|
||||
xfix2 = xfix1;
|
||||
}
|
||||
if (returnValue) {
|
||||
returnValue = Python.INDENT + 'return ' + returnValue + '\n';
|
||||
returnValue = pythonGenerator.INDENT + 'return ' + returnValue + '\n';
|
||||
} else if (!branch) {
|
||||
branch = Python.PASS;
|
||||
branch = pythonGenerator.PASS;
|
||||
}
|
||||
const args = [];
|
||||
const variables = block.getVars();
|
||||
for (let i = 0; i < variables.length; i++) {
|
||||
args[i] = Python.nameDB_.getName(variables[i], NameType.VARIABLE);
|
||||
args[i] = pythonGenerator.nameDB_.getName(variables[i], NameType.VARIABLE);
|
||||
}
|
||||
let code = 'def ' + funcName + '(' + args.join(', ') + '):\n' + globalString +
|
||||
xfix1 + loopTrap + branch + xfix2 + returnValue;
|
||||
code = Python.scrub_(block, code);
|
||||
code = pythonGenerator.scrub_(block, code);
|
||||
// Add % so as not to collide with helper functions in definitions list.
|
||||
Python.definitions_['%' + funcName] = code;
|
||||
pythonGenerator.definitions_['%' + funcName] = code;
|
||||
return null;
|
||||
};
|
||||
|
||||
// Defining a procedure without a return value uses the same generator as
|
||||
// a procedure with a return value.
|
||||
Python.forBlock['procedures_defnoreturn'] = Python.forBlock['procedures_defreturn'];
|
||||
pythonGenerator.forBlock['procedures_defnoreturn'] =
|
||||
pythonGenerator.forBlock['procedures_defreturn'];
|
||||
|
||||
Python.forBlock['procedures_callreturn'] = function(block) {
|
||||
pythonGenerator.forBlock['procedures_callreturn'] = function(block) {
|
||||
// Call a procedure with a return value.
|
||||
const funcName =
|
||||
Python.nameDB_.getName(block.getFieldValue('NAME'), NameType.PROCEDURE);
|
||||
pythonGenerator.nameDB_.getName(
|
||||
block.getFieldValue('NAME'), NameType.PROCEDURE);
|
||||
const args = [];
|
||||
const variables = block.getVars();
|
||||
for (let i = 0; i < variables.length; i++) {
|
||||
args[i] = Python.valueToCode(block, 'ARG' + i, Python.ORDER_NONE) || 'None';
|
||||
args[i] =
|
||||
pythonGenerator.valueToCode(block, 'ARG' + i, Order.NONE) || 'None';
|
||||
}
|
||||
const code = funcName + '(' + args.join(', ') + ')';
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['procedures_callnoreturn'] = function(block) {
|
||||
pythonGenerator.forBlock['procedures_callnoreturn'] = function(block) {
|
||||
// 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.
|
||||
const tuple = Python.forBlock['procedures_callreturn'](block);
|
||||
const tuple = pythonGenerator.forBlock['procedures_callreturn'](block);
|
||||
return tuple[0] + '\n';
|
||||
};
|
||||
|
||||
Python.forBlock['procedures_ifreturn'] = function(block) {
|
||||
pythonGenerator.forBlock['procedures_ifreturn'] = function(block) {
|
||||
// Conditionally return value from a procedure.
|
||||
const condition =
|
||||
Python.valueToCode(block, 'CONDITION', Python.ORDER_NONE) || 'False';
|
||||
pythonGenerator.valueToCode(block, 'CONDITION', Order.NONE) || 'False';
|
||||
let code = 'if ' + condition + ':\n';
|
||||
if (Python.STATEMENT_SUFFIX) {
|
||||
if (pythonGenerator.STATEMENT_SUFFIX) {
|
||||
// Inject any statement suffix here since the regular one at the end
|
||||
// will not get executed if the return is triggered.
|
||||
code += Python.prefixLines(
|
||||
Python.injectId(Python.STATEMENT_SUFFIX, block), Python.INDENT);
|
||||
code += pythonGenerator.prefixLines(
|
||||
pythonGenerator.injectId(
|
||||
pythonGenerator.STATEMENT_SUFFIX, block), pythonGenerator.INDENT);
|
||||
}
|
||||
if (block.hasReturnValue_) {
|
||||
const value =
|
||||
Python.valueToCode(block, 'VALUE', Python.ORDER_NONE) || 'None';
|
||||
code += Python.INDENT + 'return ' + value + '\n';
|
||||
pythonGenerator.valueToCode(block, 'VALUE', Order.NONE) || 'None';
|
||||
code += pythonGenerator.INDENT + 'return ' + value + '\n';
|
||||
} else {
|
||||
code += Python.INDENT + 'return\n';
|
||||
code += pythonGenerator.INDENT + 'return\n';
|
||||
}
|
||||
return code;
|
||||
};
|
||||
|
||||
@@ -13,20 +13,20 @@ goog.declareModuleId('Blockly.Python.texts');
|
||||
|
||||
import * as stringUtils from '../../core/utils/string.js';
|
||||
import {NameType} from '../../core/names.js';
|
||||
import {pythonGenerator as Python} from '../python.js';
|
||||
import {pythonGenerator, Order} from '../python.js';
|
||||
|
||||
|
||||
Python.forBlock['text'] = function(block) {
|
||||
pythonGenerator.forBlock['text'] = function(block) {
|
||||
// Text value.
|
||||
const code = Python.quote_(block.getFieldValue('TEXT'));
|
||||
return [code, Python.ORDER_ATOMIC];
|
||||
const code = pythonGenerator.quote_(block.getFieldValue('TEXT'));
|
||||
return [code, Order.ATOMIC];
|
||||
};
|
||||
|
||||
Python.forBlock['text_multiline'] = function(block) {
|
||||
pythonGenerator.forBlock['text_multiline'] = function(block) {
|
||||
// Text value.
|
||||
const code = Python.multiline_quote_(block.getFieldValue('TEXT'));
|
||||
const code = pythonGenerator.multiline_quote_(block.getFieldValue('TEXT'));
|
||||
const order =
|
||||
code.indexOf('+') !== -1 ? Python.ORDER_ADDITIVE : Python.ORDER_ATOMIC;
|
||||
code.indexOf('+') !== -1 ? Order.ADDITIVE : Order.ATOMIC;
|
||||
return [code, order];
|
||||
};
|
||||
|
||||
@@ -45,137 +45,140 @@ const strRegExp = /^\s*'([^']|\\')*'\s*$/;
|
||||
*/
|
||||
const forceString = function(value) {
|
||||
if (strRegExp.test(value)) {
|
||||
return [value, Python.ORDER_ATOMIC];
|
||||
return [value, Order.ATOMIC];
|
||||
}
|
||||
return ['str(' + value + ')', Python.ORDER_FUNCTION_CALL];
|
||||
return ['str(' + value + ')', Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['text_join'] = function(block) {
|
||||
pythonGenerator.forBlock['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];
|
||||
return ["''", Order.ATOMIC];
|
||||
case 1: {
|
||||
const element =
|
||||
Python.valueToCode(block, 'ADD0', Python.ORDER_NONE) || "''";
|
||||
pythonGenerator.valueToCode(block, 'ADD0', Order.NONE) || "''";
|
||||
const codeAndOrder = forceString(element);
|
||||
return codeAndOrder;
|
||||
}
|
||||
case 2: {
|
||||
const element0 =
|
||||
Python.valueToCode(block, 'ADD0', Python.ORDER_NONE) || "''";
|
||||
pythonGenerator.valueToCode(block, 'ADD0', Order.NONE) || "''";
|
||||
const element1 =
|
||||
Python.valueToCode(block, 'ADD1', Python.ORDER_NONE) || "''";
|
||||
pythonGenerator.valueToCode(block, 'ADD1', Order.NONE) || "''";
|
||||
const code = forceString(element0)[0] + ' + ' + forceString(element1)[0];
|
||||
return [code, Python.ORDER_ADDITIVE];
|
||||
return [code, Order.ADDITIVE];
|
||||
}
|
||||
default: {
|
||||
const elements = [];
|
||||
for (let i = 0; i < block.itemCount_; i++) {
|
||||
elements[i] =
|
||||
Python.valueToCode(block, 'ADD' + i, Python.ORDER_NONE) || "''";
|
||||
pythonGenerator.valueToCode(block, 'ADD' + i, Order.NONE) || "''";
|
||||
}
|
||||
const tempVar = Python.nameDB_.getDistinctName('x', NameType.VARIABLE);
|
||||
const tempVar =
|
||||
pythonGenerator.nameDB_.getDistinctName('x', NameType.VARIABLE);
|
||||
const code = '\'\'.join([str(' + tempVar + ') for ' + tempVar + ' in [' +
|
||||
elements.join(', ') + ']])';
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Python.forBlock['text_append'] = function(block) {
|
||||
pythonGenerator.forBlock['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) || "''";
|
||||
pythonGenerator.nameDB_.getName(
|
||||
block.getFieldValue('VAR'), NameType.VARIABLE);
|
||||
const value = pythonGenerator.valueToCode(block, 'TEXT', Order.NONE) || "''";
|
||||
return varName + ' = str(' + varName + ') + ' + forceString(value)[0] + '\n';
|
||||
};
|
||||
|
||||
Python.forBlock['text_length'] = function(block) {
|
||||
pythonGenerator.forBlock['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];
|
||||
const text = pythonGenerator.valueToCode(block, 'VALUE', Order.NONE) || "''";
|
||||
return ['len(' + text + ')', Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['text_isEmpty'] = function(block) {
|
||||
pythonGenerator.forBlock['text_isEmpty'] = function(block) {
|
||||
// Is the string null or array empty?
|
||||
const text = Python.valueToCode(block, 'VALUE', Python.ORDER_NONE) || "''";
|
||||
const text = pythonGenerator.valueToCode(block, 'VALUE', Order.NONE) || "''";
|
||||
const code = 'not len(' + text + ')';
|
||||
return [code, Python.ORDER_LOGICAL_NOT];
|
||||
return [code, Order.LOGICAL_NOT];
|
||||
};
|
||||
|
||||
Python.forBlock['text_indexOf'] = function(block) {
|
||||
pythonGenerator.forBlock['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) || "''";
|
||||
pythonGenerator.valueToCode(block, 'FIND', Order.NONE) || "''";
|
||||
const text =
|
||||
Python.valueToCode(block, 'VALUE', Python.ORDER_MEMBER) || "''";
|
||||
pythonGenerator.valueToCode(block, 'VALUE', Order.MEMBER) || "''";
|
||||
const code = text + '.' + operator + '(' + substring + ')';
|
||||
if (block.workspace.options.oneBasedIndex) {
|
||||
return [code + ' + 1', Python.ORDER_ADDITIVE];
|
||||
return [code + ' + 1', Order.ADDITIVE];
|
||||
}
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['text_charAt'] = function(block) {
|
||||
pythonGenerator.forBlock['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) || "''";
|
||||
(where === 'RANDOM') ? Order.NONE : Order.MEMBER;
|
||||
const text = pythonGenerator.valueToCode(block, 'VALUE', textOrder) || "''";
|
||||
switch (where) {
|
||||
case 'FIRST': {
|
||||
const code = text + '[0]';
|
||||
return [code, Python.ORDER_MEMBER];
|
||||
return [code, Order.MEMBER];
|
||||
}
|
||||
case 'LAST': {
|
||||
const code = text + '[-1]';
|
||||
return [code, Python.ORDER_MEMBER];
|
||||
return [code, Order.MEMBER];
|
||||
}
|
||||
case 'FROM_START': {
|
||||
const at = Python.getAdjustedInt(block, 'AT');
|
||||
const at = pythonGenerator.getAdjustedInt(block, 'AT');
|
||||
const code = text + '[' + at + ']';
|
||||
return [code, Python.ORDER_MEMBER];
|
||||
return [code, Order.MEMBER];
|
||||
}
|
||||
case 'FROM_END': {
|
||||
const at = Python.getAdjustedInt(block, 'AT', 1, true);
|
||||
const at = pythonGenerator.getAdjustedInt(block, 'AT', 1, true);
|
||||
const code = text + '[' + at + ']';
|
||||
return [code, Python.ORDER_MEMBER];
|
||||
return [code, Order.MEMBER];
|
||||
}
|
||||
case 'RANDOM': {
|
||||
Python.definitions_['import_random'] = 'import random';
|
||||
const functionName = Python.provideFunction_('text_random_letter', `
|
||||
def ${Python.FUNCTION_NAME_PLACEHOLDER_}(text):
|
||||
pythonGenerator.definitions_['import_random'] = 'import random';
|
||||
const functionName =
|
||||
pythonGenerator.provideFunction_('text_random_letter', `
|
||||
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(text):
|
||||
x = int(random.random() * len(text))
|
||||
return text[x]
|
||||
`);
|
||||
const code = functionName + '(' + text + ')';
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
}
|
||||
}
|
||||
throw Error('Unhandled option (text_charAt).');
|
||||
};
|
||||
|
||||
Python.forBlock['text_getSubstring'] = function(block) {
|
||||
pythonGenerator.forBlock['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) || "''";
|
||||
pythonGenerator.valueToCode(block, 'STRING', Order.MEMBER) || "''";
|
||||
let at1;
|
||||
switch (where1) {
|
||||
case 'FROM_START':
|
||||
at1 = Python.getAdjustedInt(block, 'AT1');
|
||||
at1 = pythonGenerator.getAdjustedInt(block, 'AT1');
|
||||
if (at1 === 0) {
|
||||
at1 = '';
|
||||
}
|
||||
break;
|
||||
case 'FROM_END':
|
||||
at1 = Python.getAdjustedInt(block, 'AT1', 1, true);
|
||||
at1 = pythonGenerator.getAdjustedInt(block, 'AT1', 1, true);
|
||||
break;
|
||||
case 'FIRST':
|
||||
at1 = '';
|
||||
@@ -187,14 +190,14 @@ Python.forBlock['text_getSubstring'] = function(block) {
|
||||
let at2;
|
||||
switch (where2) {
|
||||
case 'FROM_START':
|
||||
at2 = Python.getAdjustedInt(block, 'AT2', 1);
|
||||
at2 = pythonGenerator.getAdjustedInt(block, 'AT2', 1);
|
||||
break;
|
||||
case 'FROM_END':
|
||||
at2 = Python.getAdjustedInt(block, 'AT2', 0, true);
|
||||
at2 = pythonGenerator.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';
|
||||
pythonGenerator.definitions_['import_sys'] = 'import sys';
|
||||
at2 += ' or sys.maxsize';
|
||||
} else if (at2 === 0) {
|
||||
at2 = '';
|
||||
@@ -207,10 +210,10 @@ Python.forBlock['text_getSubstring'] = function(block) {
|
||||
throw Error('Unhandled option (text_getSubstring)');
|
||||
}
|
||||
const code = text + '[' + at1 + ' : ' + at2 + ']';
|
||||
return [code, Python.ORDER_MEMBER];
|
||||
return [code, Order.MEMBER];
|
||||
};
|
||||
|
||||
Python.forBlock['text_changeCase'] = function(block) {
|
||||
pythonGenerator.forBlock['text_changeCase'] = function(block) {
|
||||
// Change capitalization.
|
||||
const OPERATORS = {
|
||||
'UPPERCASE': '.upper()',
|
||||
@@ -218,12 +221,12 @@ Python.forBlock['text_changeCase'] = function(block) {
|
||||
'TITLECASE': '.title()'
|
||||
};
|
||||
const operator = OPERATORS[block.getFieldValue('CASE')];
|
||||
const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || "''";
|
||||
const text = pythonGenerator.valueToCode(block, 'TEXT', Order.MEMBER) || "''";
|
||||
const code = text + operator;
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['text_trim'] = function(block) {
|
||||
pythonGenerator.forBlock['text_trim'] = function(block) {
|
||||
// Trim spaces.
|
||||
const OPERATORS = {
|
||||
'LEFT': '.lstrip()',
|
||||
@@ -231,21 +234,21 @@ Python.forBlock['text_trim'] = function(block) {
|
||||
'BOTH': '.strip()'
|
||||
};
|
||||
const operator = OPERATORS[block.getFieldValue('MODE')];
|
||||
const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || "''";
|
||||
const text = pythonGenerator.valueToCode(block, 'TEXT', Order.MEMBER) || "''";
|
||||
const code = text + operator;
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['text_print'] = function(block) {
|
||||
pythonGenerator.forBlock['text_print'] = function(block) {
|
||||
// Print statement.
|
||||
const msg = Python.valueToCode(block, 'TEXT', Python.ORDER_NONE) || "''";
|
||||
const msg = pythonGenerator.valueToCode(block, 'TEXT', Order.NONE) || "''";
|
||||
return 'print(' + msg + ')\n';
|
||||
};
|
||||
|
||||
Python.forBlock['text_prompt_ext'] = function(block) {
|
||||
pythonGenerator.forBlock['text_prompt_ext'] = function(block) {
|
||||
// Prompt function.
|
||||
const functionName = Python.provideFunction_('text_prompt', `
|
||||
def ${Python.FUNCTION_NAME_PLACEHOLDER_}(msg):
|
||||
const functionName = pythonGenerator.provideFunction_('text_prompt', `
|
||||
def ${pythonGenerator.FUNCTION_NAME_PLACEHOLDER_}(msg):
|
||||
try:
|
||||
return raw_input(msg)
|
||||
except NameError:
|
||||
@@ -254,38 +257,39 @@ def ${Python.FUNCTION_NAME_PLACEHOLDER_}(msg):
|
||||
let msg;
|
||||
if (block.getField('TEXT')) {
|
||||
// Internal message.
|
||||
msg = Python.quote_(block.getFieldValue('TEXT'));
|
||||
msg = pythonGenerator.quote_(block.getFieldValue('TEXT'));
|
||||
} else {
|
||||
// External message.
|
||||
msg = Python.valueToCode(block, 'TEXT', Python.ORDER_NONE) || "''";
|
||||
msg = pythonGenerator.valueToCode(block, 'TEXT', Order.NONE) || "''";
|
||||
}
|
||||
let code = functionName + '(' + msg + ')';
|
||||
const toNumber = block.getFieldValue('TYPE') === 'NUMBER';
|
||||
if (toNumber) {
|
||||
code = 'float(' + code + ')';
|
||||
}
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['text_prompt'] = Python.forBlock['text_prompt_ext'];
|
||||
pythonGenerator.forBlock['text_prompt'] =
|
||||
pythonGenerator.forBlock['text_prompt_ext'];
|
||||
|
||||
Python.forBlock['text_count'] = function(block) {
|
||||
const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || "''";
|
||||
const sub = Python.valueToCode(block, 'SUB', Python.ORDER_NONE) || "''";
|
||||
pythonGenerator.forBlock['text_count'] = function(block) {
|
||||
const text = pythonGenerator.valueToCode(block, 'TEXT', Order.MEMBER) || "''";
|
||||
const sub = pythonGenerator.valueToCode(block, 'SUB', Order.NONE) || "''";
|
||||
const code = text + '.count(' + sub + ')';
|
||||
return [code, Python.ORDER_FUNCTION_CALL];
|
||||
return [code, Order.FUNCTION_CALL];
|
||||
};
|
||||
|
||||
Python.forBlock['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) || "''";
|
||||
pythonGenerator.forBlock['text_replace'] = function(block) {
|
||||
const text = pythonGenerator.valueToCode(block, 'TEXT', Order.MEMBER) || "''";
|
||||
const from = pythonGenerator.valueToCode(block, 'FROM', Order.NONE) || "''";
|
||||
const to = pythonGenerator.valueToCode(block, 'TO', Order.NONE) || "''";
|
||||
const code = text + '.replace(' + from + ', ' + to + ')';
|
||||
return [code, Python.ORDER_MEMBER];
|
||||
return [code, Order.MEMBER];
|
||||
};
|
||||
|
||||
Python.forBlock['text_reverse'] = function(block) {
|
||||
const text = Python.valueToCode(block, 'TEXT', Python.ORDER_MEMBER) || "''";
|
||||
pythonGenerator.forBlock['text_reverse'] = function(block) {
|
||||
const text = pythonGenerator.valueToCode(block, 'TEXT', Order.MEMBER) || "''";
|
||||
const code = text + '[::-1]';
|
||||
return [code, Python.ORDER_MEMBER];
|
||||
return [code, Order.MEMBER];
|
||||
};
|
||||
|
||||
@@ -12,21 +12,23 @@ import * as goog from '../../closure/goog/goog.js';
|
||||
goog.declareModuleId('Blockly.Python.variables');
|
||||
|
||||
import {NameType} from '../../core/names.js';
|
||||
import {pythonGenerator as Python} from '../python.js';
|
||||
import {pythonGenerator, Order} from '../python.js';
|
||||
|
||||
|
||||
Python.forBlock['variables_get'] = function(block) {
|
||||
pythonGenerator.forBlock['variables_get'] = function(block) {
|
||||
// Variable getter.
|
||||
const code =
|
||||
Python.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
|
||||
return [code, Python.ORDER_ATOMIC];
|
||||
pythonGenerator.nameDB_.getName(
|
||||
block.getFieldValue('VAR'), NameType.VARIABLE);
|
||||
return [code, Order.ATOMIC];
|
||||
};
|
||||
|
||||
Python.forBlock['variables_set'] = function(block) {
|
||||
pythonGenerator.forBlock['variables_set'] = function(block) {
|
||||
// Variable setter.
|
||||
const argument0 =
|
||||
Python.valueToCode(block, 'VALUE', Python.ORDER_NONE) || '0';
|
||||
pythonGenerator.valueToCode(block, 'VALUE', Order.NONE) || '0';
|
||||
const varName =
|
||||
Python.nameDB_.getName(block.getFieldValue('VAR'), NameType.VARIABLE);
|
||||
pythonGenerator.nameDB_.getName(
|
||||
block.getFieldValue('VAR'), NameType.VARIABLE);
|
||||
return varName + ' = ' + argument0 + '\n';
|
||||
};
|
||||
|
||||
@@ -11,10 +11,10 @@
|
||||
import * as goog from '../../closure/goog/goog.js';
|
||||
goog.declareModuleId('Blockly.Python.variablesDynamic');
|
||||
|
||||
import {pythonGenerator as Python} from '../python.js';
|
||||
import {pythonGenerator} from '../python.js';
|
||||
import './variables.js';
|
||||
|
||||
|
||||
// Python is dynamically typed.
|
||||
Python.forBlock['variables_get_dynamic'] = Python.forBlock['variables_get'];
|
||||
Python.forBlock['variables_set_dynamic'] = Python.forBlock['variables_set'];
|
||||
// pythonGenerator is dynamically typed.
|
||||
pythonGenerator.forBlock['variables_get_dynamic'] = pythonGenerator.forBlock['variables_get'];
|
||||
pythonGenerator.forBlock['variables_set_dynamic'] = pythonGenerator.forBlock['variables_set'];
|
||||
|
||||
Reference in New Issue
Block a user