Skip to main content

Class: CodeGenerator

Defined in: packages/blockly/core/generator.ts:40

Class for a code generator that translates the blocks into a language.

Properties index

PropertyDescription
name_-
forBlockA 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_TRAPArbitrary 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_PREFIXArbitrary 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_SUFFIXArbitrary 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
INDENTThe method of indenting. Defaults to two spaces, but language generators may override this to increase indent or change to tabs.
COMMENT_WRAPMaximum length for a comment before wrapping. Does not account for indenting level.
ORDER_OVERRIDESList of outer-inner pairings that do NOT require parentheses.
isInitializedWhether 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

MethodDescription
workspaceToCodeGenerate code for all blocks in the workspace to the specified language.
prefixLinesPrepend a common prefix onto each line of code. Intended for indenting code or adding comment markers.
allNestedCommentsRecursively spider a tree of blocks, returning all their comments.
blockToCodeGenerate code for the specified block (and attached blocks). The generator must be initialized before calling this function.
valueToCodeGenerate code representing the specified value input.
statementToCodeGenerate 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.
addLoopTrapAdd 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).
injectIdInject a block ID into a message to replace '%1'. Used for STATEMENT_PREFIX, STATEMENT_SUFFIX, and INFINITE_LOOP_TRAP.
addReservedWordsAdd 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.
getVariableNameGets 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.
getProcedureNameGets 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.
initHook 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.
finishHook 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.
scrubNakedValueNaked 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

ParameterTypeDescription
namestringLanguage 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

ParameterTypeDescription
workspace?WorkspaceWorkspace 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

ParameterTypeDescription
textstringThe lines of code.
prefixstringThe 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

ParameterTypeDescription
blockBlockThe 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

ParameterTypeDescription
blockBlock | nullThe block to generate code for.
opt_thisOnly?booleanTrue 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

ParameterTypeDescription
blockBlockThe block containing the input.
namestringThe name of the input.
outerOrdernumberThe 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

ParameterTypeDescription
blockBlockThe block containing the input.
namestringThe 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

ParameterTypeDescription
branchstringCode for loop contents.
blockBlockEnclosing 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

ParameterTypeDescription
msgstringCode snippet with '%1'.
blockBlockBlock 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

ParameterTypeDescription
wordsstringComma-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

ParameterTypeDescription
desiredNamestringThe desired name of the function (e.g. mathIsPrime).
codestring | 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

ParameterTypeDescription
nameOrIdstringThe 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

ParameterTypeDescription
namestringThe 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

ParameterTypeDescription
_workspaceWorkspaceWorkspace 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

ParameterTypeDescription
_blockBlockThe current block.
codestringThe code created for this block.
_opt_thisOnly?booleanTrue 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

ParameterTypeDescription
codestringGenerated 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

ParameterTypeDescription
linestringLine of generated code.

Returns

string

Legal line of code.