dart.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. /**
  2. * @license
  3. * Visual Blocks Language
  4. *
  5. * Copyright 2014 Google Inc.
  6. * https://developers.google.com/blockly/
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License");
  9. * you may not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. /**
  21. * @fileoverview Helper functions for generating Dart for blocks.
  22. * @author fraser@google.com (Neil Fraser)
  23. */
  24. 'use strict';
  25. goog.provide('Blockly.Dart');
  26. goog.require('Blockly.Generator');
  27. /**
  28. * Dart code generator.
  29. * @type {!Blockly.Generator}
  30. */
  31. Blockly.Dart = new Blockly.Generator('Dart');
  32. /**
  33. * List of illegal variable names.
  34. * This is not intended to be a security feature. Blockly is 100% client-side,
  35. * so bypassing this list is trivial. This is intended to prevent users from
  36. * accidentally clobbering a built-in object or function.
  37. * @private
  38. */
  39. Blockly.Dart.addReservedWords(
  40. // https://www.dartlang.org/docs/spec/latest/dart-language-specification.pdf
  41. // Section 16.1.1
  42. 'assert,break,case,catch,class,const,continue,default,do,else,enum,extends,false,final,finally,for,if,in,is,new,null,rethrow,return,super,switch,this,throw,true,try,var,void,while,with,' +
  43. // https://api.dartlang.org/dart_core.html
  44. 'print,identityHashCode,identical,BidirectionalIterator,Comparable,double,Function,int,Invocation,Iterable,Iterator,List,Map,Match,num,Pattern,RegExp,Set,StackTrace,String,StringSink,Type,bool,DateTime,Deprecated,Duration,Expando,Null,Object,RuneIterator,Runes,Stopwatch,StringBuffer,Symbol,Uri,Comparator,AbstractClassInstantiationError,ArgumentError,AssertionError,CastError,ConcurrentModificationError,CyclicInitializationError,Error,Exception,FallThroughError,FormatException,IntegerDivisionByZeroException,NoSuchMethodError,NullThrownError,OutOfMemoryError,RangeError,StackOverflowError,StateError,TypeError,UnimplementedError,UnsupportedError');
  45. /**
  46. * Order of operation ENUMs.
  47. * https://www.dartlang.org/docs/dart-up-and-running/ch02.html#operator_table
  48. */
  49. Blockly.Dart.ORDER_ATOMIC = 0; // 0 "" ...
  50. Blockly.Dart.ORDER_UNARY_POSTFIX = 1; // expr++ expr-- () [] .
  51. Blockly.Dart.ORDER_UNARY_PREFIX = 2; // -expr !expr ~expr ++expr --expr
  52. Blockly.Dart.ORDER_MULTIPLICATIVE = 3; // * / % ~/
  53. Blockly.Dart.ORDER_ADDITIVE = 4; // + -
  54. Blockly.Dart.ORDER_SHIFT = 5; // << >>
  55. Blockly.Dart.ORDER_BITWISE_AND = 6; // &
  56. Blockly.Dart.ORDER_BITWISE_XOR = 7; // ^
  57. Blockly.Dart.ORDER_BITWISE_OR = 8; // |
  58. Blockly.Dart.ORDER_RELATIONAL = 9; // >= > <= < as is is!
  59. Blockly.Dart.ORDER_EQUALITY = 10; // == !=
  60. Blockly.Dart.ORDER_LOGICAL_AND = 11; // &&
  61. Blockly.Dart.ORDER_LOGICAL_OR = 12; // ||
  62. Blockly.Dart.ORDER_CONDITIONAL = 13; // expr ? expr : expr
  63. Blockly.Dart.ORDER_CASCADE = 14; // ..
  64. Blockly.Dart.ORDER_ASSIGNMENT = 15; // = *= /= ~/= %= += -= <<= >>= &= ^= |=
  65. Blockly.Dart.ORDER_NONE = 99; // (...)
  66. /**
  67. * Initialise the database of variable names.
  68. * @param {!Blockly.Workspace} workspace Workspace to generate code from.
  69. */
  70. Blockly.Dart.init = function(workspace) {
  71. // Create a dictionary of definitions to be printed before the code.
  72. Blockly.Dart.definitions_ = Object.create(null);
  73. // Create a dictionary mapping desired function names in definitions_
  74. // to actual function names (to avoid collisions with user functions).
  75. Blockly.Dart.functionNames_ = Object.create(null);
  76. if (!Blockly.Dart.variableDB_) {
  77. Blockly.Dart.variableDB_ =
  78. new Blockly.Names(Blockly.Dart.RESERVED_WORDS_);
  79. } else {
  80. Blockly.Dart.variableDB_.reset();
  81. }
  82. var defvars = [];
  83. var variables = Blockly.Variables.allVariables(workspace);
  84. if (variables.length) {
  85. for (var i = 0; i < variables.length; i++) {
  86. defvars[i] = Blockly.Dart.variableDB_.getName(variables[i],
  87. Blockly.Variables.NAME_TYPE);
  88. }
  89. Blockly.Dart.definitions_['variables'] =
  90. 'var ' + defvars.join(', ') + ';';
  91. }
  92. };
  93. /**
  94. * Prepend the generated code with the variable definitions.
  95. * @param {string} code Generated code.
  96. * @return {string} Completed code.
  97. */
  98. Blockly.Dart.finish = function(code) {
  99. // Indent every line.
  100. if (code) {
  101. code = Blockly.Dart.prefixLines(code, Blockly.Dart.INDENT);
  102. }
  103. code = 'main() {\n' + code + '}';
  104. // Convert the definitions dictionary into a list.
  105. var imports = [];
  106. var definitions = [];
  107. for (var name in Blockly.Dart.definitions_) {
  108. var def = Blockly.Dart.definitions_[name];
  109. if (def.match(/^import\s/)) {
  110. imports.push(def);
  111. } else {
  112. definitions.push(def);
  113. }
  114. }
  115. // Clean up temporary data.
  116. delete Blockly.Dart.definitions_;
  117. delete Blockly.Dart.functionNames_;
  118. Blockly.Dart.variableDB_.reset();
  119. var allDefs = imports.join('\n') + '\n\n' + definitions.join('\n\n');
  120. return allDefs.replace(/\n\n+/g, '\n\n').replace(/\n*$/, '\n\n\n') + code;
  121. };
  122. /**
  123. * Naked values are top-level blocks with outputs that aren't plugged into
  124. * anything. A trailing semicolon is needed to make this legal.
  125. * @param {string} line Line of generated code.
  126. * @return {string} Legal line of code.
  127. */
  128. Blockly.Dart.scrubNakedValue = function(line) {
  129. return line + ';\n';
  130. };
  131. /**
  132. * Encode a string as a properly escaped Dart string, complete with quotes.
  133. * @param {string} string Text to encode.
  134. * @return {string} Dart string.
  135. * @private
  136. */
  137. Blockly.Dart.quote_ = function(string) {
  138. // TODO: This is a quick hack. Replace with goog.string.quote
  139. string = string.replace(/\\/g, '\\\\')
  140. .replace(/\n/g, '\\\n')
  141. .replace(/\$/g, '\\$')
  142. .replace(/'/g, '\\\'');
  143. return '\'' + string + '\'';
  144. };
  145. /**
  146. * Common tasks for generating Dart from blocks.
  147. * Handles comments for the specified block and any connected value blocks.
  148. * Calls any statements following this block.
  149. * @param {!Blockly.Block} block The current block.
  150. * @param {string} code The Dart code created for this block.
  151. * @return {string} Dart code with comments and subsequent blocks added.
  152. * @private
  153. */
  154. Blockly.Dart.scrub_ = function(block, code) {
  155. var commentCode = '';
  156. // Only collect comments for blocks that aren't inline.
  157. if (!block.outputConnection || !block.outputConnection.targetConnection) {
  158. // Collect comment for this block.
  159. var comment = block.getCommentText();
  160. if (comment) {
  161. commentCode += Blockly.Dart.prefixLines(comment, '// ') + '\n';
  162. }
  163. // Collect comments for all value arguments.
  164. // Don't collect comments for nested statements.
  165. for (var x = 0; x < block.inputList.length; x++) {
  166. if (block.inputList[x].type == Blockly.INPUT_VALUE) {
  167. var childBlock = block.inputList[x].connection.targetBlock();
  168. if (childBlock) {
  169. var comment = Blockly.Dart.allNestedComments(childBlock);
  170. if (comment) {
  171. commentCode += Blockly.Dart.prefixLines(comment, '// ');
  172. }
  173. }
  174. }
  175. }
  176. }
  177. var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
  178. var nextCode = Blockly.Dart.blockToCode(nextBlock);
  179. return commentCode + code + nextCode;
  180. };