blockly > CodeGenerator

CodeGenerator class

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

Signature:

export declare class CodeGenerator 

Constructors

Constructor Modifiers Description
(constructor)(name) Constructs a new instance of the CodeGenerator class

Properties

Property Modifiers Type Description
COMMENT_WRAP number Maximum length for a comment before wrapping. Does not account for indenting level.
definitions_ protected { [key: string]: string; } A dictionary of definitions to be printed before the code.
forBlock Record<string, (block: Block, generator: this) => [string, number] | string | null>

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_ string 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_ RegExp
functionNames_ protected { [key: string]: string; } A dictionary mapping desired function names in definitions_ to actual function names (to avoid collisions with user functions).
INDENT string The method of indenting. Defaults to two spaces, but language generators may override this to increase indent or change to tabs.
INFINITE_LOOP_TRAP string | null 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
isInitialized boolean | null 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.
name_ string
nameDB_? Names (Optional) A database of variable and procedure names.
ORDER_OVERRIDES number[][] List of outer-inner pairings that do NOT require parentheses.
RESERVED_WORDS_ protected string Comma-separated list of reserved words.
STATEMENT_PREFIX string | 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_SUFFIX string | 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

Methods

Method Modifiers Description
addLoopTrap(branch, block) 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).
addReservedWords(words) Add one or more words to the list of reserved words for this language.
allNestedComments(block) Recursively spider a tree of blocks, returning all their comments.
blockToCode(block, opt_thisOnly) Generate code for the specified block (and attached blocks). The generator must be initialized before calling this function.
finish(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.
getProcedureName(name) 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.
getVariableName(nameOrId) 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.
init(_workspace) Hook for code to run before code generation starts. Subclasses may override this, e.g. to initialise the database of variable names.
injectId(msg, block) Inject a block ID into a message to replace '%1'. Used for STATEMENT_PREFIX, STATEMENT_SUFFIX, and INFINITE_LOOP_TRAP.
prefixLines(text, prefix) Prepend a common prefix onto each line of code. Intended for indenting code or adding comment markers.
provideFunction_(desiredName, code)

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.

scrub_(_block, code, _opt_thisOnly) 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.
scrubNakedValue(line) 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.
statementToCode(block, name) 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.
valueToCode(block, name, outerOrder) Generate code representing the specified value input.
workspaceToCode(workspace) Generate code for all blocks in the workspace to the specified language.