From ce63f70b3780200fa717714ecc30d18897b96ede Mon Sep 17 00:00:00 2001 From: "ellen.spertus" Date: Mon, 13 Jan 2014 03:00:02 -0800 Subject: [PATCH] Automatic commit Mon Jan 13 03:00:02 PST 2014 --- apps/blockfactory/blocks.js | 11 +- apps/blockfactory/factory.js | 3 +- blocks/text.js | 16 +- core/field_image.js | 26 +- generators/dart.js | 191 +++++++++++ generators/dart/colour.js | 119 +++++++ generators/dart/lists.js | 290 +++++++++++++++++ generators/dart/logic.js | 91 ++++++ generators/dart/loops.js | 158 +++++++++ generators/dart/math.js | 516 ++++++++++++++++++++++++++++++ generators/dart/procedures.js | 101 ++++++ generators/dart/text.js | 268 ++++++++++++++++ generators/dart/variables.js | 44 +++ tests/generators/unittest_dart.js | 163 ++++++++++ 14 files changed, 1980 insertions(+), 17 deletions(-) create mode 100644 generators/dart.js create mode 100644 generators/dart/colour.js create mode 100644 generators/dart/lists.js create mode 100644 generators/dart/logic.js create mode 100644 generators/dart/loops.js create mode 100644 generators/dart/math.js create mode 100644 generators/dart/procedures.js create mode 100644 generators/dart/text.js create mode 100644 generators/dart/variables.js create mode 100644 tests/generators/unittest_dart.js diff --git a/apps/blockfactory/blocks.js b/apps/blockfactory/blocks.js index 2890b111f..096fc4f65 100644 --- a/apps/blockfactory/blocks.js +++ b/apps/blockfactory/blocks.js @@ -435,13 +435,18 @@ Blockly.Blocks['field_image'] = { .appendField(new Blockly.FieldTextInput(src), 'SRC'); this.appendDummyInput() .appendField('width') - .appendField(new Blockly.FieldTextInput('15'), 'WIDTH') + .appendField(new Blockly.FieldTextInput('15', + Blockly.FieldTextInput.numberValidator), 'WIDTH') .appendField('height') - .appendField(new Blockly.FieldTextInput('15'), 'HEIGHT'); + .appendField(new Blockly.FieldTextInput('15', + Blockly.FieldTextInput.numberValidator), 'HEIGHT') + .appendField('alt text') + .appendField(new Blockly.FieldTextInput('*'), 'ALT'); this.setPreviousStatement(true, 'Field'); this.setNextStatement(true, 'Field'); this.setTooltip('Static image (JPEG, PNG, GIF, SVG, BMP).\n' + - 'Retains aspect ratio regardless of height and width.'); + 'Retains aspect ratio regardless of height and width.\n' + + 'Alt text is for when collapsed.'); } }; diff --git a/apps/blockfactory/factory.js b/apps/blockfactory/factory.js index 0f5006886..1992d393a 100644 --- a/apps/blockfactory/factory.js +++ b/apps/blockfactory/factory.js @@ -209,8 +209,9 @@ function getFields(block) { var src = escapeString(block.getFieldValue('SRC')); var width = Number(block.getFieldValue('WIDTH')); var height = Number(block.getFieldValue('HEIGHT')); + var alt = escapeString(block.getFieldValue('ALT')); fields.push('new Blockly.FieldImage(' + - src + ', ' + width + ', ' + height + ')'); + src + ', ' + width + ', ' + height + ', ' + alt + ')'); break; } block = block.nextConnection && block.nextConnection.targetBlock(); diff --git a/blocks/text.js b/blocks/text.js index 3bdd71462..60bc70673 100644 --- a/blocks/text.js +++ b/blocks/text.js @@ -35,10 +35,10 @@ Blockly.Blocks['text'] = { this.setColour(160); this.appendDummyInput() .appendField(new Blockly.FieldImage(Blockly.pathToBlockly + - 'media/quote0.png', 12, 12)) + 'media/quote0.png', 12, 12, '"')) .appendField(new Blockly.FieldTextInput(''), 'TEXT') .appendField(new Blockly.FieldImage(Blockly.pathToBlockly + - 'media/quote1.png', 12, 12)); + 'media/quote1.png', 12, 12, '"')); this.setOutput(true, 'String'); this.setTooltip(Blockly.Msg.TEXT_TEXT_TOOLTIP); } @@ -76,9 +76,9 @@ Blockly.Blocks['text_join'] = { if (this.itemCount_ == 0) { this.appendDummyInput('EMPTY') .appendField(new Blockly.FieldImage(Blockly.pathToBlockly + - 'media/quote0.png', 12, 12)) + 'media/quote0.png', 12, 12, '"')) .appendField(new Blockly.FieldImage(Blockly.pathToBlockly + - 'media/quote1.png', 12, 12)); + 'media/quote1.png', 12, 12, '"')); } }, decompose: function(workspace) { @@ -122,9 +122,9 @@ Blockly.Blocks['text_join'] = { if (this.itemCount_ == 0) { this.appendDummyInput('EMPTY') .appendField(new Blockly.FieldImage(Blockly.pathToBlockly + - 'media/quote0.png', 12, 12)) + 'media/quote0.png', 12, 12, '"')) .appendField(new Blockly.FieldImage(Blockly.pathToBlockly + - 'media/quote1.png', 12, 12)); + 'media/quote1.png', 12, 12, '"')); } }, saveConnections: function(containerBlock) { @@ -468,10 +468,10 @@ Blockly.Blocks['text_prompt'] = { this.appendDummyInput() .appendField(dropdown, 'TYPE') .appendField(new Blockly.FieldImage(Blockly.pathToBlockly + - 'media/quote0.png', 12, 12)) + 'media/quote0.png', 12, 12, '"')) .appendField(new Blockly.FieldTextInput(''), 'TEXT') .appendField(new Blockly.FieldImage(Blockly.pathToBlockly + - 'media/quote1.png', 12, 12)); + 'media/quote1.png', 12, 12, '"')); this.setOutput(true, 'String'); // Assign 'this' to a variable for use in the tooltip closure below. var thisBlock = this; diff --git a/core/field_image.js b/core/field_image.js index 05be3349d..3a5d0415a 100644 --- a/core/field_image.js +++ b/core/field_image.js @@ -34,15 +34,17 @@ goog.require('goog.userAgent'); * @param {string} src The URL of the image. * @param {number} width Width of the image. * @param {number} height Height of the image. + * @param {?string} opt_alt Optional alt text for when block is collapsed. * @extends {Blockly.Field} * @constructor */ -Blockly.FieldImage = function(src, width, height) { +Blockly.FieldImage = function(src, width, height, opt_alt) { this.sourceBlock_ = null; // Ensure height and width are numbers. Strings are bad at math. this.height_ = Number(height); this.width_ = Number(width); this.size_ = {height: this.height_ + 10, width: this.width_}; + this.text_ = opt_alt || ''; // Build the DOM. var offsetY = 6 - Blockly.BlockSvg.FIELD_HEIGHT; this.fieldGroup_ = Blockly.createSvgElement('g', {}, null); @@ -50,7 +52,7 @@ Blockly.FieldImage = function(src, width, height) { {'height': this.height_ + 'px', 'width': this.width_ + 'px', 'y': offsetY}, this.fieldGroup_); - this.setText(src); + this.setValue(src); if (goog.userAgent.GECKO) { // Due to a Firefox bug which eats mouse events on image elements, // a transparent rectangle needs to be placed on top of the image. @@ -69,7 +71,8 @@ goog.inherits(Blockly.FieldImage, Blockly.Field); * with the current values of the arguments used during construction. */ Blockly.FieldImage.prototype.clone = function() { - return new Blockly.FieldImage(this.getText(), this.width_, this.height_); + return new Blockly.FieldImage(this.getSrc(), this.width_, this.height_, + this.getText()); }; /** @@ -126,7 +129,7 @@ Blockly.FieldImage.prototype.setTooltip = function(newTip) { * @return {string} Current text. * @override */ -Blockly.FieldImage.prototype.getText = function() { +Blockly.FieldImage.prototype.getValue = function() { return this.src_; }; @@ -135,7 +138,7 @@ Blockly.FieldImage.prototype.getText = function() { * @param {?string} src New source. * @override */ -Blockly.FieldImage.prototype.setText = function(src) { +Blockly.FieldImage.prototype.setValue = function(src) { if (src === null) { // No change if null. return; @@ -144,3 +147,16 @@ Blockly.FieldImage.prototype.setText = function(src) { this.imageElement_.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', goog.isString(src) ? src : ''); }; + +/** + * Set the alt text of this image. + * @param {?string} alt New alt text. + * @override + */ +Blockly.FieldImage.prototype.setText = function(alt) { + if (alt === null) { + // No change if null. + return; + } + this.text_ = alt; +}; diff --git a/generators/dart.js b/generators/dart.js new file mode 100644 index 000000000..df31eacfc --- /dev/null +++ b/generators/dart.js @@ -0,0 +1,191 @@ +/** + * Visual Blocks Language + * + * Copyright 2012 Google Inc. + * http://blockly.googlecode.com/ + * + * 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 Helper functions for generating Dart for blocks. + * @author fraser@google.com (Neil Fraser) + */ +'use strict'; + +goog.provide('Blockly.Dart'); + +goog.require('Blockly.CodeGenerator'); + +Blockly.Dart = Blockly.Generator.get('Dart'); + +/** + * List of illegal variable names. + * This is not intended to be a security feature. Blockly is 100% client-side, + * so bypassing this list is trivial. This is intended to prevent users from + * accidentally clobbering a built-in object or function. + * @private + */ +Blockly.Dart.addReservedWords( + // http://www.dartlang.org/docs/spec/latest/dart-language-specification.pdf + // Section 16.1.1 + 'assert,break,case,catch,class,const,continue,default,do,else,extends,false,final,finally,for,if,in,is,new,null,return,super,switch,this,throw,true,try,var,void,while,with,' + + // http://api.dartlang.org/dart_core.html + 'Collection,Comparable,Completer,Date,double,Function,Future,Hashable,HashMap,HashSet,int,InvocationMirror,Iterable,Iterator,LinkedHashMap,List,Map,Match,num,Options,Pattern,Queue,RegExp,Sequence,SequenceCollection,Set,Stopwatch,String,StringBuffer,Strings,Type,bool,DoubleLinkedQueue,DoubleLinkedQueueEntry,Duration,Expando,Expect,Futures,Object,SequenceIterator,SequenceList,Comparator,AbstractClassInstantiationError,ArgumentError,AssertionError,CastError,Error,Exception,ExpectException,FallThroughError,FormatException,FutureAlreadyCompleteException,FutureNotCompleteException,FutureUnhandledException,IllegalJSRegExpException,IntegerDivisionByZeroException,NoSuchMethodError,NullThrownError,OutOfMemoryError,RangeError,RuntimeError,StackOverflowError,StateError,TypeError,UnimplementedError,UnsupportedError'); +/** + * Order of operation ENUMs. + * http://www.dartlang.org/docs/dart-up-and-running/ch02.html#operator_table + */ +Blockly.Dart.ORDER_ATOMIC = 0; // 0 "" ... +Blockly.Dart.ORDER_UNARY_POSTFIX = 1; // expr++ expr-- () [] . +Blockly.Dart.ORDER_UNARY_PREFIX = 2; // -expr !expr ~expr ++expr --expr +Blockly.Dart.ORDER_MULTIPLICATIVE = 3; // * / % ~/ +Blockly.Dart.ORDER_ADDITIVE = 4; // + - +Blockly.Dart.ORDER_SHIFT = 5; // << >> +Blockly.Dart.ORDER_RELATIONAL = 6; // is is! >= > <= < +Blockly.Dart.ORDER_EQUALITY = 7; // == != === !== +Blockly.Dart.ORDER_BITWISE_AND = 8; // & +Blockly.Dart.ORDER_BITWISE_XOR = 9; // ^ +Blockly.Dart.ORDER_BITWISE_OR = 10; // | +Blockly.Dart.ORDER_LOGICAL_AND = 11; // && +Blockly.Dart.ORDER_LOGICAL_OR = 12; // || +Blockly.Dart.ORDER_CONDITIONAL = 13; // expr ? expr : expr +Blockly.Dart.ORDER_ASSIGNMENT = 14; // = *= /= ~/= %= += -= <<= >>= &= ^= |= +Blockly.Dart.ORDER_NONE = 99; // (...) + +/** + * 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' + * @type ?string + */ +Blockly.Dart.INFINITE_LOOP_TRAP = null; + +/** + * Initialise the database of variable names. + */ +Blockly.Dart.init = function() { + // Create a dictionary of definitions to be printed before the code. + Blockly.Dart.definitions_ = {}; + + if (Blockly.Variables) { + if (!Blockly.Dart.variableDB_) { + Blockly.Dart.variableDB_ = + new Blockly.Names(Blockly.Dart.RESERVED_WORDS_); + } else { + Blockly.Dart.variableDB_.reset(); + } + + var defvars = []; + var variables = Blockly.Variables.allVariables(); + for (var x = 0; x < variables.length; x++) { + defvars[x] = 'var ' + + Blockly.Dart.variableDB_.getName(variables[x], + Blockly.Variables.NAME_TYPE) + ';'; + } + Blockly.Dart.definitions_['variables'] = defvars.join('\n'); + } +}; + +/** + * Prepend the generated code with the variable definitions. + * @param {string} code Generated code. + * @return {string} Completed code. + */ +Blockly.Dart.finish = function(code) { + // Indent every line. + code = ' ' + code.replace(/\n/g, '\n '); + code = code.replace(/\n\s+$/, '\n'); + code = 'main() {\n' + code + '}'; + + // Convert the definitions dictionary into a list. + var imports = []; + var definitions = []; + for (var name in Blockly.Dart.definitions_) { + var def = Blockly.Dart.definitions_[name]; + if (def.match(/^import\s/)) { + imports.push(def); + } else { + definitions.push(def); + } + } + var allDefs = imports.join('\n') + '\n\n' + definitions.join('\n\n'); + return allDefs.replace(/\n\n+/g, '\n\n').replace(/\n*$/, '\n\n\n') + code; +}; + +/** + * Naked values are top-level blocks with outputs that aren't plugged into + * anything. A trailing semicolon is needed to make this legal. + * @param {string} line Line of generated code. + * @return {string} Legal line of code. + */ +Blockly.Dart.scrubNakedValue = function(line) { + return line + ';\n'; +}; + +/** + * Encode a string as a properly escaped Dart string, complete with quotes. + * @param {string} string Text to encode. + * @return {string} Dart string. + * @private + */ +Blockly.Dart.quote_ = function(string) { + // TODO: This is a quick hack. Replace with goog.string.quote + string = string.replace(/\\/g, '\\\\') + .replace(/\n/g, '\\\n') + .replace(/\$/g, '\\$') + .replace(/'/g, '\\\''); + return '\'' + string + '\''; +}; + +/** + * Common tasks for generating Dart from blocks. + * Handles comments for the specified block and any connected value blocks. + * Calls any statements following this block. + * @param {!Blockly.Block} block The current block. + * @param {string} code The Dart code created for this block. + * @return {string} Dart code with comments and subsequent blocks added. + * @this {Blockly.CodeGenerator} + * @private + */ +Blockly.Dart.scrub_ = function(block, code) { + if (code === null) { + // Block has handled code generation itself. + return ''; + } + var commentCode = ''; + // Only collect comments for blocks that aren't inline. + if (!block.outputConnection || !block.outputConnection.targetConnection) { + // Collect comment for this block. + var comment = block.getCommentText(); + if (comment) { + commentCode += Blockly.Generator.prefixLines(comment, '// ') + '\n'; + } + // Collect comments for all value arguments. + // Don't collect comments for nested statements. + for (var x = 0; x < block.inputList.length; x++) { + if (block.inputList[x].type == Blockly.INPUT_VALUE) { + var childBlock = block.inputList[x].connection.targetBlock(); + if (childBlock) { + var comment = Blockly.Generator.allNestedComments(childBlock); + if (comment) { + commentCode += Blockly.Generator.prefixLines(comment, '// '); + } + } + } + } + } + var nextBlock = block.nextConnection && block.nextConnection.targetBlock(); + var nextCode = this.blockToCode(nextBlock); + return commentCode + code + nextCode; +}; diff --git a/generators/dart/colour.js b/generators/dart/colour.js new file mode 100644 index 000000000..4b9a6b18a --- /dev/null +++ b/generators/dart/colour.js @@ -0,0 +1,119 @@ +/** + * Visual Blocks Language + * + * Copyright 2012 Google Inc. + * http://blockly.googlecode.com/ + * + * 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 Generating Dart for colour blocks. + * @author fraser@google.com (Neil Fraser) + */ +'use strict'; + +goog.provide('Blockly.Dart.colour'); + +goog.require('Blockly.Dart'); + +Blockly.Dart.addReservedWords('Math'); + +Blockly.Dart.colour_picker = function() { + // Colour picker. + var code = '\'' + this.getTitleValue('COLOUR') + '\''; + return [code, Blockly.Dart.ORDER_ATOMIC]; +}; + +Blockly.Dart.colour_rgb = function() { + // Compose a colour from RGB components. + var red = Blockly.Dart.valueToCode(this, 'RED', + Blockly.Dart.ORDER_NONE) || 0; + var green = Blockly.Dart.valueToCode(this, 'GREEN', + Blockly.Dart.ORDER_NONE) || 0; + var blue = Blockly.Dart.valueToCode(this, 'BLUE', + Blockly.Dart.ORDER_NONE) || 0; + + if (!Blockly.Dart.definitions_['colour_rgb']) { + Blockly.Dart.definitions_['import_dart_math'] = + 'import \'dart:math\' as Math;'; + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'colour_rgb', Blockly.Generator.NAME_TYPE); + Blockly.Dart.colour_rgb.functionName = functionName; + var func = []; + func.push('String ' + functionName + '(num r, num g, num b) {'); + func.push(' num rn = (Math.max(Math.min(r, 1), 0) * 255).round();'); + func.push(' String rs = rn.toInt().toRadixString(16);'); + func.push(' rs = \'0$rs\';'); + func.push(' rs = rs.substring(rs.length - 2);'); + func.push(' num gn = (Math.max(Math.min(g, 1), 0) * 255).round();'); + func.push(' String gs = gn.toInt().toRadixString(16);'); + func.push(' gs = \'0$gs\';'); + func.push(' gs = gs.substring(gs.length - 2);'); + func.push(' num bn = (Math.max(Math.min(b, 1), 0) * 255).round();'); + func.push(' String bs = bn.toInt().toRadixString(16);'); + func.push(' bs = \'0$bs\';'); + func.push(' bs = bs.substring(bs.length - 2);'); + func.push(' return \'#$rs$gs$bs\';'); + func.push('}'); + Blockly.Dart.definitions_['colour_rgb'] = func.join('\n'); + } + var code = Blockly.Dart.colour_rgb.functionName + + '(' + red + ', ' + green + ', ' + blue + ')'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; + +Blockly.Dart.colour_blend = function() { + // Blend two colours together. + var c1 = Blockly.Dart.valueToCode(this, 'COLOUR1', + Blockly.Dart.ORDER_NONE) || '\'#000000\''; + var c2 = Blockly.Dart.valueToCode(this, 'COLOUR2', + Blockly.Dart.ORDER_NONE) || '\'#000000\''; + var ratio = Blockly.Dart.valueToCode(this, 'RATIO', + Blockly.Dart.ORDER_NONE) || 0.5; + + if (!Blockly.Dart.definitions_['colour_blend']) { + Blockly.Dart.definitions_['import_dart_math'] = + 'import \'dart:math\' as Math;'; + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'colour_blend', Blockly.Generator.NAME_TYPE); + Blockly.Dart.colour_blend.functionName = functionName; + var func = []; + func.push('String ' + functionName + '(String c1, String c2, num ratio) {'); + func.push(' ratio = Math.max(Math.min(ratio, 1), 0);'); + func.push(' int r1 = int.parse(\'0x${c1.substring(1, 3)}\');'); + func.push(' int g1 = int.parse(\'0x${c1.substring(3, 5)}\');'); + func.push(' int b1 = int.parse(\'0x${c1.substring(5, 7)}\');'); + func.push(' int r2 = int.parse(\'0x${c2.substring(1, 3)}\');'); + func.push(' int g2 = int.parse(\'0x${c2.substring(3, 5)}\');'); + func.push(' int b2 = int.parse(\'0x${c2.substring(5, 7)}\');'); + func.push(' num rn = (r1 * (1 - ratio) + r2 * ratio).round();'); + func.push(' String rs = rn.toInt().toRadixString(16);'); + func.push(' num gn = (g1 * (1 - ratio) + g2 * ratio).round();'); + func.push(' String gs = gn.toInt().toRadixString(16);'); + func.push(' num bn = (b1 * (1 - ratio) + b2 * ratio).round();'); + func.push(' String bs = bn.toInt().toRadixString(16);'); + func.push(' rs = \'0$rs\';'); + func.push(' rs = rs.substring(rs.length - 2);'); + func.push(' gs = \'0$gs\';'); + func.push(' gs = gs.substring(gs.length - 2);'); + func.push(' bs = \'0$bs\';'); + func.push(' bs = bs.substring(bs.length - 2);'); + func.push(' return \'#$rs$gs$bs\';'); + func.push('}'); + Blockly.Dart.definitions_['colour_blend'] = func.join('\n'); + } + var code = Blockly.Dart.colour_blend.functionName + + '(' + c1 + ', ' + c2 + ', ' + ratio + ')'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; diff --git a/generators/dart/lists.js b/generators/dart/lists.js new file mode 100644 index 000000000..1b72efe5a --- /dev/null +++ b/generators/dart/lists.js @@ -0,0 +1,290 @@ +/** + * Visual Blocks Language + * + * Copyright 2012 Google Inc. + * http://blockly.googlecode.com/ + * + * 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 Generating Dart for list blocks. + * @author fraser@google.com (Neil Fraser) + */ +'use strict'; + +goog.provide('Blockly.Dart.lists'); + +goog.require('Blockly.Dart'); + +Blockly.Dart.addReservedWords('Math'); + +Blockly.Dart.lists_create_empty = function() { + // Create an empty list. + return ['[]', Blockly.Dart.ORDER_ATOMIC]; +}; + +Blockly.Dart.lists_create_with = function() { + // Create a list with any number of elements of any type. + var code = new Array(this.itemCount_); + for (var n = 0; n < this.itemCount_; n++) { + code[n] = Blockly.Dart.valueToCode(this, 'ADD' + n, + Blockly.Dart.ORDER_NONE) || 'null'; + } + var code = '[' + code.join(', ') + ']'; + return [code, Blockly.Dart.ORDER_ATOMIC]; +}; + +Blockly.Dart.lists_repeat = function() { + // Create a list with one element repeated. + if (!Blockly.Dart.definitions_['lists_repeat']) { + // Function adapted from Closure's goog.array.repeat. + var functionName = Blockly.Dart.variableDB_.getDistinctName('lists_repeat', + Blockly.Generator.NAME_TYPE); + Blockly.Dart.lists_repeat.repeat = functionName; + var func = []; + func.push('List ' + functionName + '(value, n) {'); + func.push(' var array = new List(n);'); + func.push(' for (int i = 0; i < n; i++) {'); + func.push(' array[i] = value;'); + func.push(' }'); + func.push(' return array;'); + func.push('}'); + Blockly.Dart.definitions_['lists_repeat'] = func.join('\n'); + } + var argument0 = Blockly.Dart.valueToCode(this, 'ITEM', + Blockly.Dart.ORDER_NONE) || 'null'; + var argument1 = Blockly.Dart.valueToCode(this, 'NUM', + Blockly.Dart.ORDER_NONE) || '0'; + var code = Blockly.Dart.lists_repeat.repeat + + '(' + argument0 + ', ' + argument1 + ')'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; + +Blockly.Dart.lists_length = function() { + // List length. + var argument0 = Blockly.Dart.valueToCode(this, 'VALUE', + Blockly.Dart.ORDER_UNARY_POSTFIX) || '[]'; + return [argument0 + '.length', Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; + +Blockly.Dart.lists_isEmpty = function() { + // Is the list empty? + var argument0 = Blockly.Dart.valueToCode(this, 'VALUE', + Blockly.Dart.ORDER_UNARY_POSTFIX) || '[]'; + return [argument0 + '.isEmpty', Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; + +Blockly.Dart.lists_indexOf = function() { + // Find an item in the list. + var operator = this.getTitleValue('END') == 'FIRST' ? + 'indexOf' : 'lastIndexOf'; + var argument0 = Blockly.Dart.valueToCode(this, 'FIND', + Blockly.Dart.ORDER_NONE) || '\'\''; + var argument1 = Blockly.Dart.valueToCode(this, 'VALUE', + Blockly.Dart.ORDER_UNARY_POSTFIX) || '[]'; + var code = argument1 + '.' + operator + '(' + argument0 + ') + 1'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; + +Blockly.Dart.lists_getIndex = function() { + // Get element at index. + // Note: Until January 2013 this block did not have MODE or WHERE inputs. + var mode = this.getTitleValue('MODE') || 'GET'; + var where = this.getTitleValue('WHERE') || 'FROM_START'; + var at = Blockly.Dart.valueToCode(this, 'AT', + Blockly.Dart.ORDER_UNARY_PREFIX) || '1'; + var list = Blockly.Dart.valueToCode(this, 'VALUE', + Blockly.Dart.ORDER_UNARY_POSTFIX) || '[]'; + + if (where == 'FIRST') { + if (mode == 'GET') { + var code = list + '.first'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + } else if (mode == 'GET_REMOVE') { + var code = list + '.removeAt(0)'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + } else if (mode == 'REMOVE') { + return list + '.removeAt(0);\n'; + } + } else if (where == 'LAST') { + if (mode == 'GET') { + var code = list + '.last'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + } else if (mode == 'GET_REMOVE') { + var code = list + '.removeLast()'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + } else if (mode == 'REMOVE') { + return list + '.removeLast();\n'; + } + } else if (where == 'FROM_START') { + // Blockly uses one-based indicies. + if (at.match(/^-?\d+$/)) { + // If the index is a naked number, decrement it right now. + at = parseInt(at, 10) - 1; + } else { + // If the index is dynamic, decrement it in code. + at += ' - 1'; + } + if (mode == 'GET') { + var code = list + '[' + at + ']'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + } else if (mode == 'GET_REMOVE') { + var code = list + '.removeAt(' + at + ')'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + } else if (mode == 'REMOVE') { + return list + '.removeAt(' + at + ');\n'; + } + } else if (where == 'FROM_END') { + if (mode == 'GET') { + if (!Blockly.Dart.definitions_['lists_get_from_end']) { + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'lists_get_from_end', Blockly.Generator.NAME_TYPE); + Blockly.Dart.lists_getIndex.lists_get_from_end = functionName; + var func = []; + func.push('dynamic ' + functionName + '(List myList, num x) {'); + func.push(' x = myList.length - x;'); + func.push(' return myList.removeAt(x);'); + func.push('}'); + Blockly.Dart.definitions_['lists_get_from_end'] = func.join('\n'); + } + code = Blockly.Dart.lists_getIndex.lists_get_from_end + + '(' + list + ', ' + at + ')'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + } else if (mode == 'GET_REMOVE' || mode == 'REMOVE') { + if (!Blockly.Dart.definitions_['lists_remove_from_end']) { + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'lists_remove_from_end', Blockly.Generator.NAME_TYPE); + Blockly.Dart.lists_getIndex.lists_remove_from_end = functionName; + var func = []; + func.push('dynamic ' + functionName + '(List myList, num x) {'); + func.push(' x = myList.length - x;'); + func.push(' return myList.removeAt(x);'); + func.push('}'); + Blockly.Dart.definitions_['lists_remove_from_end'] = func.join('\n'); + } + code = Blockly.Dart.lists_getIndex.lists_remove_from_end + + '(' + list + ', ' + at + ')'; + if (mode == 'GET_REMOVE') { + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + } else if (mode == 'REMOVE') { + return code + ';\n'; + } + } + } else if (where == 'RANDOM') { + if (!Blockly.Dart.definitions_['lists_get_random_item']) { + Blockly.Dart.definitions_['import_dart_math'] = + 'import \'dart:math\' as Math;'; + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'lists_get_random_item', Blockly.Generator.NAME_TYPE); + Blockly.Dart.lists_getIndex.random = functionName; + var func = []; + func.push('dynamic ' + functionName + '(List myList, bool remove) {'); + func.push(' int x = new Math.Random().nextInt(myList.length);'); + func.push(' if (remove) {'); + func.push(' return myList.removeAt(x);'); + func.push(' } else {'); + func.push(' return myList[x];'); + func.push(' }'); + func.push('}'); + Blockly.Dart.definitions_['lists_get_random_item'] = func.join('\n'); + } + code = Blockly.Dart.lists_getIndex.random + + '(' + list + ', ' + (mode != 'GET') + ')'; + if (mode == 'GET' || mode == 'GET_REMOVE') { + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + } else if (mode == 'REMOVE') { + return code + ';\n'; + } + } + throw 'Unhandled combination (lists_getIndex).'; +}; + +Blockly.Dart.lists_setIndex = function() { + // Set element at index. + // Note: Until February 2013 this block did not have MODE or WHERE inputs. + var list = Blockly.Dart.valueToCode(this, 'LIST', + Blockly.Dart.ORDER_UNARY_POSTFIX) || '[]'; + var mode = this.getTitleValue('MODE') || 'GET'; + var where = this.getTitleValue('WHERE') || 'FROM_START'; + var at = Blockly.Dart.valueToCode(this, 'AT', + Blockly.Dart.ORDER_ADDITIVE) || '1'; + var value = Blockly.Dart.valueToCode(this, 'TO', + Blockly.Dart.ORDER_ASSIGNMENT) || 'null'; + // Cache non-trivial values to variables to prevent repeated look-ups. + // Closure, which accesses and modifies 'list'. + function cacheList() { + if (list.match(/^\w+$/)) { + return ''; + } + var listVar = Blockly.Dart.variableDB_.getDistinctName( + 'tmp_list', Blockly.Variables.NAME_TYPE); + var code = 'List ' + listVar + ' = ' + list + ';\n'; + list = listVar; + return code; + } + if (where == 'FIRST') { + if (mode == 'SET') { + return list + '[0] = ' + value + ';\n'; + } else if (mode == 'INSERT') { + return list + '.insertRange(0, 1, ' + value + ');\n'; + } + } else if (where == 'LAST') { + if (mode == 'SET') { + var code = cacheList(); + code += list + '[' + list + '.length - 1] = ' + value + ';\n'; + return code; + } else if (mode == 'INSERT') { + return list + '.addLast(' + value + ');\n'; + } + } else if (where == 'FROM_START') { + // Blockly uses one-based indicies. + if (at.match(/^\d+$/)) { + // If the index is a naked number, decrement it right now. + at = parseInt(at, 10) - 1; + } else { + // If the index is dynamic, decrement it in code. + at += ' - 1'; + } + if (mode == 'SET') { + return list + '[' + at + '] = ' + value + ';\n'; + } else if (mode == 'INSERT') { + return list + '.insertRange(' + at + ', 1, ' + value + ');\n'; + } + } else if (where == 'FROM_END') { + var code = cacheList(); + if (mode == 'SET') { + code += list + '[' + list + '.length - ' + at + '] = ' + value + ';\n'; + return code; + } else if (mode == 'INSERT') { + code += list + '.insertRange(' + list + '.length - ' + at + ', 1, ' + + value + ');\n'; + return code; + } + } else if (where == 'RANDOM') { + Blockly.Dart.definitions_['import_dart_math'] = + 'import \'dart:math\' as Math;'; + var code = cacheList(); + var xVar = Blockly.Dart.variableDB_.getDistinctName( + 'tmp_x', Blockly.Variables.NAME_TYPE); + code += 'int ' + xVar + ' = new Math.Random().nextInt(' + list + '.length);'; + if (mode == 'SET') { + code += list + '[' + xVar + '] = ' + value + ';\n'; + return code; + } else if (mode == 'INSERT') { + code += list + '.insertRange(' + xVar + ', 1, ' + value + ');\n'; + return code; + } + } + throw 'Unhandled combination (lists_setIndex).'; +}; diff --git a/generators/dart/logic.js b/generators/dart/logic.js new file mode 100644 index 000000000..46c650c44 --- /dev/null +++ b/generators/dart/logic.js @@ -0,0 +1,91 @@ +/** + * Visual Blocks Language + * + * Copyright 2012 Google Inc. + * http://blockly.googlecode.com/ + * + * 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 Generating Dart for logic blocks. + * @author q.neutron@gmail.com (Quynh Neutron) + */ +'use strict'; + +goog.provide('Blockly.Dart.logic'); + +goog.require('Blockly.Dart'); + +Blockly.Dart.logic_compare = function() { + // Comparison operator. + var mode = this.getTitleValue('OP'); + var operator = Blockly.Dart.logic_compare.OPERATORS[mode]; + var order = (operator == '==' || operator == '!=') ? + Blockly.Dart.ORDER_EQUALITY : Blockly.Dart.ORDER_RELATIONAL; + var argument0 = Blockly.Dart.valueToCode(this, 'A', order) || '0'; + var argument1 = Blockly.Dart.valueToCode(this, 'B', order) || '0'; + var code = argument0 + ' ' + operator + ' ' + argument1; + return [code, order]; +}; + +Blockly.Dart.logic_compare.OPERATORS = { + EQ: '==', + NEQ: '!=', + LT: '<', + LTE: '<=', + GT: '>', + GTE: '>=' +}; + +Blockly.Dart.logic_operation = function() { + // Operations 'and', 'or'. + var operator = (this.getTitleValue('OP') == 'AND') ? '&&' : '||'; + var order = (operator == '&&') ? Blockly.Dart.ORDER_LOGICAL_AND : + Blockly.Dart.ORDER_LOGICAL_OR; + var argument0 = Blockly.Dart.valueToCode(this, 'A', order) || 'false'; + var argument1 = Blockly.Dart.valueToCode(this, 'B', order) || 'false'; + var code = argument0 + ' ' + operator + ' ' + argument1; + return [code, order]; +}; + +Blockly.Dart.logic_negate = function() { + // Negation. + var order = Blockly.Dart.ORDER_UNARY_PREFIX; + var argument0 = Blockly.Dart.valueToCode(this, 'BOOL', order) || 'false'; + var code = '!' + argument0; + return [code, order]; +}; + +Blockly.Dart.logic_boolean = function() { + // Boolean values true and false. + var code = (this.getTitleValue('BOOL') == 'TRUE') ? 'true' : 'false'; + return [code, Blockly.Dart.ORDER_ATOMIC]; +}; + +Blockly.Dart.logic_null = function() { + // Null data type. + return ['null', Blockly.Dart.ORDER_ATOMIC]; +}; + +Blockly.Dart.logic_ternary = function() { + // Ternary operator. + var value_if = Blockly.Dart.valueToCode(this, 'IF', + Blockly.Dart.ORDER_CONDITIONAL) || 'false'; + var value_then = Blockly.Dart.valueToCode(this, 'THEN', + Blockly.Dart.ORDER_CONDITIONAL) || 'null'; + var value_else = Blockly.Dart.valueToCode(this, 'ELSE', + Blockly.Dart.ORDER_CONDITIONAL) || 'null'; + var code = value_if + ' ? ' + value_then + ' : ' + value_else + return [code, Blockly.Dart.ORDER_CONDITIONAL]; +}; diff --git a/generators/dart/loops.js b/generators/dart/loops.js new file mode 100644 index 000000000..4e044196a --- /dev/null +++ b/generators/dart/loops.js @@ -0,0 +1,158 @@ +/** + * Visual Blocks Language + * + * Copyright 2012 Google Inc. + * http://blockly.googlecode.com/ + * + * 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 Generating Dart for control blocks. + * @author fraser@google.com (Neil Fraser) + */ +'use strict'; + +goog.provide('Blockly.Dart.control'); + +goog.require('Blockly.Dart'); + +Blockly.Dart.controls_if = function() { + // If/elseif/else condition. + var n = 0; + var argument = Blockly.Dart.valueToCode(this, 'IF' + n, + Blockly.Dart.ORDER_NONE) || 'false'; + var branch = Blockly.Dart.statementToCode(this, 'DO' + n); + var code = 'if (' + argument + ') {\n' + branch + '}'; + for (n = 1; n <= this.elseifCount_; n++) { + argument = Blockly.Dart.valueToCode(this, 'IF' + n, + Blockly.Dart.ORDER_NONE) || 'false'; + branch = Blockly.Dart.statementToCode(this, 'DO' + n); + code += ' else if (' + argument + ') {\n' + branch + '}'; + } + if (this.elseCount_) { + branch = Blockly.Dart.statementToCode(this, 'ELSE'); + code += ' else {\n' + branch + '}'; + } + return code + '\n'; +}; + +Blockly.Dart.controls_repeat = function() { + // Repeat n times. + var repeats = Number(this.getTitleValue('TIMES')); + var branch = Blockly.Dart.statementToCode(this, 'DO'); + if (Blockly.Dart.INFINITE_LOOP_TRAP) { + branch = Blockly.Dart.INFINITE_LOOP_TRAP.replace(/%1/g, + '\'' + this.id + '\'') + branch; + } + var loopVar = Blockly.Dart.variableDB_.getDistinctName( + 'count', Blockly.Variables.NAME_TYPE); + var code = 'for (int ' + loopVar + ' = 0; ' + + loopVar + ' < ' + repeats + '; ' + + loopVar + '++) {\n' + + branch + '}\n'; + return code; +}; + +Blockly.Dart.controls_whileUntil = function() { + // Do while/until loop. + var argument0 = Blockly.Dart.valueToCode(this, 'BOOL', + Blockly.Dart.ORDER_NONE) || 'false'; + var branch = Blockly.Dart.statementToCode(this, 'DO'); + if (Blockly.Dart.INFINITE_LOOP_TRAP) { + branch = Blockly.Dart.INFINITE_LOOP_TRAP.replace(/%1/g, + '\'' + this.id + '\'') + branch; + } + if (this.getTitleValue('MODE') == 'UNTIL') { + if (!argument0.match(/^\w+$/)) { + argument0 = '(' + argument0 + ')'; + } + argument0 = '!' + argument0; + } + return 'while (' + argument0 + ') {\n' + branch + '}\n'; +}; + +Blockly.Dart.controls_for = function() { + // For loop. + var variable0 = Blockly.Dart.variableDB_.getName( + this.getTitleValue('VAR'), Blockly.Variables.NAME_TYPE); + var argument0 = Blockly.Dart.valueToCode(this, 'FROM', + Blockly.Dart.ORDER_ASSIGNMENT) || '0'; + var argument1 = Blockly.Dart.valueToCode(this, 'TO', + Blockly.Dart.ORDER_ASSIGNMENT) || '0'; + var branch = Blockly.Dart.statementToCode(this, 'DO'); + if (Blockly.Dart.INFINITE_LOOP_TRAP) { + branch = Blockly.Dart.INFINITE_LOOP_TRAP.replace(/%1/g, + '\'' + this.id + '\'') + branch; + } + var code; + if (argument0.match(/^-?\d+(\.\d+)?$/) && + argument1.match(/^-?\d+(\.\d+)?$/)) { + // Both arguments are simple numbers. + var up = parseFloat(argument0) <= parseFloat(argument1); + code = 'for (num ' + variable0 + ' = ' + argument0 + '; ' + + variable0 + (up ? ' <= ' : ' >= ') + argument1 + '; ' + + variable0 + (up ? '++' : '--') + ') {\n' + + branch + '}\n'; + } else { + code = ''; + // Cache non-trivial values to variables to prevent repeated look-ups. + var startVar = argument0; + if (!argument0.match(/^\w+$/) && !argument0.match(/^-?\d+(\.\d+)?$/)) { + var startVar = Blockly.Dart.variableDB_.getDistinctName( + variable0 + '_start', Blockly.Variables.NAME_TYPE); + code += 'var ' + startVar + ' = ' + argument0 + ';\n'; + } + var endVar = argument1; + if (!argument1.match(/^\w+$/) && !argument1.match(/^-?\d+(\.\d+)?$/)) { + var endVar = Blockly.Dart.variableDB_.getDistinctName( + variable0 + '_end', Blockly.Variables.NAME_TYPE); + code += 'var ' + endVar + ' = ' + argument1 + ';\n'; + } + code += 'for (' + variable0 + ' = ' + startVar + ';\n' + + ' (' + startVar + ' <= ' + endVar + ') ? ' + + variable0 + ' <= ' + endVar + ' : ' + + variable0 + ' >= ' + endVar + ';\n' + + ' ' + variable0 + ' += (' + startVar + ' <= ' + endVar + + ') ? 1 : -1) {\n' + + branch + '}\n'; + } + return code; +}; + +Blockly.Dart.controls_forEach = function() { + // For each loop. + var variable0 = Blockly.Dart.variableDB_.getName( + this.getTitleValue('VAR'), Blockly.Variables.NAME_TYPE); + var argument0 = Blockly.Dart.valueToCode(this, 'LIST', + Blockly.Dart.ORDER_ASSIGNMENT) || '[]'; + var branch = Blockly.Dart.statementToCode(this, 'DO'); + if (Blockly.Dart.INFINITE_LOOP_TRAP) { + branch = Blockly.Dart.INFINITE_LOOP_TRAP.replace(/%1/g, + '\'' + this.id + '\'') + branch; + } + var code = 'for (var ' + variable0 + ' in ' + argument0 + ') {\n' + + branch + '}\n'; + return code; +}; + +Blockly.Dart.controls_flow_statements = function() { + // Flow statements: continue, break. + switch (this.getTitleValue('FLOW')) { + case 'BREAK': + return 'break;\n'; + case 'CONTINUE': + return 'continue;\n'; + } + throw 'Unknown flow statement.'; +}; diff --git a/generators/dart/math.js b/generators/dart/math.js new file mode 100644 index 000000000..eba373d00 --- /dev/null +++ b/generators/dart/math.js @@ -0,0 +1,516 @@ +/** + * Visual Blocks Language + * + * Copyright 2012 Google Inc. + * http://blockly.googlecode.com/ + * + * 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 Generating Dart for math blocks. + * @author q.neutron@gmail.com (Quynh Neutron) + */ +'use strict'; + +goog.provide('Blockly.Dart.math'); + +goog.require('Blockly.Dart'); + +Blockly.Dart.addReservedWords('Math'); + +Blockly.Dart.math_number = function() { + // Numeric value. + var code = window.parseFloat(this.getTitleValue('NUM')); + // -4.abs() returns -4 in Dart due to strange order of operation choices. + // -4 is actually an operator and a number. Reflect this in the order. + var order = code < 0 ? + Blockly.Dart.ORDER_UNARY_PREFIX : Blockly.Dart.ORDER_ATOMIC; + return [code, order]; +}; + +Blockly.Dart.math_arithmetic = function() { + // Basic arithmetic operators, and power. + var mode = this.getTitleValue('OP'); + var tuple = Blockly.Dart.math_arithmetic.OPERATORS[mode]; + var operator = tuple[0]; + var order = tuple[1]; + var argument0 = Blockly.Dart.valueToCode(this, 'A', order) || '0'; + var argument1 = Blockly.Dart.valueToCode(this, 'B', order) || '0'; + var code; + // Power in Dart requires a special case since it has no operator. + if (!operator) { + Blockly.Dart.definitions_['import_dart_math'] = + 'import \'dart:math\' as Math;'; + code = 'Math.pow(' + argument0 + ', ' + argument1 + ')'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + } + code = argument0 + operator + argument1; + return [code, order]; +}; + +Blockly.Dart.math_arithmetic.OPERATORS = { + ADD: [' + ', Blockly.Dart.ORDER_ADDITIVE], + MINUS: [' - ', Blockly.Dart.ORDER_ADDITIVE], + MULTIPLY: [' * ', Blockly.Dart.ORDER_MULTIPLICATIVE], + DIVIDE: [' / ', Blockly.Dart.ORDER_MULTIPLICATIVE], + POWER: [null, Blockly.Dart.ORDER_NONE] // Handle power separately. +}; + +Blockly.Dart.math_single = function() { + // Math operators with single operand. + var operator = this.getTitleValue('OP'); + var code; + var arg; + if (operator == 'NEG') { + // Negation is a special case given its different operator precedence. + arg = Blockly.Dart.valueToCode(this, 'NUM', + Blockly.Dart.ORDER_UNARY_PREFIX) || '0'; + if (arg[0] == '-') { + // --3 is not legal in Dart. + arg = ' ' + arg; + } + code = '-' + arg; + return [code, Blockly.Dart.ORDER_UNARY_PREFIX]; + } + Blockly.Dart.definitions_['import_dart_math'] = + 'import \'dart:math\' as Math;'; + if (operator == 'ABS' || operator.substring(0, 5) == 'ROUND') { + arg = Blockly.Dart.valueToCode(this, 'NUM', + Blockly.Dart.ORDER_UNARY_POSTFIX) || '0'; + } else if (operator == 'SIN' || operator == 'COS' || operator == 'TAN') { + arg = Blockly.Dart.valueToCode(this, 'NUM', + Blockly.Dart.ORDER_MULTIPLICATIVE) || '0'; + } else { + arg = Blockly.Dart.valueToCode(this, 'NUM', + Blockly.Dart.ORDER_NONE) || '0'; + } + // First, handle cases which generate values that don't need parentheses. + switch (operator) { + case 'ABS': + code = arg + '.abs()'; + break; + case 'ROOT': + code = 'Math.sqrt(' + arg + ')'; + break; + case 'LN': + code = 'Math.log(' + arg + ')'; + break; + case 'EXP': + code = 'Math.exp(' + arg + ')'; + break; + case 'POW10': + code = 'Math.pow(10,' + arg + ')'; + break; + case 'ROUND': + code = arg + '.round()'; + break; + case 'ROUNDUP': + code = arg + '.ceil()'; + break; + case 'ROUNDDOWN': + code = arg + '.floor()'; + break; + case 'SIN': + code = 'Math.sin(' + arg + ' / 180 * Math.PI)'; + break; + case 'COS': + code = 'Math.cos(' + arg + ' / 180 * Math.PI)'; + break; + case 'TAN': + code = 'Math.tan(' + arg + ' / 180 * Math.PI)'; + break; + } + if (code) { + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + } + // Second, handle cases which generate values that may need parentheses. + switch (operator) { + case 'LOG10': + code = 'Math.log(' + arg + ') / Math.log(10)'; + break; + case 'ASIN': + code = 'Math.asin(' + arg + ') / Math.PI * 180'; + break; + case 'ACOS': + code = 'Math.acos(' + arg + ') / Math.PI * 180'; + break; + case 'ATAN': + code = 'Math.atan(' + arg + ') / Math.PI * 180'; + break; + default: + throw 'Unknown math operator: ' + operator; + } + return [code, Blockly.Dart.ORDER_MULTIPLICATIVE]; +}; + +Blockly.Dart.math_constant = function() { + // Constants: PI, E, the Golden Ratio, sqrt(2), 1/sqrt(2), INFINITY. + var constant = this.getTitleValue('CONSTANT'); + if (constant != 'INFINITY') { + Blockly.Dart.definitions_['import_dart_math'] = + 'import \'dart:math\' as Math;'; + } + return Blockly.Dart.math_constant.CONSTANTS[constant]; +}; + +Blockly.Dart.math_constant.CONSTANTS = { + PI: ['Math.PI', Blockly.Dart.ORDER_UNARY_POSTFIX], + E: ['Math.E', Blockly.Dart.ORDER_UNARY_POSTFIX], + GOLDEN_RATIO: ['(1 + Math.sqrt(5)) / 2', Blockly.Dart.ORDER_MULTIPLICATIVE], + SQRT2: ['Math.SQRT2', Blockly.Dart.ORDER_UNARY_POSTFIX], + SQRT1_2: ['Math.SQRT1_2', Blockly.Dart.ORDER_UNARY_POSTFIX], + INFINITY: ['double.INFINITY', Blockly.Dart.ORDER_ATOMIC] +}; + +Blockly.Dart.math_number_property = function() { + // Check if a number is even, odd, prime, whole, positive, or negative + // or if it is divisible by certain number. Returns true or false. + var number_to_check = Blockly.Dart.valueToCode(this, 'NUMBER_TO_CHECK', + Blockly.Dart.ORDER_MULTIPLICATIVE); + if (!number_to_check) { + return ['false', Blockly.Python.ORDER_ATOMIC]; + } + var dropdown_property = this.getTitleValue('PROPERTY'); + var code; + if (dropdown_property == 'PRIME') { + // Prime is a special case as it is not a one-liner test. + if (!Blockly.Dart.definitions_['isPrime']) { + Blockly.Dart.definitions_['import_dart_math'] = + 'import \'dart:math\' as Math;'; + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'isPrime', Blockly.Generator.NAME_TYPE); + Blockly.Dart.logic_prime= functionName; + var func = []; + func.push('bool ' + functionName + '(n) {'); + func.push(' // http://en.wikipedia.org/wiki/Primality_test#Naive_methods'); + func.push(' if (n == 2 || n == 3) {'); + func.push(' return true;'); + func.push(' }'); + func.push(' // False if n is null, negative, is 1, or not whole.'); + func.push(' // And false if n is divisible by 2 or 3.'); + func.push(' if (n == null || n <= 1 || n % 1 != 0 || n % 2 == 0 ||' + + ' n % 3 == 0) {'); + func.push(' return false;'); + func.push(' }'); + func.push(' // Check all the numbers of form 6k +/- 1, up to sqrt(n).'); + func.push(' for (var x = 6; x <= Math.sqrt(n) + 1; x += 6) {'); + func.push(' if (n % (x - 1) == 0 || n % (x + 1) == 0) {'); + func.push(' return false;'); + func.push(' }'); + func.push(' }'); + func.push(' return true;'); + func.push('}'); + Blockly.Dart.definitions_['isPrime'] = func.join('\n'); + } + code = Blockly.Dart.logic_prime + '(' + number_to_check + ')'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + } + switch (dropdown_property) { + case 'EVEN': + code = number_to_check + ' % 2 == 0'; + break; + case 'ODD': + code = number_to_check + ' % 2 == 1'; + break; + case 'WHOLE': + code = number_to_check + ' % 1 == 0'; + break; + case 'POSITIVE': + code = number_to_check + ' > 0'; + break; + case 'NEGATIVE': + code = number_to_check + ' < 0'; + break; + case 'DIVISIBLE_BY': + var divisor = Blockly.Dart.valueToCode(this, 'DIVISOR', + Blockly.Dart.ORDER_MULTIPLICATIVE); + if (!divisor) { + return ['false', Blockly.Python.ORDER_ATOMIC]; + } + code = number_to_check + ' % ' + divisor + ' == 0'; + break; + } + return [code, Blockly.Dart.ORDER_EQUALITY]; +}; + +Blockly.Dart.math_change = function() { + // Add to a variable in place. + var argument0 = Blockly.Dart.valueToCode(this, 'DELTA', + Blockly.Dart.ORDER_ADDITIVE) || '0'; + var varName = Blockly.Dart.variableDB_.getName(this.getTitleValue('VAR'), + Blockly.Variables.NAME_TYPE); + return varName + ' = (' + varName + ' is num ? ' + varName + ' : 0) + ' + + argument0 + ';\n'; +}; + +// Rounding functions have a single operand. +Blockly.Dart.math_round = Blockly.Dart.math_single; +// Trigonometry functions have a single operand. +Blockly.Dart.math_trig = Blockly.Dart.math_single; + +Blockly.Dart.math_on_list = function() { + // Math functions for lists. + var func = this.getTitleValue('OP'); + var list = Blockly.Dart.valueToCode(this, 'LIST', + Blockly.Dart.ORDER_NONE) || '[]'; + var code; + switch (func) { + case 'SUM': + if (!Blockly.Dart.definitions_['math_sum']) { + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'math_sum', Blockly.Generator.NAME_TYPE); + Blockly.Dart.math_on_list.math_sum = functionName; + var func = []; + func.push('num ' + functionName + '(List myList) {'); + func.push(' num sumVal = 0;'); + func.push(' myList.forEach((num entry) {sumVal += entry;});'); + func.push(' return sumVal;'); + func.push('}'); + Blockly.Dart.definitions_['math_sum'] = func.join('\n'); + } + code = Blockly.Dart.math_on_list.math_sum + '(' + list + ')'; + break; + case 'MIN': + if (!Blockly.Dart.definitions_['math_min']) { + Blockly.Dart.definitions_['import_dart_math'] = + 'import \'dart:math\' as Math;'; + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'math_min', Blockly.Generator.NAME_TYPE); + Blockly.Dart.math_on_list.math_min = functionName; + var func = []; + func.push('num ' + functionName + '(List myList) {'); + func.push(' if (myList.isEmpty) return null;'); + func.push(' num minVal = myList[0];'); + func.push(' myList.forEach((num entry) ' + + '{minVal = Math.min(minVal, entry);});'); + func.push(' return minVal;'); + func.push('}'); + Blockly.Dart.definitions_['math_min'] = func.join('\n'); + } + code = Blockly.Dart.math_on_list.math_min + '(' + list + ')'; + break; + case 'MAX': + if (!Blockly.Dart.definitions_['math_max']) { + Blockly.Dart.definitions_['import_dart_math'] = + 'import \'dart:math\' as Math;'; + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'math_max', Blockly.Generator.NAME_TYPE); + Blockly.Dart.math_on_list.math_max = functionName; + var func = []; + func.push('num ' + functionName + '(List myList) {'); + func.push(' if (myList.isEmpty) return null;'); + func.push(' num maxVal = myList[0];'); + func.push(' myList.forEach((num entry) ' + + '{maxVal = Math.max(maxVal, entry);});'); + func.push(' return maxVal;'); + func.push('}'); + Blockly.Dart.definitions_['math_max'] = func.join('\n'); + Blockly.Dart.definitions_['import_dart_math'] = + 'import \'dart:math\' as Math;'; + } + code = Blockly.Dart.math_on_list.math_max + '(' + list + ')'; + break; + case 'AVERAGE': + // This operation exclude null and values that are not int or float: + // math_mean([null,null,"aString",1,9]) == 5.0. + if (!Blockly.Dart.definitions_['math_average']) { + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'math_average', Blockly.Generator.NAME_TYPE); + Blockly.Dart.math_on_list.math_average = functionName; + var func = []; + func.push('num ' + functionName + '(List myList) {'); + func.push(' // First filter list for numbers only.'); + func.push(' List localList = new List.from(myList);'); + func.push(' localList.removeMatching((a) => a is! num);'); + func.push(' if (localList.isEmpty) return null;'); + func.push(' num sumVal = 0;'); + func.push(' localList.forEach((num entry) {sumVal += entry;});'); + func.push(' return sumVal / localList.length;'); + func.push('}'); + Blockly.Dart.definitions_['math_average'] = func.join('\n'); + } + code = Blockly.Dart.math_on_list.math_average + '(' + list + ')'; + break; + case 'MEDIAN': + if (!Blockly.Dart.definitions_['math_median']) { + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'math_median', Blockly.Generator.NAME_TYPE); + Blockly.Dart.math_on_list.math_median = functionName; + var func = []; + func.push('num ' + functionName + '(List myList) {'); + func.push(' // First filter list for numbers only, then sort, ' + + 'then return middle value'); + func.push(' // or the average of two middle values if list has an ' + + 'even number of elements.'); + func.push(' List localList = new List.from(myList);'); + func.push(' localList.removeMatching((a) => a is! num);'); + func.push(' if (localList.isEmpty) return null;'); + func.push(' localList.sort((a, b) => (a - b));'); + func.push(' int index = localList.length ~/ 2;'); + func.push(' if (localList.length % 2 == 1) {'); + func.push(' return localList[index];'); + func.push(' } else {'); + func.push(' return (localList[index - 1] + localList[index]) / 2;'); + func.push(' }'); + func.push('}'); + Blockly.Dart.definitions_['math_median'] = func.join('\n'); + } + code = Blockly.Dart.math_on_list.math_median + '(' + list + ')'; + break; + case 'MODE': + if (!Blockly.Dart.definitions_['math_modes']) { + Blockly.Dart.definitions_['import_dart_math'] = + 'import \'dart:math\' as Math;'; + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'math_modes', Blockly.Generator.NAME_TYPE); + Blockly.Dart.math_on_list.math_modes = functionName; + // As a list of numbers can contain more than one mode, + // the returned result is provided as an array. + // Mode of [3, 'x', 'x', 1, 1, 2, '3'] -> ['x', 1]. + var func = []; + func.push('List ' + functionName + '(values) {'); + func.push(' List modes = [];'); + func.push(' List counts = [];'); + func.push(' int maxCount = 0;'); + func.push(' for (int i = 0; i < values.length; i++) {'); + func.push(' var value = values[i];'); + func.push(' bool found = false;'); + func.push(' int thisCount;'); + func.push(' for (int j = 0; j < counts.length; j++) {'); + func.push(' if (counts[j][0] == value) {'); + func.push(' thisCount = ++counts[j][1];'); + func.push(' found = true;'); + func.push(' break;'); + func.push(' }'); + func.push(' }'); + func.push(' if (!found) {'); + func.push(' counts.add([value, 1]);'); + func.push(' thisCount = 1;'); + func.push(' }'); + func.push(' maxCount = Math.max(thisCount, maxCount);'); + func.push(' }'); + func.push(' for (int j = 0; j < counts.length; j++) {'); + func.push(' if (counts[j][1] == maxCount) {'); + func.push(' modes.add(counts[j][0]);'); + func.push(' }'); + func.push(' }'); + func.push(' return modes;'); + func.push('}'); + Blockly.Dart.definitions_['math_modes'] = func.join('\n'); + } + code = Blockly.Dart.math_on_list.math_modes + '(' + list + ')'; + break; + case 'STD_DEV': + if (!Blockly.Dart.definitions_['math_standard_deviation']) { + Blockly.Dart.definitions_['import_dart_math'] = + 'import \'dart:math\' as Math;'; + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'math_standard_deviation', Blockly.Generator.NAME_TYPE); + Blockly.Dart.math_on_list.math_standard_deviation = functionName; + var func = []; + func.push('num ' + functionName + '(List myList) {'); + func.push(' // First filter list for numbers only.'); + func.push(' List numbers = new List.from(myList);'); + func.push(' numbers.removeMatching((a) => a is! num);'); + func.push(' if (numbers.isEmpty) return null;'); + func.push(' num n = numbers.length;'); + func.push(' num sum = 0;'); + func.push(' numbers.forEach((x) => sum += x);'); + func.push(' num mean = sum / n;'); + func.push(' num sumSquare = 0;'); + func.push(' numbers.forEach((x) => sumSquare += ' + + 'Math.pow(x - mean, 2));'); + func.push(' return Math.sqrt(sumSquare / n);'); + func.push('}'); + Blockly.Dart.definitions_['math_standard_deviation'] = func.join('\n'); + } + code = Blockly.Dart.math_on_list.math_standard_deviation + + '(' + list + ')'; + break; + case 'RANDOM': + if (!Blockly.Dart.definitions_['math_random_item']) { + Blockly.Dart.definitions_['import_dart_math'] = + 'import \'dart:math\' as Math;'; + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'math_random_item', Blockly.Generator.NAME_TYPE); + Blockly.Dart.math_on_list.math_random_item = functionName; + var func = []; + func.push('dynamic ' + functionName + '(List myList) {'); + func.push(' int x = new Math.Random().nextInt(myList.length);'); + func.push(' return myList[x];'); + func.push('}'); + Blockly.Dart.definitions_['math_random_item'] = func.join('\n'); + } + code = Blockly.Dart.math_on_list.math_random_item + '(' + list + ')'; + break; + default: + throw 'Unknown operator: ' + func; + } + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; + +Blockly.Dart.math_modulo = function() { + // Remainder computation. + var argument0 = Blockly.Dart.valueToCode(this, 'DIVIDEND', + Blockly.Dart.ORDER_MULTIPLICATIVE) || '0'; + var argument1 = Blockly.Dart.valueToCode(this, 'DIVISOR', + Blockly.Dart.ORDER_MULTIPLICATIVE) || '0'; + var code = argument0 + ' % ' + argument1; + return [code, Blockly.Dart.ORDER_MULTIPLICATIVE]; +}; + +Blockly.Dart.math_constrain = function() { + // Constrain a number between two limits. + var argument0 = Blockly.Dart.valueToCode(this, 'VALUE', + Blockly.Dart.ORDER_NONE) || '0'; + var argument1 = Blockly.Dart.valueToCode(this, 'LOW', + Blockly.Dart.ORDER_NONE) || '0'; + var argument2 = Blockly.Dart.valueToCode(this, 'HIGH', + Blockly.Dart.ORDER_NONE) || 'double.INFINITY'; + var code = 'Math.min(Math.max(' + argument0 + ', ' + argument1 + '), ' + + argument2 + ')'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; + +Blockly.Dart.math_random_int = function() { + // Random integer between [X] and [Y]. + var argument0 = Blockly.Dart.valueToCode(this, 'FROM', + Blockly.Dart.ORDER_NONE) || '0'; + var argument1 = Blockly.Dart.valueToCode(this, 'TO', + Blockly.Dart.ORDER_NONE) || '0'; + if (!Blockly.Dart.definitions_['math_random_int']) { + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'math_random_int', Blockly.Generator.NAME_TYPE); + Blockly.Dart.math_random_int.random_function = functionName; + var func = []; + func.push('int ' + functionName + '(num a, num b) {'); + func.push(' if (a > b) {'); + func.push(' // Swap a and b to ensure a is smaller.'); + func.push(' num c = a;'); + func.push(' a = b;'); + func.push(' b = c;'); + func.push(' }'); + func.push(' return new Math.Random().nextInt(b - a + 1) + a;'); + func.push('}'); + Blockly.Dart.definitions_['math_random_int'] = func.join('\n'); + } + var code = Blockly.Dart.math_random_int.random_function + + '(' + argument0 + ', ' + argument1 + ')'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; + +Blockly.Dart.math_random_float = function() { + // Random fraction between 0 and 1. + return ['new Math.Random().nextDouble()', Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; diff --git a/generators/dart/procedures.js b/generators/dart/procedures.js new file mode 100644 index 000000000..07e3c1b21 --- /dev/null +++ b/generators/dart/procedures.js @@ -0,0 +1,101 @@ +/** + * Visual Blocks Language + * + * Copyright 2012 Google Inc. + * http://blockly.googlecode.com/ + * + * 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 Generating Dart for variable blocks. + * @author fraser@google.com (Neil Fraser) + */ +'use strict'; + +goog.provide('Blockly.Dart.procedures'); + +goog.require('Blockly.Dart'); + +Blockly.Dart.procedures_defreturn = function() { + // Define a procedure with a return value. + var funcName = Blockly.Dart.variableDB_.getName(this.getTitleValue('NAME'), + Blockly.Procedures.NAME_TYPE); + var branch = Blockly.Dart.statementToCode(this, 'STACK'); + if (Blockly.Dart.INFINITE_LOOP_TRAP) { + branch = Blockly.Dart.INFINITE_LOOP_TRAP.replace(/%1/g, + '\'' + this.id + '\'') + branch; + } + var returnValue = Blockly.Dart.valueToCode(this, 'RETURN', + Blockly.Dart.ORDER_NONE) || ''; + if (returnValue) { + returnValue = ' return ' + returnValue + ';\n'; + } + var returnType = returnValue ? 'dynamic' : 'void'; + var args = []; + for (var x = 0; x < this.arguments_.length; x++) { + args[x] = Blockly.Dart.variableDB_.getName(this.arguments_[x], + Blockly.Variables.NAME_TYPE); + } + var code = returnType + ' ' + funcName + '(' + args.join(', ') + ') {\n' + + branch + returnValue + '}'; + code = Blockly.Dart.scrub_(this, code); + Blockly.Dart.definitions_[funcName] = code; + return null; +}; + +// Defining a procedure without a return value uses the same generator as +// a procedure with a return value. +Blockly.Dart.procedures_defnoreturn = Blockly.Dart.procedures_defreturn; + +Blockly.Dart.procedures_callreturn = function() { + // Call a procedure with a return value. + var funcName = Blockly.Dart.variableDB_.getName(this.getTitleValue('NAME'), + Blockly.Procedures.NAME_TYPE); + var args = []; + for (var x = 0; x < this.arguments_.length; x++) { + args[x] = Blockly.Dart.valueToCode(this, 'ARG' + x, + Blockly.Dart.ORDER_NONE) || 'null'; + } + var code = funcName + '(' + args.join(', ') + ')'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; + +Blockly.Dart.procedures_callnoreturn = function() { + // Call a procedure with no return value. + var funcName = Blockly.Dart.variableDB_.getName(this.getTitleValue('NAME'), + Blockly.Procedures.NAME_TYPE); + var args = []; + for (var x = 0; x < this.arguments_.length; x++) { + args[x] = Blockly.Dart.valueToCode(this, 'ARG' + x, + Blockly.Dart.ORDER_NONE) || 'null'; + } + var code = funcName + '(' + args.join(', ') + ');\n'; + return code; +}; + +Blockly.Dart.procedures_ifreturn = function() { + // Conditionally return value from a procedure. + var condition = Blockly.Dart.valueToCode(this, 'CONDITION', + Blockly.Dart.ORDER_NONE) || 'false'; + var code = 'if (' + condition + ') {\n'; + if (this.hasReturnValue_) { + var value = Blockly.Dart.valueToCode(this, 'VALUE', + Blockly.Dart.ORDER_NONE) || 'null'; + code += ' return ' + value + ';\n'; + } else { + code += ' return;\n'; + } + code += '}\n'; + return code; +}; diff --git a/generators/dart/text.js b/generators/dart/text.js new file mode 100644 index 000000000..d576cbc45 --- /dev/null +++ b/generators/dart/text.js @@ -0,0 +1,268 @@ +/** + * Visual Blocks Language + * + * Copyright 2012 Google Inc. + * http://blockly.googlecode.com/ + * + * 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 Generating Dart for text blocks. + * @author fraser@google.com (Neil Fraser) + */ +'use strict'; + +goog.provide('Blockly.Dart.text'); + +goog.require('Blockly.Dart'); + +Blockly.Dart.addReservedWords('Html,Math'); + +Blockly.Dart.text = function() { + // Text value. + var code = Blockly.Dart.quote_(this.getTitleValue('TEXT')); + return [code, Blockly.Dart.ORDER_ATOMIC]; +}; + +Blockly.Dart.text_join = function() { + // Create a string made up of any number of elements of any type. + var code; + if (this.itemCount_ == 0) { + return ['\'\'', Blockly.Dart.ORDER_ATOMIC]; + } else if (this.itemCount_ == 1) { + var argument0 = Blockly.Dart.valueToCode(this, 'ADD0', + Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\''; + code = argument0 + '.toString()'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + } else { + code = new Array(this.itemCount_); + for (var n = 0; n < this.itemCount_; n++) { + code[n] = Blockly.Dart.valueToCode(this, 'ADD' + n, + Blockly.Dart.ORDER_NONE) || '\'\''; + } + code = '[' + code.join(',') + '].join()'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + } +}; + +Blockly.Dart.text_append = function() { + // Append to a variable in place. + var varName = Blockly.Dart.variableDB_.getName(this.getTitleValue('VAR'), + Blockly.Variables.NAME_TYPE); + var argument0 = Blockly.Dart.valueToCode(this, 'TEXT', + Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\''; + return varName + ' = [' + varName + ', ' + argument0 + '].join();\n'; +}; + +Blockly.Dart.text_length = function() { + // String length. + var argument0 = Blockly.Dart.valueToCode(this, 'VALUE', + Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\''; + return [argument0 + '.length', Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; + +Blockly.Dart.text_isEmpty = function() { + // Is the string null? + var argument0 = Blockly.Dart.valueToCode(this, 'VALUE', + Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\''; + return [argument0 + '.isEmpty', Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; + +Blockly.Dart.text_endString = function() { + // Return a leading or trailing substring. + var first = this.getTitleValue('END') == 'FIRST'; + var code; + if (first) { + var argument0 = Blockly.Dart.valueToCode(this, 'NUM', + Blockly.Dart.ORDER_NONE) || '1'; + var argument1 = Blockly.Dart.valueToCode(this, 'TEXT', + Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\''; + code = argument1 + '.substring(0, ' + argument0 + ')'; + } else { + if (!Blockly.Dart.definitions_['text_tailString']) { + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'text_tailString', Blockly.Generator.NAME_TYPE); + Blockly.Dart.text_endString.text_tailString = functionName; + var func = []; + func.push('String ' + functionName + '(n, myString) {'); + func.push(' // Return a trailing substring of n characters.'); + func.push(' return myString.substring(myString.length - n);'); + func.push('}'); + Blockly.Dart.definitions_['text_tailString'] = func.join('\n'); + } + var argument0 = Blockly.Dart.valueToCode(this, 'NUM', + Blockly.Dart.ORDER_NONE) || '1'; + var argument1 = Blockly.Dart.valueToCode(this, 'TEXT', + Blockly.Dart.ORDER_NONE) || '\'\''; + code = Blockly.Dart.text_endString.text_tailString + + '(' + argument0 + ', ' + argument1 + ')'; + } + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; + +Blockly.Dart.text_indexOf = function() { + // Search the text for a substring. + var operator = this.getTitleValue('END') == 'FIRST' ? + 'indexOf' : 'lastIndexOf'; + var argument0 = Blockly.Dart.valueToCode(this, 'FIND', + Blockly.Dart.ORDER_NONE) || '\'\''; + var argument1 = Blockly.Dart.valueToCode(this, 'VALUE', + Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\''; + var code = argument1 + '.' + operator + '(' + argument0 + ') + 1'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; + +Blockly.Dart.text_charAt = function() { + // Get letter at index. + // Note: Until January 2013 this block did not have the WHERE input. + var where = this.getTitleValue('WHERE') || 'FROM_START'; + var at = Blockly.Dart.valueToCode(this, 'AT', + Blockly.Dart.ORDER_NONE) || '1'; + var text = Blockly.Dart.valueToCode(this, 'VALUE', + Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\''; + switch (where) { + case 'FIRST': + var code = text + '[0]'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + case 'FROM_START': + // Blockly uses one-based indicies. + if (at.match(/^-?\d+$/)) { + // If the index is a naked number, decrement it right now. + at = parseInt(at, 10) - 1; + } else { + // If the index is dynamic, decrement it in code. + at += ' - 1'; + } + var code = text + '[' + at + ']'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + case 'LAST': + at = 1; + // Fall through. + case 'FROM_END': + if (!Blockly.Dart.definitions_['text_get_from_end']) { + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'text_get_from_end', Blockly.Generator.NAME_TYPE); + Blockly.Dart.text_charAt.text_get_from_end = functionName; + var func = []; + func.push('String ' + functionName + '(String text, num x) {'); + func.push(' return text[text.length - x];'); + func.push('}'); + Blockly.Dart.definitions_['text_get_from_end'] = func.join('\n'); + } + code = Blockly.Dart.text_charAt.text_get_from_end + + '(' + text + ', ' + at + ')'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + case 'RANDOM': + if (!Blockly.Dart.definitions_['text_random_letter']) { + Blockly.Dart.definitions_['import_dart_math'] = + 'import \'dart:math\' as Math;'; + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'text_random_letter', Blockly.Generator.NAME_TYPE); + Blockly.Dart.text_charAt.text_random_letter = functionName; + var func = []; + func.push('String ' + functionName + '(String text) {'); + func.push(' int x = new Math.Random().nextInt(text.length);'); + func.push(' return text[x];'); + func.push('}'); + Blockly.Dart.definitions_['text_random_letter'] = func.join('\n'); + } + code = Blockly.Dart.text_charAt.text_random_letter + + '(' + text + ')'; + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; + } + throw 'Unhandled option (text_charAt).'; +}; + +Blockly.Dart.text_changeCase = function() { + // Change capitalization. + var mode = this.getTitleValue('CASE'); + var operator = Blockly.Dart.text_changeCase.OPERATORS[mode]; + var code; + if (operator) { + // Upper and lower case are functions built into Dart. + var argument0 = Blockly.Dart.valueToCode(this, 'TEXT', + Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\''; + code = argument0 + operator; + } else { + if (!Blockly.Dart.definitions_['toTitleCase']) { + // Title case is not a native Dart function. Define one. + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'text_toTitleCase', Blockly.Generator.NAME_TYPE); + Blockly.Dart.text_changeCase.toTitleCase = functionName; + var func = []; + func.push('String ' + functionName + '(str) {'); + func.push(' RegExp exp = new RegExp(r\'\\b\');'); + func.push(' List list = str.split(exp);'); + func.push(' final title = new StringBuffer();'); + func.push(' for (String part in list) {'); + func.push(' if (part.length > 0) {'); + func.push(' title.write(part[0].toUpperCase());'); + func.push(' if (part.length > 0) {'); + func.push(' title.write(part.substring(1).toLowerCase());'); + func.push(' }'); + func.push(' }'); + func.push(' }'); + func.push(' return title.toString();'); + func.push('}'); + Blockly.Dart.definitions_['toTitleCase'] = func.join('\n'); + } + var argument0 = Blockly.Dart.valueToCode(this, 'TEXT', + Blockly.Dart.ORDER_NONE) || '\'\''; + code = Blockly.Dart.text_changeCase.toTitleCase + '(' + argument0 + ')'; + } + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; + +Blockly.Dart.text_changeCase.OPERATORS = { + UPPERCASE: '.toUpperCase()', + LOWERCASE: '.toLowerCase()', + TITLECASE: null +}; + +Blockly.Dart.text_trim = function() { + // Trim spaces. + var mode = this.getTitleValue('MODE'); + var operator = Blockly.Dart.text_trim.OPERATORS[mode]; + var argument0 = Blockly.Dart.valueToCode(this, 'TEXT', + Blockly.Dart.ORDER_UNARY_POSTFIX) || '\'\''; + return [argument0 + operator, Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; + +Blockly.Dart.text_trim.OPERATORS = { + LEFT: '.replaceFirst(new RegExp(r\'^\\s+\'), \'\')', + RIGHT: '.replaceFirst(new RegExp(r\'\\s+$\'), \'\')', + BOTH: '.trim()' +}; + +Blockly.Dart.text_print = function() { + // Print statement. + var argument0 = Blockly.Dart.valueToCode(this, 'TEXT', + Blockly.Dart.ORDER_NONE) || '\'\''; + return 'print(' + argument0 + ');\n'; +}; + +Blockly.Dart.text_prompt = function() { + // Prompt function. + Blockly.Dart.definitions_['import_dart_html'] = + 'import \'dart:html\' as Html;'; + var msg = Blockly.Dart.quote_(this.getTitleValue('TEXT')); + var code = 'Html.window.prompt(' + msg + ', \'\')'; + var toNumber = this.getTitleValue('TYPE') == 'NUMBER'; + if (toNumber) { + Blockly.Dart.definitions_['import_dart_math'] = + 'import \'dart:math\' as Math;'; + code = 'Math.parseDouble(' + code + ')'; + } + return [code, Blockly.Dart.ORDER_UNARY_POSTFIX]; +}; diff --git a/generators/dart/variables.js b/generators/dart/variables.js new file mode 100644 index 000000000..cc8b60628 --- /dev/null +++ b/generators/dart/variables.js @@ -0,0 +1,44 @@ +/** + * Visual Blocks Language + * + * Copyright 2012 Google Inc. + * http://blockly.googlecode.com/ + * + * 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 Generating Dart for variable blocks. + * @author fraser@google.com (Neil Fraser) + */ +'use strict'; + +goog.provide('Blockly.Dart.variables'); + +goog.require('Blockly.Dart'); + +Blockly.Dart.variables_get = function() { + // Variable getter. + var code = Blockly.Dart.variableDB_.getName(this.getTitleValue('VAR'), + Blockly.Variables.NAME_TYPE); + return [code, Blockly.Dart.ORDER_ATOMIC]; +}; + +Blockly.Dart.variables_set = function() { + // Variable setter. + var argument0 = Blockly.Dart.valueToCode(this, 'VALUE', + Blockly.Dart.ORDER_ASSIGNMENT) || '0'; + var varName = Blockly.Dart.variableDB_.getName(this.getTitleValue('VAR'), + Blockly.Variables.NAME_TYPE); + return varName + ' = ' + argument0 + ';\n'; +}; diff --git a/tests/generators/unittest_dart.js b/tests/generators/unittest_dart.js new file mode 100644 index 000000000..7923023aa --- /dev/null +++ b/tests/generators/unittest_dart.js @@ -0,0 +1,163 @@ +/** + * Visual Blocks Language + * + * Copyright 2012 Google Inc. + * http://blockly.googlecode.com/ + * + * 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 Generating Dart for unit test blocks. + * @author fraser@google.com (Neil Fraser) + */ +'use strict'; + +Blockly.Dart = Blockly.Generator.get('Dart'); + +Blockly.Dart.unittest_main = function() { + // Container for unit tests. + var resultsVar = Blockly.Dart.variableDB_.getName('unittestResults', + Blockly.Variables.NAME_TYPE); + if (!Blockly.Dart.definitions_['unittest_report']) { + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'testReport', Blockly.Generator.NAME_TYPE); + Blockly.Dart.unittest_main.report = functionName; + var func = []; + func.push('String ' + functionName + '() {'); + func.push(' // Create test report.'); + func.push(' List report = [];'); + func.push(' StringBuffer summary = new StringBuffer();'); + func.push(' int fails = 0;'); + func.push(' for (int x = 0; x < ' + resultsVar + '.length; x++) {'); + func.push(' if (' + resultsVar + '[x][0]) {'); + func.push(' summary.write(".");'); + func.push(' } else {'); + func.push(' summary.write("F");'); + func.push(' fails++;'); + func.push(' report.add("");'); + func.push(' report.add("FAIL: ${' + resultsVar + '[x][2]}");'); + func.push(' report.add(' + resultsVar + '[x][1]);'); + func.push(' }'); + func.push(' }'); + func.push(' report.insertRange(0, 1, summary.toString());'); + func.push(' report.add("");'); + func.push(' report.add("Ran ${' + resultsVar + '.length} tests.");'); + func.push(' report.add("");'); + func.push(' if (fails != 0) {'); + func.push(' report.add("FAILED (failures=$fails)");'); + func.push(' } else {'); + func.push(' report.add("OK");'); + func.push(' }'); + func.push(' return report.join("\\n");'); + func.push('}'); + func.push(''); + Blockly.Dart.definitions_['unittest_report'] = func.join('\n'); + } + // Setup global to hold test results. + var code = resultsVar + ' = [];\n'; + // Run tests (unindented). + code += Blockly.Dart.statementToCode(this, 'DO') + .replace(/^ /, '').replace(/\n /g, '\n'); + var reportVar = Blockly.Dart.variableDB_.getDistinctName( + 'report', Blockly.Variables.NAME_TYPE); + code += 'String ' + reportVar + ' = ' + + Blockly.Dart.unittest_main.report + '();\n'; + // Destroy results. + code += resultsVar + ' = null;\n'; + // Print the report to the console (that's where errors will go anyway). + code += 'print(' + reportVar + ');\n'; + return code; +}; + +Blockly.Dart.unittest_main.defineAssert_ = function() { + if (!Blockly.Dart.definitions_['unittest_assertequals']) { + var resultsVar = Blockly.Dart.variableDB_.getName('unittestResults', + Blockly.Variables.NAME_TYPE); + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'assertEquals', Blockly.Generator.NAME_TYPE); + Blockly.Dart.unittest_main.assert_ = functionName; + var func = []; + func.push('void ' + functionName + + '(dynamic actual, dynamic expected, String message) {'); + func.push(' // Asserts that a value equals another value.'); + func.push(' if (' + resultsVar + ' == null) {'); + func.push(' throw "Orphaned assert: ${message}";'); + func.push(' }'); + func.push(' if (actual == expected) {'); + func.push(' ' + resultsVar + '.add([true, "OK", message]);'); + func.push(' } else {'); + func.push(' ' + resultsVar + '.add([false, ' + + '"Expected: $expected\\nActual: $actual", message]);'); + func.push(' }'); + func.push('}'); + func.push(''); + Blockly.Dart.definitions_['unittest_assertequals'] = func.join('\n'); + } + return Blockly.Dart.unittest_main.assert_; +}; + +Blockly.Dart.unittest_assertequals = function() { + // Asserts that a value equals another value. + var resultsVar = Blockly.Dart.variableDB_.getName('unittestResults', + Blockly.Variables.NAME_TYPE); + var message = Blockly.Dart.quote_(this.getTitleValue('MESSAGE')); + var actual = Blockly.Dart.valueToCode(this, 'ACTUAL', + Blockly.Dart.ORDER_NONE) || 'null'; + var expected = Blockly.Dart.valueToCode(this, 'EXPECTED', + Blockly.Dart.ORDER_NONE) || 'null'; + return Blockly.Dart.unittest_main.defineAssert_() + + '(' + actual + ', ' + expected + ', ' + message + ');\n'; +}; + +Blockly.Dart.unittest_assertvalue = function() { + // Asserts that a value is true, false, or null. + var resultsVar = Blockly.Dart.variableDB_.getName('unittestResults', + Blockly.Variables.NAME_TYPE); + var message = Blockly.Dart.quote_(this.getTitleValue('MESSAGE')); + var actual = Blockly.Dart.valueToCode(this, 'ACTUAL', + Blockly.Dart.ORDER_NONE) || 'true'; + var expected = this.getTitleValue('EXPECTED'); + if (expected == 'TRUE') { + expected = 'true'; + } else if (expected == 'FALSE') { + expected = 'false'; + } else if (expected == 'NULL') { + expected = 'null'; + } + return Blockly.Dart.unittest_main.defineAssert_() + + '(' + actual + ', ' + expected + ', ' + message + ');\n'; +}; + +Blockly.Dart.unittest_fail = function() { + // Always assert an error. + var resultsVar = Blockly.Dart.variableDB_.getName('unittestResults', + Blockly.Variables.NAME_TYPE); + var message = Blockly.Dart.quote_(this.getTitleValue('MESSAGE')); + if (!Blockly.Dart.definitions_['unittest_fail']) { + var functionName = Blockly.Dart.variableDB_.getDistinctName( + 'fail', Blockly.Generator.NAME_TYPE); + Blockly.Dart.unittest_fail.assert = functionName; + var func = []; + func.push('void ' + functionName + '(String message) {'); + func.push(' // Always assert an error.'); + func.push(' if (' + resultsVar + ' == null) {'); + func.push(' throw "Orphaned assert fail: ' + message + '";'); + func.push(' }'); + func.push(' ' + resultsVar + '.add([false, "Fail.", message]);'); + func.push('}'); + func.push(''); + Blockly.Dart.definitions_['unittest_fail'] = func.join('\n'); + } + return Blockly.Dart.unittest_fail.assert + '(' + message + ');\n'; +};