Class: CodeGenerator
Defined in: packages/blockly/core/generator.ts:40
Class for a code generator that translates the blocks into a language.
Properties index
| Property | Description |
|---|---|
| name_ | - |
| forBlock | A dictionary of block generator functions, keyed by block type. Each block generator function takes two parameters: |
| FUNCTION_NAME_PLACEHOLDER_ | This is used as a placeholder in functions defined using CodeGenerator.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. |
| FUNCTION_NAME_PLACEHOLDER_REGEXP_ | - |
| INFINITE_LOOP_TRAP | 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 |
| STATEMENT_PREFIX | 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_SUFFIX | 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 |
| INDENT | The method of indenting. Defaults to two spaces, but language generators may override this to increase indent or change to tabs. |
| COMMENT_WRAP | Maximum length for a comment before wrapping. Does not account for indenting level. |
| ORDER_OVERRIDES | List of outer-inner pairings that do NOT require parentheses. |
| isInitialized | 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. |
| RESERVED_WORDS_ | Comma-separated list of reserved words. |
| definitions_ | A dictionary of definitions to be printed before the code. |
| functionNames_ | A dictionary mapping desired function names in definitions_ to actual function names (to avoid collisions with user functions). |
| nameDB_ | A database of variable and procedure names. |
Methods index
| Method | Description |
|---|---|
| workspaceToCode | Generate code for all blocks in the workspace to the specified language. |
| prefixLines | Prepend a common prefix onto each line of code. Intended for indenting code or adding comment markers. |
| allNestedComments | Recursively spider a tree of blocks, returning all their comments. |
| blockToCode | Generate code for the specified block (and attached blocks). The generator must be initialized before calling this function. |
| valueToCode | Generate code representing the specified value input. |
| statementToCode | 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. |
| addLoopTrap | 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). |
| injectId | Inject a block ID into a message to replace '%1'. Used for STATEMENT_PREFIX, STATEMENT_SUFFIX, and INFINITE_LOOP_TRAP. |
| addReservedWords | Add one or more words to the list of reserved words for this language. |
| provideFunction_ | 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. |
| getVariableName | Gets a unique, legal name for a user-defined variable. Before calling this method, the nameDB_ property of the class must have been initialized already. This is typically done in the init function of the code generator class. |
| getProcedureName | Gets a unique, legal name for a user-defined procedure. Before calling this method, the nameDB_ property of the class must have been initialized already. This is typically done in the init function of the code generator class. |
| init | Hook for code to run before code generation starts. Subclasses may override this, e.g. to initialise the database of variable names. |
| scrub_ | 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. |
| finish | 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. |
| scrubNakedValue | 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. |
Constructors
Constructor
new CodeGenerator(name): CodeGenerator;
Defined in: packages/blockly/core/generator.ts:132
Parameters
| Parameter | Type | Description |
|---|---|---|
name | string | Language name of this generator. |
Returns
CodeGenerator
Properties
name_
name_: string;
Defined in: packages/blockly/core/generator.ts:41
forBlock
forBlock: Record<string, (block, generator) => [string, number] | string | null>;
Defined in: packages/blockly/core/generator.ts:58
A dictionary of block generator functions, keyed by block type. Each block generator function takes two parameters:
- the Block to generate code for, and
- the calling CodeGenerator (or subclass) instance, so the function can call methods defined below (e.g. blockToCode) or on the relevant subclass (e.g. JavascripGenerator),
and returns:
- a [code, precedence] tuple (for value/expression blocks), or
- a string containing the generated code (for statement blocks), or
- null if no code should be emitted for block.
FUNCTION_NAME_PLACEHOLDER_
FUNCTION_NAME_PLACEHOLDER_: string = '{leCUI8hutHZI4480Dc}';
Defined in: packages/blockly/core/generator.ts:69
This is used as a placeholder in functions defined using CodeGenerator.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.
FUNCTION_NAME_PLACEHOLDER_REGEXP_
FUNCTION_NAME_PLACEHOLDER_REGEXP_: RegExp;
Defined in: packages/blockly/core/generator.ts:70
INFINITE_LOOP_TRAP
INFINITE_LOOP_TRAP: string | null = null;
Defined in: packages/blockly/core/generator.ts:77
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
STATEMENT_PREFIX
STATEMENT_PREFIX: string | null = null;
Defined in: packages/blockly/core/generator.ts:84
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_SUFFIX
STATEMENT_SUFFIX: string | null = null;
Defined in: packages/blockly/core/generator.ts:91
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
INDENT
INDENT: string = ' ';
Defined in: packages/blockly/core/generator.ts:97
The method of indenting. Defaults to two spaces, but language generators may override this to increase indent or change to tabs.
COMMENT_WRAP
COMMENT_WRAP: number = 60;
Defined in: packages/blockly/core/generator.ts:103
Maximum length for a comment before wrapping. Does not account for indenting level.
ORDER_OVERRIDES
ORDER_OVERRIDES: number[][] = [];
Defined in: packages/blockly/core/generator.ts:106
List of outer-inner pairings that do NOT require parentheses.
isInitialized
isInitialized: boolean | null = null;
Defined in: packages/blockly/core/generator.ts:114
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.
RESERVED_WORDS_
protected RESERVED_WORDS_: string = '';
Defined in: packages/blockly/core/generator.ts:117
Comma-separated list of reserved words.
definitions_
protected definitions_: object;
Defined in: packages/blockly/core/generator.ts:120
A dictionary of definitions to be printed before the code.
Index Signature
[key: string]: string
functionNames_
protected functionNames_: object;
Defined in: packages/blockly/core/generator.ts:126
A dictionary mapping desired function names in definitions_ to actual function names (to avoid collisions with user functions).
Index Signature
[key: string]: string
nameDB_?
optional nameDB_?: Names = undefined;
Defined in: packages/blockly/core/generator.ts:129
A database of variable and procedure names.
Methods
workspaceToCode()
workspaceToCode(workspace?): string;
Defined in: packages/blockly/core/generator.ts:147
Generate code for all blocks in the workspace to the specified language.
Parameters
| Parameter | Type | Description |
|---|---|---|
workspace? | Workspace | Workspace to generate code from. |
Returns
string
Generated code.
prefixLines()
prefixLines(text, prefix): string;
Defined in: packages/blockly/core/generator.ts:198
Prepend a common prefix onto each line of code. Intended for indenting code or adding comment markers.
Parameters
| Parameter | Type | Description |
|---|---|---|
text | string | The lines of code. |
prefix | string | The common prefix. |
Returns
string
The prefixed lines of code.
allNestedComments()
allNestedComments(block): string;
Defined in: packages/blockly/core/generator.ts:208
Recursively spider a tree of blocks, returning all their comments.
Parameters
| Parameter | Type | Description |
|---|---|---|
block | Block | The block from which to start spidering. |
Returns
string
Concatenated list of comments.
blockToCode()
blockToCode(block, opt_thisOnly?): string | [string, number];
Defined in: packages/blockly/core/generator.ts:234
Generate code for the specified block (and attached blocks). The generator must be initialized before calling this function.
Parameters
| Parameter | Type | Description |
|---|---|---|
block | Block | null | The block to generate code for. |
opt_thisOnly? | boolean | True to generate code for only this statement. |
Returns
string | [string, number]
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.
valueToCode()
valueToCode(
block,
name,
outerOrder
): string;
Defined in: packages/blockly/core/generator.ts:300
Generate code representing the specified value input.
Parameters
| Parameter | Type | Description |
|---|---|---|
block | Block | The block containing the input. |
name | string | The name of the input. |
outerOrder | number | The maximum binding strength (minimum order value) of any operators adjacent to "block". |
Returns
string
Generated code or '' if no blocks are connected.
Throws
ReferenceError if the specified input does not exist.
statementToCode()
statementToCode(block, name): string;
Defined in: packages/blockly/core/generator.ts:385
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.
Parameters
| Parameter | Type | Description |
|---|---|---|
block | Block | The block containing the input. |
name | string | The name of the input. |
Returns
string
Generated code or '' if no blocks are connected.
Throws
ReferenceError if the specified input does not exist.
addLoopTrap()
addLoopTrap(branch, block): string;
Defined in: packages/blockly/core/generator.ts:415
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).
Parameters
| Parameter | Type | Description |
|---|---|---|
branch | string | Code for loop contents. |
block | Block | Enclosing block. |
Returns
string
Loop contents, with infinite loop trap added.
injectId()
injectId(msg, block): string;
Defined in: packages/blockly/core/generator.ts:449
Inject a block ID into a message to replace '%1'. Used for STATEMENT_PREFIX, STATEMENT_SUFFIX, and INFINITE_LOOP_TRAP.
Parameters
| Parameter | Type | Description |
|---|---|---|
msg | string | Code snippet with '%1'. |
block | Block | Block which has an ID. |
Returns
string
Code snippet with ID.
addReservedWords()
addReservedWords(words): void;
Defined in: packages/blockly/core/generator.ts:460
Add one or more words to the list of reserved words for this language.
Parameters
| Parameter | Type | Description |
|---|---|---|
words | string | Comma-separated list of words to add to the list. No spaces. Duplicates are ok. |
Returns
void
provideFunction_()
provideFunction_(desiredName, code): string;
Defined in: packages/blockly/core/generator.ts:484
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 CodeGenerator.finish() is called.
Parameters
| Parameter | Type | Description |
|---|---|---|
desiredName | string | The desired name of the function (e.g. mathIsPrime). |
code | string | string[] | A list of statements or one multi-line code string. Use ' ' for indents (they will be replaced). |
Returns
string
The actual name of the new function. This may differ from desiredName if the former has already been taken by the user.
getVariableName()
getVariableName(nameOrId): string;
Defined in: packages/blockly/core/generator.ts:522
Gets a unique, legal name for a user-defined variable.
Before calling this method, the nameDB_ property of the class
must have been initialized already. This is typically done in
the init function of the code generator class.
Parameters
| Parameter | Type | Description |
|---|---|---|
nameOrId | string | The ID of the variable to get a name for, or the proposed name for a variable not associated with an id. |
Returns
string
A unique, legal name for the variable.
getProcedureName()
getProcedureName(name): string;
Defined in: packages/blockly/core/generator.ts:535
Gets a unique, legal name for a user-defined procedure.
Before calling this method, the nameDB_ property of the class
must have been initialized already. This is typically done in
the init function of the code generator class.
Parameters
| Parameter | Type | Description |
|---|---|---|
name | string | The proposed name for a procedure. |
Returns
string
A unique, legal name for the procedure.
init()
init(_workspace): void;
Defined in: packages/blockly/core/generator.ts:555
Hook for code to run before code generation starts. Subclasses may override this, e.g. to initialise the database of variable names.
Parameters
| Parameter | Type | Description |
|---|---|---|
_workspace | Workspace | Workspace to generate code from. |
Returns
void
scrub_()
scrub_(
_block,
code,
_opt_thisOnly?
): string;
Defined in: packages/blockly/core/generator.ts:577
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.
Parameters
| Parameter | Type | Description |
|---|---|---|
_block | Block | The current block. |
code | string | The code created for this block. |
_opt_thisOnly? | boolean | True to generate code for only this statement. |
Returns
string
Code with comments and subsequent blocks added.
finish()
finish(code): string;
Defined in: packages/blockly/core/generator.ts:590
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.
Parameters
| Parameter | Type | Description |
|---|---|---|
code | string | Generated code. |
Returns
string
Completed code.
scrubNakedValue()
scrubNakedValue(line): string;
Defined in: packages/blockly/core/generator.ts:607
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.
Parameters
| Parameter | Type | Description |
|---|---|---|
line | string | Line of generated code. |
Returns
string
Legal line of code.