lua.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. * Initialise the database of variable names.
  83. * @param {!Blockly.Workspace} workspace Workspace to generate code from.
  84. */
  85. Blockly.Lua.init = function(workspace) {
  86. // Create a dictionary of definitions to be printed before the code.
  87. Blockly.Lua.definitions_ = Object.create(null);
  88. // Create a dictionary mapping desired function names in definitions_
  89. // to actual function names (to avoid collisions with user functions).
  90. Blockly.Lua.functionNames_ = Object.create(null);
  91. if (!Blockly.Lua.variableDB_) {
  92. Blockly.Lua.variableDB_ =
  93. new Blockly.Names(Blockly.Lua.RESERVED_WORDS_);
  94. } else {
  95. Blockly.Lua.variableDB_.reset();
  96. }
  97. };
  98. /**
  99. * Prepend the generated code with the variable definitions.
  100. * @param {string} code Generated code.
  101. * @return {string} Completed code.
  102. */
  103. Blockly.Lua.finish = function(code) {
  104. // Convert the definitions dictionary into a list.
  105. var definitions = [];
  106. for (var name in Blockly.Lua.definitions_) {
  107. definitions.push(Blockly.Lua.definitions_[name]);
  108. }
  109. // Clean up temporary data.
  110. delete Blockly.Lua.definitions_;
  111. delete Blockly.Lua.functionNames_;
  112. Blockly.Lua.variableDB_.reset();
  113. return definitions.join('\n\n') + '\n\n\n' + code;
  114. };
  115. /**
  116. * Naked values are top-level blocks with outputs that aren't plugged into
  117. * anything. In Lua, an expression is not a legal statement, so we must assign
  118. * the value to the (conventionally ignored) _.
  119. * http://lua-users.org/wiki/ExpressionsAsStatements
  120. * @param {string} line Line of generated code.
  121. * @return {string} Legal line of code.
  122. */
  123. Blockly.Lua.scrubNakedValue = function(line) {
  124. return 'local _ = ' + line + '\n';
  125. };
  126. /**
  127. * Encode a string as a properly escaped Lua string, complete with
  128. * quotes.
  129. * @param {string} string Text to encode.
  130. * @return {string} Lua string.
  131. * @private
  132. */
  133. Blockly.Lua.quote_ = function(string) {
  134. // TODO: This is a quick hack. Replace with goog.string.quote
  135. string = string.replace(/\\/g, '\\\\')
  136. .replace(/\n/g, '\\\n')
  137. .replace(/'/g, '\\\'');
  138. return '\'' + string + '\'';
  139. };
  140. /**
  141. * Common tasks for generating Lua from blocks.
  142. * Handles comments for the specified block and any connected value blocks.
  143. * Calls any statements following this block.
  144. * @param {!Blockly.Block} block The current block.
  145. * @param {string} code The Lua code created for this block.
  146. * @return {string} Lua code with comments and subsequent blocks added.
  147. * @private
  148. */
  149. Blockly.Lua.scrub_ = function(block, code) {
  150. var commentCode = '';
  151. // Only collect comments for blocks that aren't inline.
  152. if (!block.outputConnection || !block.outputConnection.targetConnection) {
  153. // Collect comment for this block.
  154. var comment = block.getCommentText();
  155. if (comment) {
  156. commentCode += Blockly.Lua.prefixLines(comment, '-- ') + '\n';
  157. }
  158. // Collect comments for all value arguments.
  159. // Don't collect comments for nested statements.
  160. for (var x = 0; x < block.inputList.length; x++) {
  161. if (block.inputList[x].type == Blockly.INPUT_VALUE) {
  162. var childBlock = block.inputList[x].connection.targetBlock();
  163. if (childBlock) {
  164. comment = Blockly.Lua.allNestedComments(childBlock);
  165. if (comment) {
  166. commentCode += Blockly.Lua.prefixLines(comment, '-- ');
  167. }
  168. }
  169. }
  170. }
  171. }
  172. var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
  173. var nextCode = Blockly.Lua.blockToCode(nextBlock);
  174. return commentCode + code + nextCode;
  175. };