python.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. /**
  2. * @license
  3. * Visual Blocks Language
  4. *
  5. * Copyright 2012 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 Python for blocks.
  22. * @author fraser@google.com (Neil Fraser)
  23. */
  24. 'use strict';
  25. goog.provide('Blockly.Python');
  26. goog.require('Blockly.Generator');
  27. //Blockly.Python.StaticTyping = new Blockly.StaticTyping();
  28. /**
  29. * Python code generator.
  30. * @type {!Blockly.Generator}
  31. */
  32. //Blockly.Python = new Blockly.Generator('Python');
  33. /**
  34. * List of illegal variable names.
  35. * This is not intended to be a security feature. Blockly is 100% client-side,
  36. * so bypassing this list is trivial. This is intended to prevent users from
  37. * accidentally clobbering a built-in object or function.
  38. * @private
  39. */
  40. Blockly.Python.addReservedWords(
  41. // import keyword
  42. // print ','.join(keyword.kwlist)
  43. // http://docs.python.org/reference/lexical_analysis.html#keywords
  44. 'and,as,assert,break,class,continue,def,del,elif,else,except,exec,' +
  45. 'finally,for,from,global,if,import,in,is,lambda,not,or,pass,print,raise,' +
  46. 'return,try,while,with,yield,' +
  47. //http://docs.python.org/library/constants.html
  48. 'True,False,None,NotImplemented,Ellipsis,__debug__,quit,exit,copyright,license,credits,' +
  49. // Reserved libraries
  50. //'crime,stocks,earthquakes,books,weather,plt,math,'+
  51. // http://docs.python.org/library/functions.html
  52. ''
  53. //'abs,divmod,input,open,staticmethod,all,enumerate,int,ord,str,any,eval,isinstance,pow,sum,basestring,execfile,issubclass,print,super,bin,file,iter,property,tuple,bool,filter,len,range,type,bytearray,float,list,raw_input,unichr,callable,format,locals,reduce,unicode,chr,frozenset,long,reload,vars,classmethod,getattr,map,repr,xrange,cmp,globals,max,reversed,zip,compile,hasattr,memoryview,round,__import__,complex,hash,min,set,apply,delattr,help,next,setattr,buffer,dict,hex,object,slice,coerce,dir,id,oct,sorted,intern'
  54. );
  55. /**
  56. * Order of operation ENUMs.
  57. * http://docs.python.org/reference/expressions.html#summary
  58. */
  59. Blockly.Python.ORDER_ATOMIC = 0; // 0 "" ...
  60. Blockly.Python.ORDER_COLLECTION = 1; // tuples, lists, dictionaries
  61. Blockly.Python.ORDER_STRING_CONVERSION = 1; // `expression...`
  62. Blockly.Python.ORDER_MEMBER = 2.1; // . []
  63. Blockly.Python.ORDER_FUNCTION_CALL = 2.2; // ()
  64. Blockly.Python.ORDER_EXPONENTIATION = 3; // **
  65. Blockly.Python.ORDER_UNARY_SIGN = 4; // + -
  66. Blockly.Python.ORDER_BITWISE_NOT = 4; // ~
  67. Blockly.Python.ORDER_MULTIPLICATIVE = 5; // * / // %
  68. Blockly.Python.ORDER_ADDITIVE = 6; // + -
  69. Blockly.Python.ORDER_BITWISE_SHIFT = 7; // << >>
  70. Blockly.Python.ORDER_BITWISE_AND = 8; // &
  71. Blockly.Python.ORDER_BITWISE_XOR = 9; // ^
  72. Blockly.Python.ORDER_BITWISE_OR = 10; // |
  73. Blockly.Python.ORDER_RELATIONAL = 11; // in, not in, is, is not,
  74. // <, <=, >, >=, <>, !=, ==
  75. Blockly.Python.ORDER_LOGICAL_NOT = 12; // not
  76. Blockly.Python.ORDER_LOGICAL_AND = 13; // and
  77. Blockly.Python.ORDER_LOGICAL_OR = 14; // or
  78. Blockly.Python.ORDER_CONDITIONAL = 15; // if else
  79. Blockly.Python.ORDER_LAMBDA = 16; // lambda
  80. Blockly.Python.ORDER_NONE = 99; // (...)
  81. /**
  82. * Empty loops or conditionals are not allowed in Python.
  83. */
  84. Blockly.Python.PASS = ' pass\n';
  85. /*
  86. * Allow for switching between one and zero based indexing for lists and text,
  87. * one based by default.
  88. */
  89. Blockly.Python.ONE_BASED_INDEXING = false;
  90. /**
  91. * List of outer-inner pairings that do NOT require parentheses.
  92. * @type {!Array.<!Array.<number>>}
  93. */
  94. Blockly.Python.ORDER_OVERRIDES = [
  95. // (foo()).bar -> foo().bar
  96. // (foo())[0] -> foo()[0]
  97. [Blockly.Python.ORDER_FUNCTION_CALL, Blockly.Python.ORDER_MEMBER],
  98. // (foo())() -> foo()()
  99. [Blockly.Python.ORDER_FUNCTION_CALL, Blockly.Python.ORDER_FUNCTION_CALL],
  100. // (foo.bar).baz -> foo.bar.baz
  101. // (foo.bar)[0] -> foo.bar[0]
  102. // (foo[0]).bar -> foo[0].bar
  103. // (foo[0])[1] -> foo[0][1]
  104. [Blockly.Python.ORDER_MEMBER, Blockly.Python.ORDER_MEMBER],
  105. // (foo.bar)() -> foo.bar()
  106. // (foo[0])() -> foo[0]()
  107. [Blockly.Python.ORDER_MEMBER, Blockly.Python.ORDER_FUNCTION_CALL],
  108. // not (not foo) -> not not foo
  109. [Blockly.Python.ORDER_LOGICAL_NOT, Blockly.Python.ORDER_LOGICAL_NOT],
  110. // a and (b and c) -> a and b and c
  111. [Blockly.Python.ORDER_LOGICAL_AND, Blockly.Python.ORDER_LOGICAL_AND],
  112. // a or (b or c) -> a or b or c
  113. [Blockly.Python.ORDER_LOGICAL_OR, Blockly.Python.ORDER_LOGICAL_OR]
  114. ];
  115. /**
  116. * Initialise the database of variable names.
  117. * @param {!Blockly.Workspace} workspace Workspace to generate code from.
  118. */
  119. Blockly.Python.init = function (workspace) {
  120. /**
  121. * Empty loops or conditionals are not allowed in Python.
  122. */
  123. Blockly.Python.PASS = this.INDENT + 'pass\n';
  124. // Create a dictionary of definitions to be printed before the code.
  125. Blockly.Python.definitions_ = Object.create(null);
  126. // Create a dictionary mapping desired function names in definitions_
  127. // to actual function names (to avoid collisions with user functions).
  128. Blockly.Python.functionNames_ = Object.create(null);
  129. if (!Blockly.Python.variableDB_) {
  130. Blockly.Python.variableDB_ =
  131. new Blockly.Names(Blockly.Python.RESERVED_WORDS_);
  132. } else {
  133. Blockly.Python.variableDB_.reset();
  134. }
  135. // Removed, because we shouldn't teach students to do this.
  136. /*
  137. var defvars = [];
  138. var variables = workspace.variableList;
  139. for (var i = 0; i < variables.length; i++) {
  140. defvars[i] = Blockly.Python.variableDB_.getName(variables[i],
  141. Blockly.Variables.NAME_TYPE) + ' = None';
  142. }
  143. Blockly.Python.definitions_['variables'] = defvars.join('\n');*/
  144. };
  145. /**
  146. * Prepend the generated code with the variable definitions.
  147. * @param {string} code Generated code.
  148. * @return {string} Completed code.
  149. */
  150. Blockly.Python.finish = function (code) {
  151. // Convert the definitions dictionary into a list.
  152. var imports = [];
  153. var definitions = [];
  154. for (var name in Blockly.Python.definitions_) {
  155. var def = Blockly.Python.definitions_[name];
  156. if (def.match(/^(from\s+\S+\s+)?import\s+\S+/)) {
  157. imports.push(def);
  158. } else {
  159. definitions.push(def);
  160. }
  161. }
  162. // Clean up temporary data.
  163. delete Blockly.Python.definitions_;
  164. delete Blockly.Python.functionNames_;
  165. Blockly.Python.variableDB_.reset();
  166. var allDefs = imports.join('\n') + '\n\n' + definitions.join('\n\n');
  167. return allDefs.replace(/\n\n+/g, '\n\n').replace(/\n*$/, '\n\n\n') + code;
  168. };
  169. /**
  170. * Naked values are top-level blocks with outputs that aren't plugged into
  171. * anything.
  172. * @param {string} line Line of generated code.
  173. * @return {string} Legal line of code.
  174. */
  175. Blockly.Python.scrubNakedValue = function (line) {
  176. return line + '\n';
  177. };
  178. /**
  179. * Encode a string as a properly escaped Python string, complete with quotes.
  180. * @param {string} string Text to encode.
  181. * @return {string} Python string.
  182. * @private
  183. */
  184. Blockly.Python.quote_ = function (string) {
  185. // Can't use goog.string.quote since % must also be escaped.
  186. string = string.replace(/\\/g, '\\\\')
  187. .replace(/\n/g, '\\\n');
  188. if (string.indexOf('"') > -1 && string.indexOf('"') == -1) {
  189. return '\'' + string + '\'';
  190. } else if (string.indexOf('"') == -1 && string.indexOf('"') > -1) {
  191. return '"' + string + '"';
  192. } else {
  193. string = string.replace(/"/g, '\\\"');
  194. return '"' + string + '"';
  195. }
  196. };
  197. /**
  198. * Common tasks for generating Python from blocks.
  199. * Handles comments for the specified block and any connected value blocks.
  200. * Calls any statements following this block.
  201. * @param {!Blockly.Block} block The current block.
  202. * @param {string} code The Python code created for this block.
  203. * @return {string} Python code with comments and subsequent blocks added.
  204. * @private
  205. */
  206. Blockly.Python.scrub_ = function (block, code) {
  207. var commentCode = '';
  208. // Only collect comments for blocks that aren't inline.
  209. if (!block.outputConnection || !block.outputConnection.targetConnection) {
  210. // Collect comment for this block.
  211. var comment = block.getCommentText();
  212. comment = Blockly.utils.wrap(comment, Blockly.Python.COMMENT_WRAP - 3);
  213. if (comment) {
  214. if (block.getProcedureDef) {
  215. // Use a comment block for function comments.
  216. //TODO: fixme
  217. //commentCode += '"""' + comment + '\n"""\n';
  218. } else {
  219. commentCode += Blockly.Python.prefixLines(comment + '\n', '# ');
  220. }
  221. }
  222. // Collect comments for all value arguments.
  223. // Don't collect comments for nested statements.
  224. for (var i = 0; i < block.inputList.length; i++) {
  225. if (block.inputList[i].type == Blockly.INPUT_VALUE) {
  226. var childBlock = block.inputList[i].connection.targetBlock();
  227. if (childBlock) {
  228. var comment = Blockly.Python.allNestedComments(childBlock);
  229. if (comment) {
  230. commentCode += Blockly.Python.prefixLines(comment, '# ');
  231. }
  232. }
  233. }
  234. }
  235. }
  236. var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
  237. var nextCode = Blockly.Python.blockToCode(nextBlock);
  238. return commentCode + code + nextCode;
  239. };
  240. /**
  241. * Gets a property and adjusts the value, taking into account indexing, and
  242. * casts to an integer.
  243. * @param {!Blockly.Block} block The block.
  244. * @param {string} atId The property ID of the element to get.
  245. * @param {number=} opt_delta Value to add.
  246. * @param {boolean=} opt_negate Whether to negate the value.
  247. * @return {string|number}
  248. */
  249. Blockly.Python.getAdjustedInt = function (block, atId, opt_delta, opt_negate) {
  250. var delta = opt_delta || 0;
  251. if (block.workspace.options.oneBasedIndex) {
  252. delta--;
  253. }
  254. var defaultAtIndex = block.workspace.options.oneBasedIndex ? '1' : '0';
  255. var atOrder = delta ? Blockly.Python.ORDER_ADDITIVE :
  256. Blockly.Python.ORDER_NONE;
  257. var at = Blockly.Python.valueToCode(block, atId, atOrder) || defaultAtIndex;
  258. if (Blockly.isNumber(at)) {
  259. // If the index is a naked number, adjust it right now.
  260. at = parseInt(at, 10) + delta;
  261. if (opt_negate) {
  262. at = -at;
  263. }
  264. } else {
  265. // If the index is dynamic, adjust it in code.
  266. if (delta > 0) {
  267. at = 'int(' + at + ' + ' + delta + ')';
  268. } else if (delta < 0) {
  269. at = 'int(' + at + ' - ' + -delta + ')';
  270. } else {
  271. at = 'int(' + at + ')';
  272. }
  273. if (opt_negate) {
  274. at = '-' + at;
  275. }
  276. }
  277. return at;
  278. };
  279. /**
  280. * A list of types tasks that the pins can be assigned. Used to track usage and
  281. * warn if the same pin has been assigned to more than one task.
  282. */
  283. Blockly.Python.PinTypes = {
  284. INPUT: 'INPUT',
  285. OUTPUT: 'OUTPUT',
  286. PWM: 'PWM',
  287. SERVO: 'SERVO',
  288. STEPPER: 'STEPPER',
  289. SERIAL: 'SERIAL',
  290. I2C: 'I2C/TWI',
  291. SPI: 'SPI',
  292. // extra setup
  293. FASTLED: 'FASTLED',
  294. DHT: 'DHT'
  295. };
  296. /**
  297. * Arduino generator short name for
  298. * Blockly.Generator.prototype.FUNCTION_NAME_PLACEHOLDER_
  299. * @type {!string}
  300. */
  301. Blockly.Python.DEF_FUNC_NAME = Blockly.Python.FUNCTION_NAME_PLACEHOLDER_;
  302. /**
  303. * Initialises the database of global definitions, the setup function, function
  304. * names, and variable names.
  305. * @param {Blockly.Workspace} workspace Workspace to generate code from.
  306. */
  307. Blockly.Python.init = function (workspace) {
  308. // Create a dictionary of definitions to be printed at the top of the sketch
  309. Blockly.Python.includes_ = Object.create(null);
  310. // Create a dictionary of global definitions to be printed after variables
  311. Blockly.Python.definitions_ = Object.create(null);
  312. // Create a dictionary of variables
  313. Blockly.Python.variables_ = Object.create(null);
  314. // Create a dictionary of functions from the code generator
  315. Blockly.Python.codeFunctions_ = Object.create(null);
  316. // Create a dictionary of functions created by the user
  317. Blockly.Python.userFunctions_ = Object.create(null);
  318. // Create a dictionary mapping desired function names in definitions_
  319. // to actual function names (to avoid collisions with user functions)
  320. Blockly.Python.functionNames_ = Object.create(null);
  321. // Create a dictionary of setups to be printed in the setup() function
  322. Blockly.Python.setups_ = Object.create(null);
  323. // Create a dictionary of pins to check if their use conflicts
  324. Blockly.Python.pins_ = Object.create(null);
  325. if (!Blockly.Python.variableDB_) {
  326. Blockly.Python.variableDB_ =
  327. new Blockly.Names(Blockly.Python.RESERVED_WORDS_);
  328. } else {
  329. Blockly.Python.variableDB_.reset();
  330. }
  331. // var defvars = [];
  332. // var variables = workspace.variableList;
  333. // for (var i = 0; i < variables.length; i++) {
  334. // defvars[i] = Blockly.Python.variableDB_.getName(variables[i],
  335. // Blockly.Variables.NAME_TYPE) + ' = None';
  336. // }
  337. //Blockly.Python.definitions_['variables'] = defvars.join('\n');
  338. // Iterate through to capture all blocks types and set the function arguments
  339. // var varsWithTypes = Blockly.Python.StaticTyping.collectVarsWithTypes(workspace);
  340. // Blockly.Python.StaticTyping.setProcedureArgs(workspace, varsWithTypes);
  341. // // Set variable declarations with their Arduino type in the defines dictionary
  342. // for (var varName in varsWithTypes) {
  343. // if (Blockly.Python.getArduinoType_(varsWithTypes[varName]) != "array") {
  344. // // console.log(Blockly.Python.getArduinoType_(varsWithTypes[varName]));
  345. // Blockly.Python.addVariable(varName,
  346. // Blockly.Python.getArduinoType_(varsWithTypes[varName]) + ' ' +
  347. // Blockly.Python.variableDB_.getName(varName, Blockly.Variables.NAME_TYPE) + ';');
  348. // }
  349. // }
  350. };
  351. // /**
  352. // * Prepare all generated code to be placed in the sketch specific locations.
  353. // * @param {string} code Generated main program (loop function) code.
  354. // * @return {string} Completed sketch code.
  355. // */
  356. Blockly.Python.finish = function (code) {
  357. // Convert the includes, definitions, and functions dictionaries into lists
  358. var includes = [], definitions = [], variables = [], functions = [];
  359. for (var name in Blockly.Python.includes_) {
  360. includes.push(Blockly.Python.includes_[name]);
  361. }
  362. if (includes.length) {
  363. includes.push('\n');
  364. }
  365. for (var name in Blockly.Python.variables_) {
  366. variables.push(Blockly.Python.variables_[name]);
  367. }
  368. if (variables.length) {
  369. variables.push('\n');
  370. }
  371. for (var name in Blockly.Python.definitions_) {
  372. var def = Blockly.Python.definitions_[name];
  373. if (def.match(/^(from\s+\S+\s+)?import\s+\S+/)) {
  374. includes.push(def);
  375. } else {
  376. definitions.push(def);
  377. }
  378. }
  379. if (definitions.length) {
  380. definitions.push('\n');
  381. }
  382. for (var name in Blockly.Python.codeFunctions_) {
  383. functions.push(Blockly.Python.codeFunctions_[name]);
  384. }
  385. for (var name in Blockly.Python.userFunctions_) {
  386. functions.push(Blockly.Python.userFunctions_[name]);
  387. }
  388. if (functions.length) {
  389. functions.push('\n');
  390. }
  391. // userSetupCode added at the end of the setup function without leading spaces
  392. var setups = [''], userSetupCode = '';
  393. if (Blockly.Python.setups_['userSetupCode'] !== undefined) {
  394. userSetupCode = '\n' + Blockly.Python.setups_['userSetupCode'];
  395. delete Blockly.Python.setups_['userSetupCode'];
  396. }
  397. for (var name in Blockly.Python.setups_) {
  398. setups.push(Blockly.Python.setups_[name]);
  399. }
  400. if (userSetupCode) {
  401. setups.push(userSetupCode);
  402. }
  403. // Clean up temporary data
  404. delete Blockly.Python.includes_;
  405. delete Blockly.Python.definitions_;
  406. delete Blockly.Python.variables_;
  407. delete Blockly.Python.codeFunctions_;
  408. delete Blockly.Python.userFunctions_;
  409. delete Blockly.Python.functionNames_;
  410. delete Blockly.Python.setups_;
  411. delete Blockly.Python.pins_;
  412. Blockly.Python.variableDB_.reset();
  413. var allDefs = includes.join('\n') + '\n\n' +
  414. definitions.join('\n') + '\n\n' + functions.join('\n') + '\n\n' + variables.join('\n') + '\n\n';
  415. var setup = setups.join('\n') + '\n\n';
  416. var loop = code + '\n\n';
  417. // functions.join('\n').replace(/\n\n+/g, '\n\n') +
  418. return allDefs.replace(/\n\n+/g, '\n\n') + setup.replace(/\n\n+/g, '\n\n') + loop.replace(/\n\n+/g, '\n\n');
  419. };
  420. /**
  421. * Adds a string of "include" code to be added to the sketch.
  422. * Once a include is added it will not get overwritten with new code.
  423. * @param {!string} includeTag Identifier for this include code.
  424. * @param {!string} code Code to be included at the very top of the sketch.
  425. */
  426. Blockly.Python.addInclude = function (includeTag, code) {
  427. if (Blockly.Python.includes_[includeTag] === undefined) {
  428. Blockly.Python.includes_[includeTag] = code;
  429. }
  430. };
  431. /**
  432. * Adds a string of code to be declared globally to the sketch.
  433. * Once it is added it will not get overwritten with new code.
  434. * @param {!string} declarationTag Identifier for this declaration code.
  435. * @param {!string} code Code to be added below the includes.
  436. */
  437. Blockly.Python.addDeclaration = function (declarationTag, code) {
  438. if (Blockly.Python.definitions_[declarationTag] === undefined) {
  439. Blockly.Python.definitions_[declarationTag] = code;
  440. }
  441. };
  442. /**
  443. * Adds a string of code to declare a variable globally to the sketch.
  444. * Only if overwrite option is set to true it will overwrite whatever
  445. * value the identifier held before.
  446. * @param {!string} varName The name of the variable to declare.
  447. * @param {!string} code Code to be added for the declaration.
  448. * @param {boolean=} overwrite Flag to ignore previously set value.
  449. * @return {!boolean} Indicates if the declaration overwrote a previous one.
  450. */
  451. Blockly.Python.addVariable = function (varName, code, overwrite) {
  452. var overwritten = false;
  453. if (overwrite || (Blockly.Python.variableDB_.dbReverse_[varName] === undefined)) {
  454. Blockly.Python.variables_[varName] = code;
  455. Blockly.mainWorkspace.createVariable(varName)
  456. // Blockly.Python.variableDB_.dbReverse_[varName] = true;
  457. // Blockly.Python.variableDB_.db_[varName + "_VARIABLE"] = varName;
  458. overwritten = true;
  459. }
  460. return overwritten;
  461. };
  462. /**
  463. * Adds a string of code into the Arduino setup() function. It takes an
  464. * identifier to not repeat the same kind of initialisation code from several
  465. * blocks. If overwrite option is set to true it will overwrite whatever
  466. * value the identifier held before.
  467. * @param {!string} setupTag Identifier for the type of set up code.
  468. * @param {!string} code Code to be included in the setup() function.
  469. * @param {boolean=} overwrite Flag to ignore previously set value.
  470. * @return {!boolean} Indicates if the new setup code overwrote a previous one.
  471. */
  472. Blockly.Python.addSetup = function (setupTag, code, overwrite) {
  473. var overwritten = false;
  474. if (overwrite || (Blockly.Python.setups_[setupTag] === undefined)) {
  475. Blockly.Python.setups_[setupTag] = code;
  476. overwritten = true;
  477. }
  478. return overwritten;
  479. };
  480. /**
  481. * Adds a string of code as a function. It takes an identifier (meant to be the
  482. * function name) to only keep a single copy even if multiple blocks might
  483. * request this function to be created.
  484. * A function (and its code) will only be added on first request.
  485. * @param {!string} preferedName Identifier for the function.
  486. * @param {!string} code Code to be included in the setup() function.
  487. * @return {!string} A unique function name based on input name.
  488. */
  489. Blockly.Python.addFunction = function (preferedName, code) {
  490. if (Blockly.Python.codeFunctions_[preferedName] === undefined) {
  491. var uniqueName = Blockly.Python.variableDB_.getDistinctName(
  492. preferedName, Blockly.Generator.NAME_TYPE);
  493. Blockly.Python.codeFunctions_[preferedName] =
  494. code.replace(Blockly.Python.DEF_FUNC_NAME, uniqueName);
  495. Blockly.Python.functionNames_[preferedName] = uniqueName;
  496. }
  497. return Blockly.Python.functionNames_[preferedName];
  498. };
  499. /**
  500. * Description.
  501. * @param {!Blockly.Block} block Description.
  502. * @param {!string} pin Description.
  503. * @param {!string} pinType Description.
  504. * @param {!string} warningTag Description.
  505. */
  506. Blockly.Python.reservePin = function (block, pin, pinType, warningTag) {
  507. if (Blockly.Python.pins_[pin] !== undefined) {
  508. if (Blockly.Python.pins_[pin] != pinType) {
  509. block.setWarningText(Blockly.Msg.ARD_PIN_WARN1.replace('%1', pin)
  510. .replace('%2', warningTag).replace('%3', pinType)
  511. .replace('%4', Blockly.Python.pins_[pin]), warningTag);
  512. } else {
  513. block.setWarningText(null, warningTag);
  514. }
  515. } else {
  516. Blockly.Python.pins_[pin] = pinType;
  517. block.setWarningText(null, warningTag);
  518. }
  519. };
  520. /**
  521. * Naked values are top-level blocks with outputs that aren't plugged into
  522. * anything. A trailing semicolon is needed to make this legal.
  523. * @param {string} line Line of generated code.
  524. * @return {string} Legal line of code.
  525. */
  526. // Blockly.Python.scrubNakedValue = function(line) {
  527. // return line + ';\n';
  528. // };
  529. /**
  530. * Encode a string as a properly escaped Arduino string, complete with quotes.
  531. * @param {string} string Text to encode.
  532. * @return {string} Arduino string.
  533. * @private
  534. */
  535. // Blockly.Python.quote_ = function(string) {
  536. // // TODO: This is a quick hack. Replace with goog.string.quote
  537. // string = string.replace(/\\/g, '\\\\')
  538. // .replace(/\n/g, '\\\n')
  539. // .replace(/\$/g, '\\$')
  540. // .replace(/'/g, '\\\'');
  541. // return '\"' + string + '\"';
  542. // };
  543. /**
  544. * Common tasks for generating Arduino from blocks.
  545. * Handles comments for the specified block and any connected value blocks.
  546. * Calls any statements following this block.
  547. * @param {!Blockly.Block} block The current block.
  548. * @param {string} code The Arduino code created for this block.
  549. * @return {string} Arduino code with comments and subsequent blocks added.
  550. * @this {Blockly.CodeGenerator}
  551. * @private
  552. */
  553. // Blockly.Python.scrub_ = function(block, code) {
  554. // if (code === null) { return ''; } // Block has handled code generation itself
  555. // var commentCode = '';
  556. // // Only collect comments for blocks that aren't inline
  557. // if (!block.outputConnection || !block.outputConnection.targetConnection) {
  558. // // Collect comment for this block.
  559. // var comment = block.getCommentText();
  560. // if (comment) {
  561. // commentCode += this.prefixLines(comment, '// ') + '\n';
  562. // }
  563. // // Collect comments for all value arguments
  564. // // Don't collect comments for nested statements
  565. // for (var x = 0; x < block.inputList.length; x++) {
  566. // if (block.inputList[x].type == Blockly.INPUT_VALUE) {
  567. // var childBlock = block.inputList[x].connection.targetBlock();
  568. // if (childBlock) {
  569. // var comment = this.allNestedComments(childBlock);
  570. // if (comment) {
  571. // commentCode += this.prefixLines(comment, '// ');
  572. // }
  573. // }
  574. // }
  575. // }
  576. // }
  577. // var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
  578. // var nextCode = this.blockToCode(nextBlock);
  579. // return commentCode + code + nextCode;
  580. // };
  581. /**
  582. * Generates Arduino Types from a Blockly Type.
  583. * @param {!Blockly.Type} typeBlockly The Blockly type to be converted.
  584. * @return {string} Arduino type for the respective Blockly input type, in a
  585. * string format.
  586. * @private
  587. */
  588. Blockly.Python.getArduinoType_ = function (typeBlockly) {
  589. switch (typeBlockly.typeId) {
  590. case Blockly.Types.SHORT_NUMBER.typeId:
  591. return 'short';
  592. case Blockly.Types.NUMBER.typeId:
  593. return 'int';
  594. case Blockly.Types.LARGE_NUMBER.typeId:
  595. return 'long';
  596. case Blockly.Types.DECIMAL.typeId:
  597. return 'float';
  598. case Blockly.Types.TEXT.typeId:
  599. return 'String';
  600. case Blockly.Types.CHARACTER.typeId:
  601. return 'char';
  602. case Blockly.Types.BOOLEAN.typeId:
  603. return 'boolean';
  604. case Blockly.Types.NULL.typeId:
  605. return 'void';
  606. case Blockly.Types.UNDEF.typeId:
  607. return 'undefined';
  608. case Blockly.Types.CHILD_BLOCK_MISSING.typeId:
  609. // If no block connected default to int, change for easier debugging
  610. //return 'ChildBlockMissing';
  611. return 'int';
  612. case Blockly.Types.ARRAY.typeId:
  613. return 'array';
  614. default:
  615. return 'Invalid Blockly Type';
  616. }
  617. };
  618. /** Used for not-yet-implemented block code generators */
  619. Blockly.Python.noGeneratorCodeInline = function () {
  620. return ['', Blockly.Python.ORDER_ATOMIC];
  621. };
  622. /** Used for not-yet-implemented block code generators */
  623. Blockly.Python.noGeneratorCodeLine = function () { return ''; };