lua.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. /**
  2. * @license
  3. * Visual Blocks Language
  4. *
  5. * Copyright 2016 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 Lua for blocks.
  22. * @author rodrigoq@google.com (Rodrigo Queiro)
  23. * Based on Ellen Spertus's blocky-lua project.
  24. */
  25. 'use strict';
  26. goog.provide('Blockly.Lua');
  27. goog.require('Blockly.Generator');
  28. /**
  29. * Lua code generator.
  30. * @type {!Blockly.Generator}
  31. */
  32. Blockly.Lua = new Blockly.Generator('Lua');
  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.Lua.addReservedWords(
  41. // Special character
  42. '_,' +
  43. // From theoriginalbit's script:
  44. // https://github.com/espertus/blockly-lua/issues/6
  45. '__inext,assert,bit,colors,colours,coroutine,disk,dofile,error,fs,' +
  46. 'fetfenv,getmetatable,gps,help,io,ipairs,keys,loadfile,loadstring,math,' +
  47. 'native,next,os,paintutils,pairs,parallel,pcall,peripheral,print,' +
  48. 'printError,rawequal,rawget,rawset,read,rednet,redstone,rs,select,' +
  49. 'setfenv,setmetatable,sleep,string,table,term,textutils,tonumber,' +
  50. 'tostring,turtle,type,unpack,vector,write,xpcall,_VERSION,__indext,' +
  51. // Not included in the script, probably because it wasn't enabled:
  52. 'HTTP,' +
  53. // Keywords (http://www.lua.org/pil/1.3.html).
  54. 'and,break,do,else,elseif,end,false,for,function,if,in,local,nil,not,or,' +
  55. 'repeat,return,then,true,until,while,' +
  56. // Metamethods (http://www.lua.org/manual/5.2/manual.html).
  57. 'add,sub,mul,div,mod,pow,unm,concat,len,eq,lt,le,index,newindex,call,' +
  58. // Basic functions (http://www.lua.org/manual/5.2/manual.html, section 6.1).
  59. 'assert,collectgarbage,dofile,error,_G,getmetatable,inpairs,load,' +
  60. 'loadfile,next,pairs,pcall,print,rawequal,rawget,rawlen,rawset,select,' +
  61. 'setmetatable,tonumber,tostring,type,_VERSION,xpcall,' +
  62. // Modules (http://www.lua.org/manual/5.2/manual.html, section 6.3).
  63. 'require,package,string,table,math,bit32,io,file,os,debug'
  64. );
  65. /**
  66. * Order of operation ENUMs.
  67. * http://www.lua.org/manual/5.3/manual.html#3.4.8
  68. */
  69. Blockly.Lua.ORDER_ATOMIC = 0; // literals
  70. // The next level was not explicit in documentation and inferred by Ellen.
  71. Blockly.Lua.ORDER_HIGH = 1; // Function calls, tables[]
  72. Blockly.Lua.ORDER_EXPONENTIATION = 2; // ^
  73. Blockly.Lua.ORDER_UNARY = 3; // not # - ~
  74. Blockly.Lua.ORDER_MULTIPLICATIVE = 4; // * / %
  75. Blockly.Lua.ORDER_ADDITIVE = 5; // + -
  76. Blockly.Lua.ORDER_CONCATENATION = 6; // ..
  77. Blockly.Lua.ORDER_RELATIONAL = 7; // < > <= >= ~= ==
  78. Blockly.Lua.ORDER_AND = 8; // and
  79. Blockly.Lua.ORDER_OR = 9; // or
  80. Blockly.Lua.ORDER_NONE = 99;
  81. /**
  82. * Lua is not supporting zero-indexing since the language itself is one-indexed,
  83. * so there is not flag for ONE_BASED_INDEXING to indicate which indexing is
  84. * used for lists and text.
  85. */
  86. /**
  87. * Initialise the database of variable names.
  88. * @param {!Blockly.Workspace} workspace Workspace to generate code from.
  89. */
  90. Blockly.Lua.init = function(workspace) {
  91. // Create a dictionary of definitions to be printed before the code.
  92. Blockly.Lua.definitions_ = Object.create(null);
  93. // Create a dictionary mapping desired function names in definitions_
  94. // to actual function names (to avoid collisions with user functions).
  95. Blockly.Lua.functionNames_ = Object.create(null);
  96. if (!Blockly.Lua.variableDB_) {
  97. Blockly.Lua.variableDB_ =
  98. new Blockly.Names(Blockly.Lua.RESERVED_WORDS_);
  99. } else {
  100. Blockly.Lua.variableDB_.reset();
  101. }
  102. };
  103. /**
  104. * Prepend the generated code with the variable definitions.
  105. * @param {string} code Generated code.
  106. * @return {string} Completed code.
  107. */
  108. Blockly.Lua.finish = function(code) {
  109. // Convert the definitions dictionary into a list.
  110. var definitions = [];
  111. for (var name in Blockly.Lua.definitions_) {
  112. definitions.push(Blockly.Lua.definitions_[name]);
  113. }
  114. // Clean up temporary data.
  115. delete Blockly.Lua.definitions_;
  116. delete Blockly.Lua.functionNames_;
  117. Blockly.Lua.variableDB_.reset();
  118. return definitions.join('\n\n') + '\n\n\n' + code;
  119. };
  120. /**
  121. * Naked values are top-level blocks with outputs that aren't plugged into
  122. * anything. In Lua, an expression is not a legal statement, so we must assign
  123. * the value to the (conventionally ignored) _.
  124. * http://lua-users.org/wiki/ExpressionsAsStatements
  125. * @param {string} line Line of generated code.
  126. * @return {string} Legal line of code.
  127. */
  128. Blockly.Lua.scrubNakedValue = function(line) {
  129. return 'local _ = ' + line + '\n';
  130. };
  131. /**
  132. * Encode a string as a properly escaped Lua string, complete with
  133. * quotes.
  134. * @param {string} string Text to encode.
  135. * @return {string} Lua string.
  136. * @private
  137. */
  138. Blockly.Lua.quote_ = function(string) {
  139. string = string.replace(/\\/g, '\\\\')
  140. .replace(/\n/g, '\\\n')
  141. .replace(/'/g, '\\\'');
  142. return '\'' + string + '\'';
  143. };
  144. /**
  145. * Common tasks for generating Lua from blocks.
  146. * Handles comments for the specified block and any connected value blocks.
  147. * Calls any statements following this block.
  148. * @param {!Blockly.Block} block The current block.
  149. * @param {string} code The Lua code created for this block.
  150. * @return {string} Lua code with comments and subsequent blocks added.
  151. * @private
  152. */
  153. Blockly.Lua.scrub_ = function(block, code) {
  154. var commentCode = '';
  155. // Only collect comments for blocks that aren't inline.
  156. if (!block.outputConnection || !block.outputConnection.targetConnection) {
  157. // Collect comment for this block.
  158. var comment = block.getCommentText();
  159. comment = Blockly.utils.wrap(comment, Blockly.Lua.COMMENT_WRAP - 3);
  160. if (comment) {
  161. commentCode += Blockly.Lua.prefixLines(comment, '-- ') + '\n';
  162. }
  163. // Collect comments for all value arguments.
  164. // Don't collect comments for nested statements.
  165. for (var i = 0; i < block.inputList.length; i++) {
  166. if (block.inputList[i].type == Blockly.INPUT_VALUE) {
  167. var childBlock = block.inputList[i].connection.targetBlock();
  168. if (childBlock) {
  169. comment = Blockly.Lua.allNestedComments(childBlock);
  170. if (comment) {
  171. commentCode += Blockly.Lua.prefixLines(comment, '-- ');
  172. }
  173. }
  174. }
  175. }
  176. }
  177. var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
  178. var nextCode = Blockly.Lua.blockToCode(nextBlock);
  179. return commentCode + code + nextCode;
  180. };