mirror of
https://github.com/google/blockly.git
synced 2026-01-04 15:40:08 +01:00
* fix: convert files to typescript * fix: add alias for AnyDuringMigration so that tsc will run * chore: format * chore: enable ts for the clang-format workflow (#6233) * chore: Restore @fileoverview comment locations (#6237) * chore: add declareModuleId (#6238) * fix: Revert comment change to app_controller.js (#6241) * fix: Add missing import goog statements (#6240) I've added the import statement immediately before the goog.declareModuleId calls that depend on it. There is an argument to be made that we should put the import statement in their normal place amongst any other imports, and move the declareModuleId statement to below the double blank line below the imports, but as these are so tightly coupled, replace the previous goog.module calls, and will both be deleted at the same time once the transition to TypeScript is fully complete I think it's fine (and certainly much easier) to do it this way. * chore: Fix whitespace (#6243) * fix: Remove spurious blank lines Remove extraneous blank lines introduced by deletion of 'use strict'; pragmas. Also fix the location of the goog.declareModuleId call in core/utils/array.ts. * fix: Add missing double-blank-line before body of modules Our convention is to have two blank lines between the imports (or module ID, if there are no imports) and the beginning of the body of the module. Enforce this. * fix: one addition format error for PR #6243 * fix(build): Skip npm prepare when running in CI (#6244) Have npm prepare do nothing when running in CI. We don't need to do any building, because npm test will build everything needed in the workflows in which it is run, and we don't want to build anything in other workflows because a tsc error would prevent those workflows from completing. * fix: re-add `@package` annotations as `@internal` annotations (#6232) * fix: add ~70% of internal attributes * fix: work on manually adding more @internal annotations * fix: add more manual internal annotations * fix: rename package typos to internal * fix: final manual fixes for internal annotations * chore: format * chore: make unnecessary multiline jsdoc a single line * fix: fix internal tags in serialization exceptions * fix: tsc errors picked up from develop (#6224) * fix: relative path for deprecation utils * fix: checking if properties exist in svg_math * fix: set all timeout PIDs to AnyDuringMigration * fix: make nullability errors explicity in block drag surface * fix: make null check in events_block_change explicit * fix: make getEventWorkspace_ internal so we can access it from CommentCreateDeleteHelper * fix: rename DIV -> containerDiv in tooltip * fix: ignore backwards compat check in category * fix: set block styles to AnyDuringMigration * fix: type typo in KeyboardShortcut * fix: constants name in row measurables * fix: typecast in mutator * fix: populateProcedures type of flattened array * fix: ignore errors related to workspace comment deserialization * chore: format files * fix: renaming imports missing file extensions * fix: remove check for sound.play * fix: temporarily remove bad requireType. All `export type` statements are stripped when tsc is run. This means that when we attempt to require BlockDefinition from the block files, we get an error because it does not exist. We decided to temporarily remove the require, because this will no longer be a problem when we conver the blocks to typescript, and everything gets compiled together. * fix: bad jsdoc in array * fix: silence missing property errors Closure was complaining about inexistant properties, but they actually do exist, they're just not being transpiled by tsc in a way that closure understands. I.E. if things are initialized in a function called by the constructor, rather than in a class field or in the custructor itself, closure would error. It would also error on enums, because they are transpiled to a weird IIFE. * fix: context menu action handler not knowing the type of this. this: TypeX information gets stripped when tsc is run, so closure could not know that this was not global. Fixed this by reorganizing to use the option object directly instead of passing it to onAction to be bound to this. * fix: readd getDeveloperVars checks (should not be part of migration) This was found because ALL_DEVELOPER_VARS_WARNINGS_BY_BLOCK_TYPE was no longer being accessed. * fix: silence closure errors about overriding supertype props We propertly define the overrides in typescript, but these get removed from the compiled output, so closure doesn't know they exist. * fix: silence globalThis errors this: TypeX annotations get stripped from the compiled output, so closure can't know that we're accessing the correct things. However, typescript makes sure that this always has the correct properties, so silencing this should be fine. * fix: bad jsdoc name * chore: attempt compiling with blockly.js * fix: attempt moving the import statement above the namespace line * chore: add todo comments to block def files * chore: remove todo from context menu * chore: add comments abotu disabled errors * chore: move comments back to their correct positions (#6249) * fix: work on fixing comments * chore: finish moving all comments * chore: format * chore: move some other messed up comments * chore: format * fix: Correct enum formatting, use merged `namespace`s for types that are class static members (#6246) * fix: formatting of enum KeyCodes * fix: Use merged namespace for ContextMenuRegistry static types - Create a namespace to be merged with the ContextMenuRegistry class containing the types that were formerly declared as static properties on that class. - Use type aliases to export them individually as well, for compatibility with the changes made by MigranTS (and/or @gonfunko) to how other modules in core/ now import these types. - Update renamings.json5 to reflect the availability of the direct exports for modules that import this module directly (though they are not available to, and will not be used by, code that imports only via blockly.js/blockly.ts.) * fix: Use merged namespace for Input.Align - Create a merged namespace for the Input.Align enum. - Use type/const aliases to export it as Input too. - Update renamings.json5 to reflect the availability of the direct export. * fix: Use merged namespace for Names.NameType - Create a merged namespace for the Names.NameType enum. - Use type/const aliases to export it as NameType too. - Update renamings.json5 to reflect the availability of the direct export. (This ought to have happened in an earlier version as it was already available by both routes.) * chore: Fix minor issues for PR #6246 - Use `Align` instead of `Input.Align` where possible. * fix(build): Suppress irrelevant JSC_UNUSED_LOCAL_ASSIGNMENT errors tsc generates code for merged namespaces that looks like: (function (ClassName) { let EnumName; (function (EnumName) { EnumName[EnumNameAlign["v1"] = 0] = "v1"; // etc. })(EnumName = ClassName.EnumName || (ClassName.EnumName = {})); })(ClassName || (ClassName = {})); and Closure Compiler complains about the fact that the EnumName let binding is initialised but never used. (It exists so that any other code that was in the namespace could see the enum.) Suppress this message, since it is not actionable and lint and/or tsc should tell us if we have actual unused variables in our .ts files. * chore(build): Suppress spurious warnings from closure-make-deps (#6253) A little bit of an ugly hack, but it works: pipe stderr through grep -v to suppress error output starting with "WARNING in". * fix: remaining enums that weren't properly exported (#6251) * fix: remaining enums that weren't properly exported * chore: format * fix: add enum value exports * chore: format * fix: properly export interfaces that were typedefs (#6250) * fix: properly export interfaces that were typedefs * fix: allowCollsion -> allowCollision * fix: convert unconverted enums * fix: enums that were/are instance properties * fix: revert changes to property enums * fix: renamed protected parameter properties (#6252) * fix: bad protected parameter properties * chore:format * fix: gesture constructor * fix: overridden properties that were renamed * refactor: Migrate `blockly.js` to TypeScript (#6261) * chore: Apply changes to blockly.js to blockly.ts * fix: Build using core/blockly.ts instead of .js Compiles and runs in compressed mode correctly! * fix(build): Don't depend on execSync running bash (#6262) For some reason on Github CI servers execSync uses /bin/sh, which is (on Ubuntu) dash rather than bash, and does not understand the pipefail option. So remove the grep pipe on stderr and just discard all error output at all. This is not ideal as errors in test deps will go unreported AND not even cause test failure, but it's not clear that it's worth investing more time to fix this at the moment. * chore: use `import type` where possible (#6279) * chore: automatically change imports to import types * chore: revert changes that actually need to be imports * chore: format * chore: add more import type statements based on importsNotUsedAsValues * chore: fix tsconfig * chore: add link to compiler issue * fix: add type information to blockly options (#6283) * fix: add type information to blockly options * chore: format * chore: remove erroneous comment * fix: bugs revealed by getting the built output working (#6282) * fix: types of compose and decompose in block * fix: workspace naming in toolbox * chore: add jsdoc * chore: restore registry comments to better positions * chore: pr comments' * fix(variables): Revert inadvertent change to allDeveloperVariables (#6290) It appears that a function call got modified incorrectly (probably in an effort to fix a typing issue). This fix trivially reverts the line in question to match the original JS version from develop. This causes the generator tests to pass. * fix: circular dependencies (#6281) * chore: fix circular dependencies w/ static workspace funcs * remove preserved imports that aren't currently necessary (probably) * fix circular dependency with workspaces and block using stub * fix dependency between variables and xml by moving function to utils * add stub for trashcan as well * fix line endings from rebase * fix goog/base order * add trashcan patch * fix: types of compose and decompose in block * fix: workspace naming in toolbox * chore: add jsdoc * chore: restore registry comments to better positions * chore: remove implementations in goog.js * chore: fix types of stubs * chore: remove added AnyDuringMigration casts * chore: remove modifications to xml and variables * chore: format * chore: remove event requirements in workspace comments * chore: fix circular dependency with xml and workspace comments * fixup remove ContextMenu import * chore: fix dependency between mutator and workspace * chore: break circular dependency between names and procedures * chore: get tests to run? * chore: pr comments' * chore: fix stubbing field registry fromJson * chore: fix spying on fire * chore: fix stubbing parts of connection checker * chore: fix stubbing dialog * chore: fix stubbing style * chore: fix spying on duplicate * chore: fix stubbing variables * chore: fix stubbing copy * chore: fix stubbing in workspace * chore: remove unnecessary stubs * chore: fix formatting * chore: fix other formatting * chore: add backwards compatible static properties to workspace * chore: move static type properties * chore: move and comment stubs * chore: add newlines at EOF * chore: improve errors for monkey patched functions * chore: update comment with a pointer to the doc * chore: update comment with a pointer to the doc * chore: format * chore: revert changes to playground used for testing (#6292) * chore: get mocha tests to pass. (#6291) * chore: fix undo and empty code blocks * chore: skip IE test * chore: fix gesture test * chore: fix replace message references test * chore: fix string table interpolation * chore: skip getById tests * chore: fix field tests * chore: fix console errors by making workspace nullable * chore: format * chore: fix definition overwrite warning * chore: update metadata * chore: temporarily modify the the advanced compile test * chore: fix gestures by fixing test instead Co-authored-by: Neil Fraser <fraser@google.com> Co-authored-by: Christopher Allen <cpcallen+git@google.com>
540 lines
19 KiB
TypeScript
540 lines
19 KiB
TypeScript
/**
|
|
* @license
|
|
* Copyright 2012 Google LLC
|
|
* SPDX-License-Identifier: Apache-2.0
|
|
*/
|
|
|
|
/**
|
|
* @fileoverview Utility functions for generating executable code from
|
|
* Blockly code.
|
|
*/
|
|
|
|
/**
|
|
* Utility functions for generating executable code from
|
|
* Blockly code.
|
|
* @class
|
|
*/
|
|
import * as goog from '../closure/goog/goog.js';
|
|
goog.declareModuleId('Blockly.Generator');
|
|
|
|
import type {Block} from './block.js';
|
|
import * as common from './common.js';
|
|
import {Names, NameType} from './names.js';
|
|
import * as deprecation from './utils/deprecation.js';
|
|
import type {Workspace} from './workspace.js';
|
|
|
|
|
|
/**
|
|
* Class for a code generator that translates the blocks into a language.
|
|
* @unrestricted
|
|
* @alias Blockly.Generator
|
|
*/
|
|
export class Generator {
|
|
name_: AnyDuringMigration;
|
|
|
|
/**
|
|
* This is used as a placeholder in functions defined using
|
|
* Generator.provideFunction_. It must not be legal code that could
|
|
* legitimately appear in a function definition (or comment), and it must
|
|
* not confuse the regular expression parser.
|
|
*/
|
|
protected FUNCTION_NAME_PLACEHOLDER_ = '{leCUI8hutHZI4480Dc}';
|
|
FUNCTION_NAME_PLACEHOLDER_REGEXP_: AnyDuringMigration;
|
|
|
|
/**
|
|
* Arbitrary code to inject into locations that risk causing infinite loops.
|
|
* Any instances of '%1' will be replaced by the block ID that failed.
|
|
* E.g. ' checkTimeout(%1);\n'
|
|
*/
|
|
INFINITE_LOOP_TRAP: string|null = null;
|
|
|
|
/**
|
|
* Arbitrary code to inject before every statement.
|
|
* Any instances of '%1' will be replaced by the block ID of the statement.
|
|
* E.g. 'highlight(%1);\n'
|
|
*/
|
|
STATEMENT_PREFIX: string|null = null;
|
|
|
|
/**
|
|
* Arbitrary code to inject after every statement.
|
|
* Any instances of '%1' will be replaced by the block ID of the statement.
|
|
* E.g. 'highlight(%1);\n'
|
|
*/
|
|
STATEMENT_SUFFIX: string|null = null;
|
|
|
|
/**
|
|
* The method of indenting. Defaults to two spaces, but language generators
|
|
* may override this to increase indent or change to tabs.
|
|
*/
|
|
INDENT = ' ';
|
|
|
|
/**
|
|
* Maximum length for a comment before wrapping. Does not account for
|
|
* indenting level.
|
|
*/
|
|
COMMENT_WRAP = 60;
|
|
|
|
/** List of outer-inner pairings that do NOT require parentheses. */
|
|
ORDER_OVERRIDES: number[][] = [];
|
|
|
|
/**
|
|
* Whether the init method has been called.
|
|
* Generators that set this flag to false after creation and true in init
|
|
* will cause blockToCode to emit a warning if the generator has not been
|
|
* initialized. If this flag is untouched, it will have no effect.
|
|
*/
|
|
isInitialized: boolean|null = null;
|
|
|
|
/** Comma-separated list of reserved words. */
|
|
protected RESERVED_WORDS_ = '';
|
|
|
|
/** A dictionary of definitions to be printed before the code. */
|
|
protected definitions_?: AnyDuringMigration = undefined;
|
|
|
|
/**
|
|
* A dictionary mapping desired function names in definitions_ to actual
|
|
* function names (to avoid collisions with user functions).
|
|
*/
|
|
protected functionNames_?: AnyDuringMigration = undefined;
|
|
|
|
/** A database of variable and procedure names. */
|
|
protected nameDB_?: Names = undefined;
|
|
|
|
/** @param name Language name of this generator. */
|
|
constructor(name: string) {
|
|
this.name_ = name;
|
|
|
|
this.FUNCTION_NAME_PLACEHOLDER_REGEXP_ =
|
|
new RegExp(this.FUNCTION_NAME_PLACEHOLDER_, 'g');
|
|
}
|
|
|
|
/**
|
|
* Generate code for all blocks in the workspace to the specified language.
|
|
* @param workspace Workspace to generate code from.
|
|
* @return Generated code.
|
|
*/
|
|
workspaceToCode(workspace?: Workspace): string {
|
|
if (!workspace) {
|
|
// Backwards compatibility from before there could be multiple workspaces.
|
|
console.warn(
|
|
'No workspace specified in workspaceToCode call. Guessing.');
|
|
workspace = common.getMainWorkspace();
|
|
}
|
|
let code = [];
|
|
this.init(workspace);
|
|
const blocks = workspace.getTopBlocks(true);
|
|
for (let i = 0, block; block = blocks[i]; i++) {
|
|
let line = this.blockToCode(block);
|
|
if (Array.isArray(line)) {
|
|
// Value blocks return tuples of code and operator order.
|
|
// Top-level blocks don't care about operator order.
|
|
line = line[0];
|
|
}
|
|
if (line) {
|
|
if (block.outputConnection) {
|
|
// This block is a naked value. Ask the language's code generator if
|
|
// it wants to append a semicolon, or something.
|
|
// AnyDuringMigration because: Argument of type 'string | any[]' is
|
|
// not assignable to parameter of type 'string'.
|
|
line = this.scrubNakedValue(line as AnyDuringMigration);
|
|
if (this.STATEMENT_PREFIX && !block.suppressPrefixSuffix) {
|
|
line = this.injectId(this.STATEMENT_PREFIX, block) + line;
|
|
}
|
|
if (this.STATEMENT_SUFFIX && !block.suppressPrefixSuffix) {
|
|
line = line + this.injectId(this.STATEMENT_SUFFIX, block);
|
|
}
|
|
}
|
|
code.push(line);
|
|
}
|
|
}
|
|
// AnyDuringMigration because: Type 'string' is not assignable to type
|
|
// 'any[]'.
|
|
// Blank line between each section.
|
|
code = code.join('\n') as AnyDuringMigration;
|
|
// AnyDuringMigration because: Argument of type 'any[]' is not assignable
|
|
// to parameter of type 'string'. AnyDuringMigration because: Type 'string'
|
|
// is not assignable to type 'any[]'.
|
|
code = this.finish(code as AnyDuringMigration) as AnyDuringMigration;
|
|
// Final scrubbing of whitespace.
|
|
// AnyDuringMigration because: Property 'replace' does not exist on type
|
|
// 'any[]'.
|
|
code = (code as AnyDuringMigration).replace(/^\s+\n/, '');
|
|
code = code.replace(/\n\s+$/, '\n');
|
|
code = code.replace(/[ \t]+\n/g, '\n');
|
|
return code;
|
|
}
|
|
|
|
// The following are some helpful functions which can be used by multiple
|
|
|
|
// languages.
|
|
|
|
/**
|
|
* Prepend a common prefix onto each line of code.
|
|
* Intended for indenting code or adding comment markers.
|
|
* @param text The lines of code.
|
|
* @param prefix The common prefix.
|
|
* @return The prefixed lines of code.
|
|
*/
|
|
prefixLines(text: string, prefix: string): string {
|
|
return prefix + text.replace(/(?!\n$)\n/g, '\n' + prefix);
|
|
}
|
|
|
|
/**
|
|
* Recursively spider a tree of blocks, returning all their comments.
|
|
* @param block The block from which to start spidering.
|
|
* @return Concatenated list of comments.
|
|
*/
|
|
allNestedComments(block: Block): string {
|
|
const comments = [];
|
|
const blocks = block.getDescendants(true);
|
|
for (let i = 0; i < blocks.length; i++) {
|
|
const comment = blocks[i].getCommentText();
|
|
if (comment) {
|
|
comments.push(comment);
|
|
}
|
|
}
|
|
// Append an empty string to create a trailing line break when joined.
|
|
if (comments.length) {
|
|
comments.push('');
|
|
}
|
|
return comments.join('\n');
|
|
}
|
|
|
|
/**
|
|
* Generate code for the specified block (and attached blocks).
|
|
* The generator must be initialized before calling this function.
|
|
* @param block The block to generate code for.
|
|
* @param opt_thisOnly True to generate code for only this statement.
|
|
* @return For statement blocks, the generated code.
|
|
* For value blocks, an array containing the generated code and an
|
|
* operator order value. Returns '' if block is null.
|
|
*/
|
|
blockToCode(block: Block|null, opt_thisOnly?: boolean): string
|
|
|AnyDuringMigration[] {
|
|
if (this.isInitialized === false) {
|
|
console.warn(
|
|
'Generator init was not called before blockToCode was called.');
|
|
}
|
|
if (!block) {
|
|
return '';
|
|
}
|
|
if (!block.isEnabled()) {
|
|
// Skip past this block if it is disabled.
|
|
return opt_thisOnly ? '' : this.blockToCode(block.getNextBlock());
|
|
}
|
|
if (block.isInsertionMarker()) {
|
|
// Skip past insertion markers.
|
|
return opt_thisOnly ? '' : this.blockToCode(block.getChildren(false)[0]);
|
|
}
|
|
|
|
const func = (this as AnyDuringMigration)[block.type];
|
|
if (typeof func !== 'function') {
|
|
throw Error(
|
|
'Language "' + this.name_ + '" does not know how to generate ' +
|
|
'code for block type "' + block.type + '".');
|
|
}
|
|
// First argument to func.call is the value of 'this' in the generator.
|
|
// Prior to 24 September 2013 'this' was the only way to access the block.
|
|
// The current preferred method of accessing the block is through the second
|
|
// argument to func.call, which becomes the first parameter to the
|
|
// generator.
|
|
let code = func.call(block, block);
|
|
if (Array.isArray(code)) {
|
|
// Value blocks return tuples of code and operator order.
|
|
if (!block.outputConnection) {
|
|
throw TypeError('Expecting string from statement block: ' + block.type);
|
|
}
|
|
return [this.scrub_(block, code[0], opt_thisOnly), code[1]];
|
|
} else if (typeof code === 'string') {
|
|
if (this.STATEMENT_PREFIX && !block.suppressPrefixSuffix) {
|
|
code = this.injectId(this.STATEMENT_PREFIX, block) + code;
|
|
}
|
|
if (this.STATEMENT_SUFFIX && !block.suppressPrefixSuffix) {
|
|
code = code + this.injectId(this.STATEMENT_SUFFIX, block);
|
|
}
|
|
return this.scrub_(block, code, opt_thisOnly);
|
|
} else if (code === null) {
|
|
// Block has handled code generation itself.
|
|
return '';
|
|
}
|
|
throw SyntaxError('Invalid code generated: ' + code);
|
|
}
|
|
|
|
/**
|
|
* Generate code representing the specified value input.
|
|
* @param block The block containing the input.
|
|
* @param name The name of the input.
|
|
* @param outerOrder The maximum binding strength (minimum order value) of any
|
|
* operators adjacent to "block".
|
|
* @return Generated code or '' if no blocks are connected or the specified
|
|
* input does not exist.
|
|
*/
|
|
valueToCode(block: Block, name: string, outerOrder: number): string {
|
|
if (isNaN(outerOrder)) {
|
|
throw TypeError('Expecting valid order from block: ' + block.type);
|
|
}
|
|
const targetBlock = block.getInputTargetBlock(name);
|
|
if (!targetBlock) {
|
|
return '';
|
|
}
|
|
const tuple = this.blockToCode(targetBlock);
|
|
if (tuple === '') {
|
|
// Disabled block.
|
|
return '';
|
|
}
|
|
// Value blocks must return code and order of operations info.
|
|
// Statement blocks must only return code.
|
|
if (!Array.isArray(tuple)) {
|
|
throw TypeError('Expecting tuple from value block: ' + targetBlock.type);
|
|
}
|
|
let code = tuple[0];
|
|
const innerOrder = tuple[1];
|
|
if (isNaN(innerOrder)) {
|
|
throw TypeError(
|
|
'Expecting valid order from value block: ' + targetBlock.type);
|
|
}
|
|
if (!code) {
|
|
return '';
|
|
}
|
|
|
|
// Add parentheses if needed.
|
|
let parensNeeded = false;
|
|
const outerOrderClass = Math.floor(outerOrder);
|
|
const innerOrderClass = Math.floor(innerOrder);
|
|
if (outerOrderClass <= innerOrderClass) {
|
|
if (outerOrderClass === innerOrderClass &&
|
|
(outerOrderClass === 0 || outerOrderClass === 99)) {
|
|
// Don't generate parens around NONE-NONE and ATOMIC-ATOMIC pairs.
|
|
// 0 is the atomic order, 99 is the none order. No parentheses needed.
|
|
// In all known languages multiple such code blocks are not order
|
|
// sensitive. In fact in Python ('a' 'b') 'c' would fail.
|
|
} else {
|
|
// The operators outside this code are stronger than the operators
|
|
// inside this code. To prevent the code from being pulled apart,
|
|
// wrap the code in parentheses.
|
|
parensNeeded = true;
|
|
// Check for special exceptions.
|
|
for (let i = 0; i < this.ORDER_OVERRIDES.length; i++) {
|
|
if (this.ORDER_OVERRIDES[i][0] === outerOrder &&
|
|
this.ORDER_OVERRIDES[i][1] === innerOrder) {
|
|
parensNeeded = false;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (parensNeeded) {
|
|
// Technically, this should be handled on a language-by-language basis.
|
|
// However all known (sane) languages use parentheses for grouping.
|
|
code = '(' + code + ')';
|
|
}
|
|
return code;
|
|
}
|
|
|
|
/**
|
|
* Generate a code string representing the blocks attached to the named
|
|
* statement input. Indent the code.
|
|
* This is mainly used in generators. When trying to generate code to evaluate
|
|
* look at using workspaceToCode or blockToCode.
|
|
* @param block The block containing the input.
|
|
* @param name The name of the input.
|
|
* @return Generated code or '' if no blocks are connected.
|
|
*/
|
|
statementToCode(block: Block, name: string): string {
|
|
const targetBlock = block.getInputTargetBlock(name);
|
|
let code = this.blockToCode(targetBlock);
|
|
// Value blocks must return code and order of operations info.
|
|
// Statement blocks must only return code.
|
|
if (typeof code !== 'string') {
|
|
throw TypeError(
|
|
'Expecting code from statement block: ' +
|
|
(targetBlock && targetBlock.type));
|
|
}
|
|
if (code) {
|
|
code = this.prefixLines((code), this.INDENT);
|
|
}
|
|
return code;
|
|
}
|
|
|
|
/**
|
|
* Add an infinite loop trap to the contents of a loop.
|
|
* Add statement suffix at the start of the loop block (right after the loop
|
|
* statement executes), and a statement prefix to the end of the loop block
|
|
* (right before the loop statement executes).
|
|
* @param branch Code for loop contents.
|
|
* @param block Enclosing block.
|
|
* @return Loop contents, with infinite loop trap added.
|
|
*/
|
|
addLoopTrap(branch: string, block: Block): string {
|
|
if (this.INFINITE_LOOP_TRAP) {
|
|
branch = this.prefixLines(
|
|
this.injectId(this.INFINITE_LOOP_TRAP, block), this.INDENT) +
|
|
branch;
|
|
}
|
|
if (this.STATEMENT_SUFFIX && !block.suppressPrefixSuffix) {
|
|
branch = this.prefixLines(
|
|
this.injectId(this.STATEMENT_SUFFIX, block), this.INDENT) +
|
|
branch;
|
|
}
|
|
if (this.STATEMENT_PREFIX && !block.suppressPrefixSuffix) {
|
|
branch = branch +
|
|
this.prefixLines(
|
|
this.injectId(this.STATEMENT_PREFIX, block), this.INDENT);
|
|
}
|
|
return branch;
|
|
}
|
|
|
|
/**
|
|
* Inject a block ID into a message to replace '%1'.
|
|
* Used for STATEMENT_PREFIX, STATEMENT_SUFFIX, and INFINITE_LOOP_TRAP.
|
|
* @param msg Code snippet with '%1'.
|
|
* @param block Block which has an ID.
|
|
* @return Code snippet with ID.
|
|
*/
|
|
injectId(msg: string, block: Block): string {
|
|
const id = block.id.replace(/\$/g, '$$$$'); // Issue 251.
|
|
return msg.replace(/%1/g, '\'' + id + '\'');
|
|
}
|
|
|
|
/**
|
|
* Add one or more words to the list of reserved words for this language.
|
|
* @param words Comma-separated list of words to add to the list.
|
|
* No spaces. Duplicates are ok.
|
|
*/
|
|
addReservedWords(words: string) {
|
|
this.RESERVED_WORDS_ += words + ',';
|
|
}
|
|
|
|
/**
|
|
* Define a developer-defined function (not a user-defined procedure) to be
|
|
* included in the generated code. Used for creating private helper
|
|
* functions. The first time this is called with a given desiredName, the code
|
|
* is saved and an actual name is generated. Subsequent calls with the same
|
|
* desiredName have no effect but have the same return value.
|
|
*
|
|
* It is up to the caller to make sure the same desiredName is not
|
|
* used for different helper functions (e.g. use "colourRandom" and
|
|
* "listRandom", not "random"). There is no danger of colliding with reserved
|
|
* words, or user-defined variable or procedure names.
|
|
*
|
|
* The code gets output when Generator.finish() is called.
|
|
*
|
|
* @param desiredName The desired name of the function (e.g. mathIsPrime).
|
|
* @param code A list of statements or one multi-line code string. Use ' '
|
|
* for indents (they will be replaced).
|
|
* @return The actual name of the new function. This may differ from
|
|
* desiredName if the former has already been taken by the user.
|
|
*/
|
|
protected provideFunction_(desiredName: string, code: string[]|string):
|
|
string {
|
|
if (!this.definitions_[desiredName]) {
|
|
const functionName =
|
|
this.nameDB_!.getDistinctName(desiredName, NameType.PROCEDURE);
|
|
this.functionNames_[desiredName] = functionName;
|
|
if (Array.isArray(code)) {
|
|
code = code.join('\n');
|
|
}
|
|
let codeText = code.trim().replace(
|
|
this.FUNCTION_NAME_PLACEHOLDER_REGEXP_, functionName);
|
|
// Change all ' ' indents into the desired indent.
|
|
// To avoid an infinite loop of replacements, change all indents to '\0'
|
|
// character first, then replace them all with the indent.
|
|
// We are assuming that no provided functions contain a literal null char.
|
|
let oldCodeText;
|
|
while (oldCodeText !== codeText) {
|
|
oldCodeText = codeText;
|
|
codeText = codeText.replace(/^(( {2})*) {2}/gm, '$1\0');
|
|
}
|
|
codeText = codeText.replace(/\0/g, this.INDENT);
|
|
this.definitions_[desiredName] = codeText;
|
|
}
|
|
return this.functionNames_[desiredName];
|
|
}
|
|
|
|
/**
|
|
* Hook for code to run before code generation starts.
|
|
* Subclasses may override this, e.g. to initialise the database of variable
|
|
* names.
|
|
* @param _workspace Workspace to generate code from.
|
|
*/
|
|
init(_workspace: Workspace) {
|
|
// Optionally override
|
|
// Create a dictionary of definitions to be printed before the code.
|
|
this.definitions_ = Object.create(null);
|
|
// Create a dictionary mapping desired developer-defined function names in
|
|
// definitions_ to actual function names (to avoid collisions with
|
|
// user-defined procedures).
|
|
this.functionNames_ = Object.create(null);
|
|
}
|
|
|
|
/**
|
|
* Common tasks for generating code from blocks. This is called from
|
|
* blockToCode and is called on every block, not just top level blocks.
|
|
* Subclasses may override this, e.g. to generate code for statements
|
|
* following the block, or to handle comments for the specified block and any
|
|
* connected value blocks.
|
|
* @param _block The current block.
|
|
* @param code The code created for this block.
|
|
* @param _opt_thisOnly True to generate code for only this statement.
|
|
* @return Code with comments and subsequent blocks added.
|
|
*/
|
|
protected scrub_(_block: Block, code: string, _opt_thisOnly?: boolean):
|
|
string {
|
|
// Optionally override
|
|
return code;
|
|
}
|
|
|
|
/**
|
|
* Hook for code to run at end of code generation.
|
|
* Subclasses may override this, e.g. to prepend the generated code with
|
|
* import statements or variable definitions.
|
|
* @param code Generated code.
|
|
* @return Completed code.
|
|
*/
|
|
finish(code: string): string {
|
|
// Optionally override
|
|
// Clean up temporary data.
|
|
delete this.definitions_;
|
|
delete this.functionNames_;
|
|
return code;
|
|
}
|
|
|
|
/**
|
|
* Naked values are top-level blocks with outputs that aren't plugged into
|
|
* anything.
|
|
* Subclasses may override this, e.g. if their language does not allow
|
|
* naked values.
|
|
* @param line Line of generated code.
|
|
* @return Legal line of code.
|
|
*/
|
|
scrubNakedValue(line: string): string {
|
|
// Optionally override
|
|
return line;
|
|
}
|
|
}
|
|
|
|
Object.defineProperties(Generator.prototype, {
|
|
/**
|
|
* A database of variable names.
|
|
* @name Blockly.Generator.prototype.variableDB_
|
|
* @deprecated 'variableDB_' was renamed to 'nameDB_' (May 2021).
|
|
* @suppress {checkTypes}
|
|
*/
|
|
// AnyDuringMigration because: Type 'Names | undefined' is not assignable to
|
|
// type 'PropertyDescriptor'.
|
|
variableDB_: ({
|
|
/** @return Name database. */
|
|
get(this: Generator): Names |
|
|
undefined {
|
|
deprecation.warn(
|
|
'variableDB_', 'May 2021', 'September 2022', 'nameDB_');
|
|
return this.nameDB_;
|
|
},
|
|
/** @param nameDb New name database. */
|
|
set(this: Generator, nameDb: Names|undefined) {
|
|
deprecation.warn('variableDB_', 'May 2021', 'September2022', 'nameDB_');
|
|
this.nameDB_ = nameDb;
|
|
},
|
|
}),
|
|
});
|