dart.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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,' +
  43. 'extends,false,final,finally,for,if,in,is,new,null,rethrow,return,super,' +
  44. 'switch,this,throw,true,try,var,void,while,with,' +
  45. // https://api.dartlang.org/dart_core.html
  46. 'print,identityHashCode,identical,BidirectionalIterator,Comparable,' +
  47. 'double,Function,int,Invocation,Iterable,Iterator,List,Map,Match,num,' +
  48. 'Pattern,RegExp,Set,StackTrace,String,StringSink,Type,bool,DateTime,' +
  49. 'Deprecated,Duration,Expando,Null,Object,RuneIterator,Runes,Stopwatch,' +
  50. 'StringBuffer,Symbol,Uri,Comparator,AbstractClassInstantiationError,' +
  51. 'ArgumentError,AssertionError,CastError,ConcurrentModificationError,' +
  52. 'CyclicInitializationError,Error,Exception,FallThroughError,' +
  53. 'FormatException,IntegerDivisionByZeroException,NoSuchMethodError,' +
  54. 'NullThrownError,OutOfMemoryError,RangeError,StackOverflowError,' +
  55. 'StateError,TypeError,UnimplementedError,UnsupportedError'
  56. );
  57. /**
  58. * Order of operation ENUMs.
  59. * https://www.dartlang.org/docs/dart-up-and-running/ch02.html#operator_table
  60. */
  61. Blockly.Dart.ORDER_ATOMIC = 0; // 0 "" ...
  62. Blockly.Dart.ORDER_UNARY_POSTFIX = 1; // expr++ expr-- () [] . ?.
  63. Blockly.Dart.ORDER_UNARY_PREFIX = 2; // -expr !expr ~expr ++expr --expr
  64. Blockly.Dart.ORDER_MULTIPLICATIVE = 3; // * / % ~/
  65. Blockly.Dart.ORDER_ADDITIVE = 4; // + -
  66. Blockly.Dart.ORDER_SHIFT = 5; // << >>
  67. Blockly.Dart.ORDER_BITWISE_AND = 6; // &
  68. Blockly.Dart.ORDER_BITWISE_XOR = 7; // ^
  69. Blockly.Dart.ORDER_BITWISE_OR = 8; // |
  70. Blockly.Dart.ORDER_RELATIONAL = 9; // >= > <= < as is is!
  71. Blockly.Dart.ORDER_EQUALITY = 10; // == !=
  72. Blockly.Dart.ORDER_LOGICAL_AND = 11; // &&
  73. Blockly.Dart.ORDER_LOGICAL_OR = 12; // ||
  74. Blockly.Dart.ORDER_IF_NULL = 13; // ??
  75. Blockly.Dart.ORDER_CONDITIONAL = 14; // expr ? expr : expr
  76. Blockly.Dart.ORDER_CASCADE = 15; // ..
  77. Blockly.Dart.ORDER_ASSIGNMENT = 16; // = *= /= ~/= %= += -= <<= >>= &= ^= |=
  78. Blockly.Dart.ORDER_NONE = 99; // (...)
  79. /**
  80. * Allow for switching between one and zero based indexing for lists and text,
  81. * one based by default.
  82. */
  83. Blockly.Dart.ONE_BASED_INDEXING = true;
  84. /**
  85. * Initialise the database of variable names.
  86. * @param {!Blockly.Workspace} workspace Workspace to generate code from.
  87. */
  88. Blockly.Dart.init = function(workspace) {
  89. // Create a dictionary of definitions to be printed before the code.
  90. Blockly.Dart.definitions_ = Object.create(null);
  91. // Create a dictionary mapping desired function names in definitions_
  92. // to actual function names (to avoid collisions with user functions).
  93. Blockly.Dart.functionNames_ = Object.create(null);
  94. if (!Blockly.Dart.variableDB_) {
  95. Blockly.Dart.variableDB_ =
  96. new Blockly.Names(Blockly.Dart.RESERVED_WORDS_);
  97. } else {
  98. Blockly.Dart.variableDB_.reset();
  99. }
  100. var defvars = [];
  101. var variables = Blockly.Variables.allVariables(workspace);
  102. if (variables.length) {
  103. for (var i = 0; i < variables.length; i++) {
  104. defvars[i] = Blockly.Dart.variableDB_.getName(variables[i],
  105. Blockly.Variables.NAME_TYPE);
  106. }
  107. Blockly.Dart.definitions_['variables'] =
  108. 'var ' + defvars.join(', ') + ';';
  109. }
  110. };
  111. /**
  112. * Prepend the generated code with the variable definitions.
  113. * @param {string} code Generated code.
  114. * @return {string} Completed code.
  115. */
  116. Blockly.Dart.finish = function(code) {
  117. // Indent every line.
  118. if (code) {
  119. code = Blockly.Dart.prefixLines(code, Blockly.Dart.INDENT);
  120. }
  121. code = 'main() {\n' + code + '}';
  122. // Convert the definitions dictionary into a list.
  123. var imports = [];
  124. var definitions = [];
  125. for (var name in Blockly.Dart.definitions_) {
  126. var def = Blockly.Dart.definitions_[name];
  127. if (def.match(/^import\s/)) {
  128. imports.push(def);
  129. } else {
  130. definitions.push(def);
  131. }
  132. }
  133. // Clean up temporary data.
  134. delete Blockly.Dart.definitions_;
  135. delete Blockly.Dart.functionNames_;
  136. Blockly.Dart.variableDB_.reset();
  137. var allDefs = imports.join('\n') + '\n\n' + definitions.join('\n\n');
  138. return allDefs.replace(/\n\n+/g, '\n\n').replace(/\n*$/, '\n\n\n') + code;
  139. };
  140. /**
  141. * Naked values are top-level blocks with outputs that aren't plugged into
  142. * anything. A trailing semicolon is needed to make this legal.
  143. * @param {string} line Line of generated code.
  144. * @return {string} Legal line of code.
  145. */
  146. Blockly.Dart.scrubNakedValue = function(line) {
  147. return line + ';\n';
  148. };
  149. /**
  150. * Encode a string as a properly escaped Dart string, complete with quotes.
  151. * @param {string} string Text to encode.
  152. * @return {string} Dart string.
  153. * @private
  154. */
  155. Blockly.Dart.quote_ = function(string) {
  156. // Can't use goog.string.quote since $ must also be escaped.
  157. string = string.replace(/\\/g, '\\\\')
  158. .replace(/\n/g, '\\\n')
  159. .replace(/\$/g, '\\$')
  160. .replace(/'/g, '\\\'');
  161. return '\'' + string + '\'';
  162. };
  163. /**
  164. * Common tasks for generating Dart from blocks.
  165. * Handles comments for the specified block and any connected value blocks.
  166. * Calls any statements following this block.
  167. * @param {!Blockly.Block} block The current block.
  168. * @param {string} code The Dart code created for this block.
  169. * @return {string} Dart code with comments and subsequent blocks added.
  170. * @private
  171. */
  172. Blockly.Dart.scrub_ = function(block, code) {
  173. var commentCode = '';
  174. // Only collect comments for blocks that aren't inline.
  175. if (!block.outputConnection || !block.outputConnection.targetConnection) {
  176. // Collect comment for this block.
  177. var comment = block.getCommentText();
  178. if (comment) {
  179. if (block.getProcedureDef) {
  180. // Use documentation comment for function comments.
  181. commentCode += Blockly.Dart.prefixLines(comment + '\n', '/// ');
  182. } else {
  183. commentCode += Blockly.Dart.prefixLines(comment + '\n', '// ');
  184. }
  185. }
  186. // Collect comments for all value arguments.
  187. // Don't collect comments for nested statements.
  188. for (var i = 0; i < block.inputList.length; i++) {
  189. if (block.inputList[i].type == Blockly.INPUT_VALUE) {
  190. var childBlock = block.inputList[i].connection.targetBlock();
  191. if (childBlock) {
  192. var comment = Blockly.Dart.allNestedComments(childBlock);
  193. if (comment) {
  194. commentCode += Blockly.Dart.prefixLines(comment, '// ');
  195. }
  196. }
  197. }
  198. }
  199. }
  200. var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
  201. var nextCode = Blockly.Dart.blockToCode(nextBlock);
  202. return commentCode + code + nextCode;
  203. };
  204. /**
  205. * Gets a property and adjusts the value while taking into account indexing.
  206. * @param {!Blockly.Block} block The block.
  207. * @param {string} atId The property ID of the element to get.
  208. * @param {number=} opt_delta Value to add.
  209. * @param {boolean=} opt_negate Whether to negate the value.
  210. * @param {number=} opt_order The highest order acting on this value.
  211. * @return {string|number}
  212. */
  213. Blockly.Dart.getAdjusted = function(block, atId, opt_delta, opt_negate,
  214. opt_order) {
  215. var delta = opt_delta || 0;
  216. var order = opt_order || Blockly.Dart.ORDER_NONE;
  217. if (Blockly.Dart.ONE_BASED_INDEXING) {
  218. delta--;
  219. }
  220. var defaultAtIndex = Blockly.Dart.ONE_BASED_INDEXING ? '1' : '0';
  221. if (delta) {
  222. var at = Blockly.Dart.valueToCode(block, atId,
  223. Blockly.Dart.ORDER_ADDITIVE) || defaultAtIndex;
  224. } else if (opt_negate) {
  225. var at = Blockly.Dart.valueToCode(block, atId,
  226. Blockly.Dart.ORDER_UNARY_PREFIX) || defaultAtIndex;
  227. } else {
  228. var at = Blockly.Dart.valueToCode(block, atId, order) ||
  229. defaultAtIndex;
  230. }
  231. if (Blockly.isNumber(at)) {
  232. // If the index is a naked number, adjust it right now.
  233. at = parseInt(at, 10) + delta;
  234. if (opt_negate) {
  235. at = -at;
  236. }
  237. } else {
  238. // If the index is dynamic, adjust it in code.
  239. if (delta > 0) {
  240. at = at + ' + ' + delta;
  241. var innerOrder = Blockly.Dart.ORDER_ADDITIVE;
  242. } else if (delta < 0) {
  243. at = at + ' - ' + -delta;
  244. var innerOrder = Blockly.Dart.ORDER_ADDITIVE;
  245. }
  246. if (opt_negate) {
  247. if (delta) {
  248. at = '-(' + at + ')';
  249. } else {
  250. at = '-' + at;
  251. }
  252. var innerOrder = Blockly.Dart.ORDER_UNARY_PREFIX;
  253. }
  254. innerOrder = Math.floor(innerOrder);
  255. order = Math.floor(order);
  256. if (innerOrder && order >= innerOrder) {
  257. at = '(' + at + ')';
  258. }
  259. }
  260. return at;
  261. };