scratch-blocks/core/generator.js

427 lines
14 KiB
JavaScript
Raw Permalink Normal View History

/**
* @license
* Visual Blocks Editor
*
* Copyright 2012 Google Inc.
2014-10-07 13:09:55 -07:00
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Utility functions for generating executable code from
* Blockly code.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Generator');
goog.require('Blockly.Block');
goog.require('goog.asserts');
/**
* Class for a code generator that translates the blocks into a language.
* @param {string} name Language name of this generator.
* @constructor
*/
Blockly.Generator = function(name) {
this.name_ = name;
2014-09-08 14:26:52 -07:00
this.FUNCTION_NAME_PLACEHOLDER_REGEXP_ =
new RegExp(this.FUNCTION_NAME_PLACEHOLDER_, 'g');
};
/**
* Category to separate generated function names from variables and procedures.
*/
Blockly.Generator.NAME_TYPE = 'generated_function';
2014-09-08 14:26:52 -07:00
/**
* 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'
2015-07-13 15:03:22 -07:00
* @type {?string}
2014-09-08 14:26:52 -07:00
*/
Blockly.Generator.prototype.INFINITE_LOOP_TRAP = 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'
2015-07-13 15:03:22 -07:00
* @type {?string}
2014-09-08 14:26:52 -07:00
*/
Blockly.Generator.prototype.STATEMENT_PREFIX = null;
/**
* The method of indenting. Defaults to two spaces, but language generators
* may override this to increase indent or change to tabs.
* @type {string}
*/
Blockly.Generator.prototype.INDENT = ' ';
2016-06-08 00:12:58 -07:00
/**
* Maximum length for a comment before wrapping. Does not account for
* indenting level.
* @type {number}
*/
Blockly.Generator.prototype.COMMENT_WRAP = 60;
/**
* List of outer-inner pairings that do NOT require parentheses.
* @type {!Array.<!Array.<number>>}
*/
Blockly.Generator.prototype.ORDER_OVERRIDES = [];
/**
* Generate code for all blocks in the workspace to the specified language.
2015-04-28 13:51:25 -07:00
* @param {Blockly.Workspace} workspace Workspace to generate code from.
* @return {string} Generated code.
*/
2015-04-28 13:51:25 -07:00
Blockly.Generator.prototype.workspaceToCode = function(workspace) {
if (!workspace) {
2016-05-11 16:52:51 -07:00
// Backwards compatibility from before there could be multiple workspaces.
2015-04-28 13:51:25 -07:00
console.warn('No workspace specified in workspaceToCode call. Guessing.');
workspace = Blockly.getMainWorkspace();
}
var code = [];
2014-12-23 11:22:02 -08:00
this.init(workspace);
var blocks = workspace.getTopBlocks(true);
for (var x = 0, block; block = blocks[x]; x++) {
var line = this.blockToCode(block);
if (goog.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.scrubNakedValue) {
// This block is a naked value. Ask the language's code generator if
// it wants to append a semicolon, or something.
line = this.scrubNakedValue(line);
}
code.push(line);
}
}
code = code.join('\n'); // Blank line between each section.
code = this.finish(code);
// Final scrubbing of whitespace.
code = code.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.
* @param {string} text The lines of code.
* @param {string} prefix The common prefix.
* @return {string} The prefixed lines of code.
*/
Blockly.Generator.prototype.prefixLines = function(text, prefix) {
Adding indexing settings, tests and fixing bugs (#464) * Add indexing setting for JavaScript Generation Adding setting to allow for switching between zero and one based indexing for Blockly Blocks such that the generated code will use this flag to determine whether one based or zero based indexing should be used. One based indexing is enabled by default. * Updating js lists to do zero and one based index Updated generated JavaScript to change depending on whether one based indexing is enabled or not. * Updating js text to do zero and one based index Change so that JavaScript generated for text blocks either assumes blocks use zero or one based index based on setting. * Start of python indexing Start of work on allowing one and zero indexing for generated python for lists. * Fixing bug and lint fixed Fixing bug caused by not setting the return of concat when concatenating lines for sublist and substring functions. Also renamed these functions to be getSubsequece. Fixed lint errors with spacing * Converting from if to switch statements Comverting if statements to switch statements when appropriate and adding spacing. * Modified sublist JavaScript generation Added case so that helper function is not generated if not necessary. Helper function is not generated if list length is not needed or if list is a simple block (such as a variable, as oppossed to a function call or list create). * Stripping unecessary ids Removing ids from xml file. * Localisation updates from https://translatewiki.net. * Fix typo in flyout.js (#403) * Fix typo in flyout.js (#402) * Localisation updates from https://translatewiki.net. * Add indexing setting for JavaScript Generation Adding setting to allow for switching between zero and one based indexing for Blockly Blocks such that the generated code will use this flag to determine whether one based or zero based indexing should be used. One based indexing is enabled by default. * Updating js lists to do zero and one based index Updated generated JavaScript to change depending on whether one based indexing is enabled or not. * Updating js text to do zero and one based index Change so that JavaScript generated for text blocks either assumes blocks use zero or one based index based on setting. * Fixing bug and lint fixed Fixing bug caused by not setting the return of concat when concatenating lines for sublist and substring functions. Also renamed these functions to be getSubsequece. Fixed lint errors with spacing * Converting from if to switch statements Comverting if statements to switch statements when appropriate and adding spacing. * Modified sublist JavaScript generation Added case so that helper function is not generated if not necessary. Helper function is not generated if list length is not needed or if list is a simple block (such as a variable, as oppossed to a function call or list create). * Stripping unecessary ids Removing ids from xml file. * Updating generator test Modifying sublist test and re-formatting spacing between blocks. * Updating js lists to do zero and one based index Updated generated JavaScript to change depending on whether one based indexing is enabled or not. * Updating js text to do zero and one based index Change so that JavaScript generated for text blocks either assumes blocks use zero or one based index based on setting. * Fixing bug and lint fixed Fixing bug caused by not setting the return of concat when concatenating lines for sublist and substring functions. Also renamed these functions to be getSubsequece. Fixed lint errors with spacing * Converting from if to switch statements Comverting if statements to switch statements when appropriate and adding spacing. * Modified sublist JavaScript generation Added case so that helper function is not generated if not necessary. Helper function is not generated if list length is not needed or if list is a simple block (such as a variable, as oppossed to a function call or list create). * Stripping unecessary ids Removing ids from xml file. * Localisation updates from https://translatewiki.net. * Localisation updates from https://translatewiki.net. * Updating js lists to do zero and one based index Updated generated JavaScript to change depending on whether one based indexing is enabled or not. * Fixing bug and lint fixed Fixing bug caused by not setting the return of concat when concatenating lines for sublist and substring functions. Also renamed these functions to be getSubsequece. Fixed lint errors with spacing * Modified sublist JavaScript generation Added case so that helper function is not generated if not necessary. Helper function is not generated if list length is not needed or if list is a simple block (such as a variable, as oppossed to a function call or list create). * Stripping unecessary ids Removing ids from xml file. * Updating generator test Modifying sublist test and re-formatting spacing between blocks. * Adding tests for indexing and extra cases Adding tests for indexing with custom block to adjust number based on what indexing is being generated. * Adding tests and renaming tests Adding tests for sublist and renaming tests. * Fixes for order for sublists Fixes so that parenthesis are generated properly for index for sublist * Cleaning up test generated code Changing order returned for unit test adjust index function to generate less unecessary parenthesis. * Adding tests for order Adding tests for order, relevant for methods that use index from start (because 1 is added) * Fixing JS order for getIndex and setIndex Changing to the correct order type when calling valueToCode in JS generation for getIndex and setIndex. * Fixed unittest adjustIndex Fixed uninttest adjustindex to also check whether the ONE_BASED_INDEXING variable has been defined to ensure proper behaviour. * Fixing lint and formatting for JS/lists Making line fixes and changing an if/elseif to case statement. * Tests added to include case for bug found Added tests with sublist combinations of different where's for the two indices after bug for this found in python. * Adding and renaming tests Adding test case for creating a sublist that encompasses the whole list but uses # and #-end instead of first last (applicable for python). Also, renaming tests. * Adding contant and fixing python lists bugs Adding contant for ONE_BASED_INDEXING and fixing bugs in python for lists. * Fixing test get random Fixing test get random to take into account indexing for return value. * Adding indexing checkbox to test page Adding checkbos on test page so that code can be generated for one and zero based indexing. Languages that are generated with zero based indexing that do not have it implemented will fail tests as expected. * Fixing unittest getremove random Fixing unittest getremove random to take into account the return value based on indexing. * Change comparison for getremove random test Fixed comparison to equal for the return value for getremove random. * Fixing bugs with lists zero-indexing Fixing getIndex and getSublist methods to pass for zero-indexed tests. * Adding test cases and formatting Adding test cases to text tests, reordering a couple list test, and formatting block spacing. * Fixing unittest expected value Fixing expected value fore unit tests for sublist. * Cleanup Removing obvious comments, formatting fixes, and naming in generated code in JS. * Helper function for Python lists Adding helper function for casting to int for indices. * Expanding helper to reduce duplicated code Expanding helper method to also get the property with the correct order and check indexing to reduce duplicated code. * Cleaning up JS indexing with helper function Adding helper function for indexing and used it in lists and text. * Moving helper function and formatting fixes Moving helper function, formatting fixes, and changing some generated code variable names. * Fixing python generation for text Fixing all failinng tests for python and using new helper method. * Lint fixes and order in indexOf Making lint fixes and correcting returned order in indexOf. * Python variable renaming Renaming a few generated variables. * Fixing comment and order Fixing comment to list Blockly.Block type and fixing order because it could be higher. * Switching back to if Switching switch back to if statements because there weren't enough cases to warrant for a switch. * Adding order and fixing lists for Dart Adding if null operator to operator precedence for Dart. Also, fixing lists implementation to pass unit tests and adding zero-indexing functionality. * Formatting and lint fixes Formatting and lint fixes * Dart text fixed Fixing Dart text generation to pass unit tests. * Changing back to variable Changing switch condition back to variable. * Fixing ORDER_OVERRIDES Inner and outer order was switched . * Adding bug with order caused by generator change Flooring order before comparision because of how the order constants were modified. * Adding list tests Adding tests for additional cases for lists/ * Adding comment for dart order Adding comment for Dart ORDER_IF_NULL operator. * Formatting fixes Formatting fixes for line indentation. * Fixing PHP order and lists generation Fixing PHP order constants and fixing lists so that they pass unit tests. * Fixing tests Removing duplicate unit test * Adding text tests Adding tests for text. * Renaming variable and removing unused variable Renaming variables from exceptionIndex to errorIndex and removing unused at variable. * Adding missing function call to test Adding missing funciton call to test that was causing tests to fail when they shouldn't. * Fixing PHP text generation Fixing PHP text code generation so it passes unit tests. * Formatting fixes Cleaning up code, renamiing a variable. * Fixing failing subsequence tests Fixing JS code that failed for sublist/substring tests. * Fixing intentation Fixing indentation. * Fixing Dart sublist/substring Fixing sublist/substring to include condiiton where FROM_START (and not throw error by mistake) when zero-indexed. * Adding order subtraction test Adding test for checking order for subtraction x- (y - z) x - (y + z). * Updating to new PHP power operator Updating from pow function to ** operator to clean up code. * Updating to new removeWhere Updating removeMatching to removeWhere because new version of Dart now use removeWhere. * Fix for lua rounding assertequals Adding check for number in equlity check for comparing number for floats. * Adding test for copy of list Adding test that checks the list is copied when a sublist is made first-last. * Formatting and order fixes Fixing formatting such as indentation and order fixes. * Adding comment for clarity Adding comment about how Lua code generation is not supporting zero indexing. * Changed variable names in code Changed variable names to follow style guide and changed for loop variable from n to i as is typical. * Reducing unecessarily generated functions and renaming variables Reducing number of generated functions using gensym_ by adding parameters to provided function. Renaming variables to make functions more readble. * Fixing sublist order and sort variable Fixing order used for valueToCode for sublist and renaming list variable in sort to match rest of code.. * Fixing order constant order Removing operator () that was incorrect and addiung ~, * Fixing order and indentation Fixing order return fro create lists blocks and fixing indentationn for string array. * Fixing order and renaming variables Fixing order to be the correct strength and renaming variables to be more readable/ * Changing assert blocks for unit tests Changing assert blocks to have a value input instead of a field so there is more flexibility in writing tests. * Cleaning up and adding missing order tests Adding tests for order for paramters for list blocks that weren't being tested to uncover bugs. Test were also cleaned up/reorganized/renamed to be more readable and shorter vertically (but lines wider horizontally). * Compile error fix and order in Dart generation. Fixing compile error in generated code and incorrect order in get sublist for Dart. * Fixing typo in getIndex and invalid parameter name Fixing type in getIndex where list code should have been appended but instead an undefined variable was added. The parameter in lists_sort was changed to my_list because list is a reserved word in python. * Fixing order, parenthesis bug, and variable declaration in Lua Fixing incorrect order in Lua. Fixing bug caused by missing parenthesis around ternary operator in code. Variable code was declared with JavaScript syntax, this was fixed to be valid in Lua. * Adding tests and formatting tests Adding missing test for order in text/lists. Changing spacing/order of tests and updating comments. * Fixing error in code Changing to correct function call in empy tests and changing test name that was duplicated to be more clear. * Renamed test helper function * Fixing order and renaming variable in JS generator Fixing order for charAt and renaming variable in code list_sort from listCode to list to be consistent with rest of code. * Fixing order for dart text Fixing roder for dart charAt * Cleaning up generated code for Dart getIndex Cleaning up generated code for Dart getIndex so that helper functions aren't generated unecessarily and adding comments. * Fixing Dart remove random error Fixing error caused by remove random implementation in Dart. index should have been x but instead was length - x. * Fixing unit test blocks Fixing Lua unit test block that should have just returned the number and removing unecessary checks in other blocks because the constant was defined. * Fixing Lua assert equals block string.format was throwing an error if one of the values happened to be a boolean. * Adding tests for create text with number Adding test for create text with numbers as parameters * Fixing lua unit test block Lua unit test block should have added 1 * Removing indexing setting for Lua tests Removing setting index setting for Lua generation because it is always one-indexed. * Fixing order and create text Fixing failing test caused by improper order and fixed create text to properly convert to string when there is one element. * Running linter on generator code Running linter on generator code and fixing spacing/indentation problems. * Editing comments and removing uneeded parenthesis Editing and adding comments and removing uneeded parenthesis around ternary operator condition. * Fixing order and changing variable names Fixing orders that were incorrect and changing variable names to be more descriptive and consistent across code. * Adding comment about list support and fixes for PHP Adding comment about how lists are not fully supported for PHP. Adding missing order to PHP and fixing order errors throughout. Fixing regex for variable matching in lists. Cleaning up variable names to be more readable and consistent with other parts of code. * Reducing complexity for getremove/remove in JS Reducing complexity in generated code for getremove/remove in JavaScript by replacing unecessary helper function. * Fixing spacing before inline comments Ensuring there are two spaces before inline comments. * Changing JS list copy for clarity Changing JavaScript list copy to use slice(0) instead of concat for clarity and to use the same pattern as the other sublist methods. * Changing generated variable name tmp_x Changing tmp_x to tmpX to follow closer to the correct style for JavaScript. * Prefixing empy lines between comment text Prior to this change, comments with an empty line between text did not have a comment prefix before it, resulting in comment blocks that seemed disjoined although they were for the same block. This change affects how the prefix line function works so that those lines will have the prefix (if applicable) while still taking into account the trailing newline character. * Changing for loops variable names Changing most for loops to use i as the variable name (or j if applicable) or changing name to be more readable. * Simplifying provided subsequence function Simplifying subsequence function to generate a simpler function depending on where combination instead of a larger complex function that works for all where combinations. * Style fixes Fixing indentation, comments, and other formatting-type changes based on pull request comments. * Fixing indentation Fixing indentation and removing an extra newline. * Fixing PHP mode implementation Fixing PHP mode implementation to properlyu return multiple modes if applicable. * Fixing line too long Wrapping lines in php/math.js with lines longer than 80 characters. * Wrapping long lines Wrapping lines that are too long. * Changing boolean casing Changing boolean casing to be lowercase.
2016-07-08 11:43:48 -07:00
return prefix + text.replace(/(?!\n$)\n/g, '\n' + prefix);
};
/**
* Recursively spider a tree of blocks, returning all their comments.
* @param {!Blockly.Block} block The block from which to start spidering.
* @return {string} Concatenated list of comments.
*/
Blockly.Generator.prototype.allNestedComments = function(block) {
var comments = [];
var blocks = block.getDescendants(true);
Adding indexing settings, tests and fixing bugs (#464) * Add indexing setting for JavaScript Generation Adding setting to allow for switching between zero and one based indexing for Blockly Blocks such that the generated code will use this flag to determine whether one based or zero based indexing should be used. One based indexing is enabled by default. * Updating js lists to do zero and one based index Updated generated JavaScript to change depending on whether one based indexing is enabled or not. * Updating js text to do zero and one based index Change so that JavaScript generated for text blocks either assumes blocks use zero or one based index based on setting. * Start of python indexing Start of work on allowing one and zero indexing for generated python for lists. * Fixing bug and lint fixed Fixing bug caused by not setting the return of concat when concatenating lines for sublist and substring functions. Also renamed these functions to be getSubsequece. Fixed lint errors with spacing * Converting from if to switch statements Comverting if statements to switch statements when appropriate and adding spacing. * Modified sublist JavaScript generation Added case so that helper function is not generated if not necessary. Helper function is not generated if list length is not needed or if list is a simple block (such as a variable, as oppossed to a function call or list create). * Stripping unecessary ids Removing ids from xml file. * Localisation updates from https://translatewiki.net. * Fix typo in flyout.js (#403) * Fix typo in flyout.js (#402) * Localisation updates from https://translatewiki.net. * Add indexing setting for JavaScript Generation Adding setting to allow for switching between zero and one based indexing for Blockly Blocks such that the generated code will use this flag to determine whether one based or zero based indexing should be used. One based indexing is enabled by default. * Updating js lists to do zero and one based index Updated generated JavaScript to change depending on whether one based indexing is enabled or not. * Updating js text to do zero and one based index Change so that JavaScript generated for text blocks either assumes blocks use zero or one based index based on setting. * Fixing bug and lint fixed Fixing bug caused by not setting the return of concat when concatenating lines for sublist and substring functions. Also renamed these functions to be getSubsequece. Fixed lint errors with spacing * Converting from if to switch statements Comverting if statements to switch statements when appropriate and adding spacing. * Modified sublist JavaScript generation Added case so that helper function is not generated if not necessary. Helper function is not generated if list length is not needed or if list is a simple block (such as a variable, as oppossed to a function call or list create). * Stripping unecessary ids Removing ids from xml file. * Updating generator test Modifying sublist test and re-formatting spacing between blocks. * Updating js lists to do zero and one based index Updated generated JavaScript to change depending on whether one based indexing is enabled or not. * Updating js text to do zero and one based index Change so that JavaScript generated for text blocks either assumes blocks use zero or one based index based on setting. * Fixing bug and lint fixed Fixing bug caused by not setting the return of concat when concatenating lines for sublist and substring functions. Also renamed these functions to be getSubsequece. Fixed lint errors with spacing * Converting from if to switch statements Comverting if statements to switch statements when appropriate and adding spacing. * Modified sublist JavaScript generation Added case so that helper function is not generated if not necessary. Helper function is not generated if list length is not needed or if list is a simple block (such as a variable, as oppossed to a function call or list create). * Stripping unecessary ids Removing ids from xml file. * Localisation updates from https://translatewiki.net. * Localisation updates from https://translatewiki.net. * Updating js lists to do zero and one based index Updated generated JavaScript to change depending on whether one based indexing is enabled or not. * Fixing bug and lint fixed Fixing bug caused by not setting the return of concat when concatenating lines for sublist and substring functions. Also renamed these functions to be getSubsequece. Fixed lint errors with spacing * Modified sublist JavaScript generation Added case so that helper function is not generated if not necessary. Helper function is not generated if list length is not needed or if list is a simple block (such as a variable, as oppossed to a function call or list create). * Stripping unecessary ids Removing ids from xml file. * Updating generator test Modifying sublist test and re-formatting spacing between blocks. * Adding tests for indexing and extra cases Adding tests for indexing with custom block to adjust number based on what indexing is being generated. * Adding tests and renaming tests Adding tests for sublist and renaming tests. * Fixes for order for sublists Fixes so that parenthesis are generated properly for index for sublist * Cleaning up test generated code Changing order returned for unit test adjust index function to generate less unecessary parenthesis. * Adding tests for order Adding tests for order, relevant for methods that use index from start (because 1 is added) * Fixing JS order for getIndex and setIndex Changing to the correct order type when calling valueToCode in JS generation for getIndex and setIndex. * Fixed unittest adjustIndex Fixed uninttest adjustindex to also check whether the ONE_BASED_INDEXING variable has been defined to ensure proper behaviour. * Fixing lint and formatting for JS/lists Making line fixes and changing an if/elseif to case statement. * Tests added to include case for bug found Added tests with sublist combinations of different where's for the two indices after bug for this found in python. * Adding and renaming tests Adding test case for creating a sublist that encompasses the whole list but uses # and #-end instead of first last (applicable for python). Also, renaming tests. * Adding contant and fixing python lists bugs Adding contant for ONE_BASED_INDEXING and fixing bugs in python for lists. * Fixing test get random Fixing test get random to take into account indexing for return value. * Adding indexing checkbox to test page Adding checkbos on test page so that code can be generated for one and zero based indexing. Languages that are generated with zero based indexing that do not have it implemented will fail tests as expected. * Fixing unittest getremove random Fixing unittest getremove random to take into account the return value based on indexing. * Change comparison for getremove random test Fixed comparison to equal for the return value for getremove random. * Fixing bugs with lists zero-indexing Fixing getIndex and getSublist methods to pass for zero-indexed tests. * Adding test cases and formatting Adding test cases to text tests, reordering a couple list test, and formatting block spacing. * Fixing unittest expected value Fixing expected value fore unit tests for sublist. * Cleanup Removing obvious comments, formatting fixes, and naming in generated code in JS. * Helper function for Python lists Adding helper function for casting to int for indices. * Expanding helper to reduce duplicated code Expanding helper method to also get the property with the correct order and check indexing to reduce duplicated code. * Cleaning up JS indexing with helper function Adding helper function for indexing and used it in lists and text. * Moving helper function and formatting fixes Moving helper function, formatting fixes, and changing some generated code variable names. * Fixing python generation for text Fixing all failinng tests for python and using new helper method. * Lint fixes and order in indexOf Making lint fixes and correcting returned order in indexOf. * Python variable renaming Renaming a few generated variables. * Fixing comment and order Fixing comment to list Blockly.Block type and fixing order because it could be higher. * Switching back to if Switching switch back to if statements because there weren't enough cases to warrant for a switch. * Adding order and fixing lists for Dart Adding if null operator to operator precedence for Dart. Also, fixing lists implementation to pass unit tests and adding zero-indexing functionality. * Formatting and lint fixes Formatting and lint fixes * Dart text fixed Fixing Dart text generation to pass unit tests. * Changing back to variable Changing switch condition back to variable. * Fixing ORDER_OVERRIDES Inner and outer order was switched . * Adding bug with order caused by generator change Flooring order before comparision because of how the order constants were modified. * Adding list tests Adding tests for additional cases for lists/ * Adding comment for dart order Adding comment for Dart ORDER_IF_NULL operator. * Formatting fixes Formatting fixes for line indentation. * Fixing PHP order and lists generation Fixing PHP order constants and fixing lists so that they pass unit tests. * Fixing tests Removing duplicate unit test * Adding text tests Adding tests for text. * Renaming variable and removing unused variable Renaming variables from exceptionIndex to errorIndex and removing unused at variable. * Adding missing function call to test Adding missing funciton call to test that was causing tests to fail when they shouldn't. * Fixing PHP text generation Fixing PHP text code generation so it passes unit tests. * Formatting fixes Cleaning up code, renamiing a variable. * Fixing failing subsequence tests Fixing JS code that failed for sublist/substring tests. * Fixing intentation Fixing indentation. * Fixing Dart sublist/substring Fixing sublist/substring to include condiiton where FROM_START (and not throw error by mistake) when zero-indexed. * Adding order subtraction test Adding test for checking order for subtraction x- (y - z) x - (y + z). * Updating to new PHP power operator Updating from pow function to ** operator to clean up code. * Updating to new removeWhere Updating removeMatching to removeWhere because new version of Dart now use removeWhere. * Fix for lua rounding assertequals Adding check for number in equlity check for comparing number for floats. * Adding test for copy of list Adding test that checks the list is copied when a sublist is made first-last. * Formatting and order fixes Fixing formatting such as indentation and order fixes. * Adding comment for clarity Adding comment about how Lua code generation is not supporting zero indexing. * Changed variable names in code Changed variable names to follow style guide and changed for loop variable from n to i as is typical. * Reducing unecessarily generated functions and renaming variables Reducing number of generated functions using gensym_ by adding parameters to provided function. Renaming variables to make functions more readble. * Fixing sublist order and sort variable Fixing order used for valueToCode for sublist and renaming list variable in sort to match rest of code.. * Fixing order constant order Removing operator () that was incorrect and addiung ~, * Fixing order and indentation Fixing order return fro create lists blocks and fixing indentationn for string array. * Fixing order and renaming variables Fixing order to be the correct strength and renaming variables to be more readable/ * Changing assert blocks for unit tests Changing assert blocks to have a value input instead of a field so there is more flexibility in writing tests. * Cleaning up and adding missing order tests Adding tests for order for paramters for list blocks that weren't being tested to uncover bugs. Test were also cleaned up/reorganized/renamed to be more readable and shorter vertically (but lines wider horizontally). * Compile error fix and order in Dart generation. Fixing compile error in generated code and incorrect order in get sublist for Dart. * Fixing typo in getIndex and invalid parameter name Fixing type in getIndex where list code should have been appended but instead an undefined variable was added. The parameter in lists_sort was changed to my_list because list is a reserved word in python. * Fixing order, parenthesis bug, and variable declaration in Lua Fixing incorrect order in Lua. Fixing bug caused by missing parenthesis around ternary operator in code. Variable code was declared with JavaScript syntax, this was fixed to be valid in Lua. * Adding tests and formatting tests Adding missing test for order in text/lists. Changing spacing/order of tests and updating comments. * Fixing error in code Changing to correct function call in empy tests and changing test name that was duplicated to be more clear. * Renamed test helper function * Fixing order and renaming variable in JS generator Fixing order for charAt and renaming variable in code list_sort from listCode to list to be consistent with rest of code. * Fixing order for dart text Fixing roder for dart charAt * Cleaning up generated code for Dart getIndex Cleaning up generated code for Dart getIndex so that helper functions aren't generated unecessarily and adding comments. * Fixing Dart remove random error Fixing error caused by remove random implementation in Dart. index should have been x but instead was length - x. * Fixing unit test blocks Fixing Lua unit test block that should have just returned the number and removing unecessary checks in other blocks because the constant was defined. * Fixing Lua assert equals block string.format was throwing an error if one of the values happened to be a boolean. * Adding tests for create text with number Adding test for create text with numbers as parameters * Fixing lua unit test block Lua unit test block should have added 1 * Removing indexing setting for Lua tests Removing setting index setting for Lua generation because it is always one-indexed. * Fixing order and create text Fixing failing test caused by improper order and fixed create text to properly convert to string when there is one element. * Running linter on generator code Running linter on generator code and fixing spacing/indentation problems. * Editing comments and removing uneeded parenthesis Editing and adding comments and removing uneeded parenthesis around ternary operator condition. * Fixing order and changing variable names Fixing orders that were incorrect and changing variable names to be more descriptive and consistent across code. * Adding comment about list support and fixes for PHP Adding comment about how lists are not fully supported for PHP. Adding missing order to PHP and fixing order errors throughout. Fixing regex for variable matching in lists. Cleaning up variable names to be more readable and consistent with other parts of code. * Reducing complexity for getremove/remove in JS Reducing complexity in generated code for getremove/remove in JavaScript by replacing unecessary helper function. * Fixing spacing before inline comments Ensuring there are two spaces before inline comments. * Changing JS list copy for clarity Changing JavaScript list copy to use slice(0) instead of concat for clarity and to use the same pattern as the other sublist methods. * Changing generated variable name tmp_x Changing tmp_x to tmpX to follow closer to the correct style for JavaScript. * Prefixing empy lines between comment text Prior to this change, comments with an empty line between text did not have a comment prefix before it, resulting in comment blocks that seemed disjoined although they were for the same block. This change affects how the prefix line function works so that those lines will have the prefix (if applicable) while still taking into account the trailing newline character. * Changing for loops variable names Changing most for loops to use i as the variable name (or j if applicable) or changing name to be more readable. * Simplifying provided subsequence function Simplifying subsequence function to generate a simpler function depending on where combination instead of a larger complex function that works for all where combinations. * Style fixes Fixing indentation, comments, and other formatting-type changes based on pull request comments. * Fixing indentation Fixing indentation and removing an extra newline. * Fixing PHP mode implementation Fixing PHP mode implementation to properlyu return multiple modes if applicable. * Fixing line too long Wrapping lines in php/math.js with lines longer than 80 characters. * Wrapping long lines Wrapping lines that are too long. * Changing boolean casing Changing boolean casing to be lowercase.
2016-07-08 11:43:48 -07:00
for (var i = 0; i < blocks.length; i++) {
var 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).
* @param {Blockly.Block} block The block to generate code for.
* @return {string|!Array} 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.
*/
Blockly.Generator.prototype.blockToCode = function(block) {
if (!block) {
return '';
}
if (block.disabled) {
// Skip past this block if it is disabled.
2014-09-08 14:26:52 -07:00
return this.blockToCode(block.getNextBlock());
}
var func = this[block.type];
goog.asserts.assertFunction(func,
'Language "%s" does not know how to generate code for block type "%s".',
this.name_, 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 prefered method of accessing the block is through the second
// argument to func.call, which becomes the first parameter to the generator.
var code = func.call(block, block);
if (goog.isArray(code)) {
// Value blocks return tuples of code and operator order.
goog.asserts.assert(block.outputConnection,
'Expecting string from statement block "%s".', block.type);
return [this.scrub_(block, code[0]), code[1]];
} else if (goog.isString(code)) {
var id = block.id.replace(/\$/g, '$$$$'); // Issue 251.
2014-09-08 14:26:52 -07:00
if (this.STATEMENT_PREFIX) {
code = this.STATEMENT_PREFIX.replace(/%1/g, '\'' + id + '\'') +
code;
2014-09-08 14:26:52 -07:00
}
return this.scrub_(block, code);
2014-09-08 14:26:52 -07:00
} else if (code === null) {
// Block has handled code generation itself.
return '';
} else {
goog.asserts.fail('Invalid code generated: %s', code);
}
};
/**
* Generate code representing the specified value input.
* @param {!Blockly.Block} block The block containing the input.
* @param {string} name The name of the input.
* @param {number} outerOrder The maximum binding strength (minimum order value)
* of any operators adjacent to "block".
* @return {string} Generated code or '' if no blocks are connected or the
* specified input does not exist.
*/
Blockly.Generator.prototype.valueToCode = function(block, name, outerOrder) {
if (isNaN(outerOrder)) {
goog.asserts.fail('Expecting valid order from block "%s".', block.type);
}
var targetBlock = block.getInputTargetBlock(name);
if (!targetBlock) {
return '';
}
var tuple = this.blockToCode(targetBlock);
if (tuple === '') {
// Disabled block.
return '';
}
2015-07-23 13:09:06 -07:00
// Value blocks must return code and order of operations info.
// Statement blocks must only return code.
goog.asserts.assertArray(tuple, 'Expecting tuple from value block "%s".',
targetBlock.type);
var code = tuple[0];
var innerOrder = tuple[1];
if (isNaN(innerOrder)) {
goog.asserts.fail('Expecting valid order from value block "%s".',
2015-07-23 13:09:06 -07:00
targetBlock.type);
}
if (!code) {
return '';
}
// Add parentheses if needed.
var parensNeeded = false;
var outerOrderClass = Math.floor(outerOrder);
var 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 (var 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 code representing the statement. Indent the code.
* @param {!Blockly.Block} block The block containing the input.
* @param {string} name The name of the input.
* @return {string} Generated code or '' if no blocks are connected.
*/
Blockly.Generator.prototype.statementToCode = function(block, name) {
var targetBlock = block.getInputTargetBlock(name);
var code = this.blockToCode(targetBlock);
2015-07-23 13:09:06 -07:00
// Value blocks must return code and order of operations info.
// Statement blocks must only return code.
goog.asserts.assertString(code, 'Expecting code from statement block "%s".',
targetBlock && targetBlock.type);
if (code) {
2014-09-08 14:26:52 -07:00
code = this.prefixLines(/** @type {string} */ (code), this.INDENT);
}
return code;
};
2014-09-08 14:26:52 -07:00
/**
* Add an infinite loop trap to the contents of a loop.
* If loop is empty, add a statment prefix for the loop block.
* @param {string} branch Code for loop contents.
* @param {string} id ID of enclosing block.
* @return {string} Loop contents, with infinite loop trap added.
*/
Blockly.Generator.prototype.addLoopTrap = function(branch, id) {
id = id.replace(/\$/g, '$$$$'); // Issue 251.
2014-09-08 14:26:52 -07:00
if (this.INFINITE_LOOP_TRAP) {
branch = this.INFINITE_LOOP_TRAP.replace(/%1/g, '\'' + id + '\'') + branch;
}
if (this.STATEMENT_PREFIX) {
branch += this.prefixLines(this.STATEMENT_PREFIX.replace(/%1/g,
'\'' + id + '\''), this.INDENT);
}
return branch;
};
/**
* Comma-separated list of reserved words.
* @type {string}
* @private
*/
Blockly.Generator.prototype.RESERVED_WORDS_ = '';
/**
* Add one or more words to the list of reserved words for this language.
* @param {string} words Comma-separated list of words to add to the list.
* No spaces. Duplicates are ok.
*/
Blockly.Generator.prototype.addReservedWords = function(words) {
this.RESERVED_WORDS_ += words + ',';
};
/**
* This is used as a placeholder in functions defined using
* Blockly.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.
* @type {string}
2014-09-08 14:26:52 -07:00
* @private
*/
Blockly.Generator.prototype.FUNCTION_NAME_PLACEHOLDER_ = '{leCUI8hutHZI4480Dc}';
/**
* Define a function to be included in the generated code.
* 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 code values.
*
* The code gets output when Blockly.Generator.finish() is called.
*
* @param {string} desiredName The desired name of the function (e.g., isPrime).
* @param {!Array.<string>} code A list of statements. Use ' ' for indents.
* @return {string} The actual name of the new function. This may differ
* from desiredName if the former has already been taken by the user.
* @private
*/
Blockly.Generator.prototype.provideFunction_ = function(desiredName, code) {
if (!this.definitions_[desiredName]) {
var functionName = this.variableDB_.getDistinctName(desiredName,
Blockly.Procedures.NAME_TYPE);
this.functionNames_[desiredName] = functionName;
var codeText = code.join('\n').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.
var oldCodeText;
while (oldCodeText != codeText) {
oldCodeText = codeText;
2016-11-02 13:56:27 -07:00
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 {!Blockly.Workspace} _workspace Workspace to generate code from.
*/
Blockly.Generator.prototype.init = function(_workspace) {
// Optionally override
};
/**
* 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 {!Blockly.Block} _block The current block.
* @param {string} code The JavaScript code created for this block.
* @return {string} JavaScript code with comments and subsequent blocks added.
* @private
*/
Blockly.Generator.prototype.scrub_ = function(_block, code) {
// 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 the
* variable definitions.
* @param {string} code Generated code.
* @return {string} Completed code.
*/
Blockly.Generator.prototype.finish = function(code) {
// Optionally override
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 {string} line Line of generated code.
* @return {string} Legal line of code.
*/
Blockly.Generator.prototype.scrubNakedValue = function(line) {
// Optionally override
return line;
};