php.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. /**
  2. * @license
  3. * Visual Blocks Language
  4. *
  5. * Copyright 2015 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 PHP for blocks.
  22. * @author daarond@gmail.com (Daaron Dwyer)
  23. */
  24. 'use strict';
  25. goog.provide('Blockly.PHP');
  26. goog.require('Blockly.Generator');
  27. /**
  28. * PHP code generator.
  29. * @type {!Blockly.Generator}
  30. */
  31. Blockly.PHP = new Blockly.Generator('PHP');
  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.PHP.addReservedWords(
  40. // http://php.net/manual/en/reserved.keywords.php
  41. '__halt_compiler,abstract,and,array,as,break,callable,case,catch,class,' +
  42. 'clone,const,continue,declare,default,die,do,echo,else,elseif,empty,' +
  43. 'enddeclare,endfor,endforeach,endif,endswitch,endwhile,eval,exit,extends,' +
  44. 'final,for,foreach,function,global,goto,if,implements,include,' +
  45. 'include_once,instanceof,insteadof,interface,isset,list,namespace,new,or,' +
  46. 'print,private,protected,public,require,require_once,return,static,' +
  47. 'switch,throw,trait,try,unset,use,var,while,xor,' +
  48. // http://php.net/manual/en/reserved.constants.php
  49. 'PHP_VERSION,PHP_MAJOR_VERSION,PHP_MINOR_VERSION,PHP_RELEASE_VERSION,' +
  50. 'PHP_VERSION_ID,PHP_EXTRA_VERSION,PHP_ZTS,PHP_DEBUG,PHP_MAXPATHLEN,' +
  51. 'PHP_OS,PHP_SAPI,PHP_EOL,PHP_INT_MAX,PHP_INT_SIZE,DEFAULT_INCLUDE_PATH,' +
  52. 'PEAR_INSTALL_DIR,PEAR_EXTENSION_DIR,PHP_EXTENSION_DIR,PHP_PREFIX,' +
  53. 'PHP_BINDIR,PHP_BINARY,PHP_MANDIR,PHP_LIBDIR,PHP_DATADIR,PHP_SYSCONFDIR,' +
  54. 'PHP_LOCALSTATEDIR,PHP_CONFIG_FILE_PATH,PHP_CONFIG_FILE_SCAN_DIR,' +
  55. 'PHP_SHLIB_SUFFIX,E_ERROR,E_WARNING,E_PARSE,E_NOTICE,E_CORE_ERROR,' +
  56. 'E_CORE_WARNING,E_COMPILE_ERROR,E_COMPILE_WARNING,E_USER_ERROR,' +
  57. 'E_USER_WARNING,E_USER_NOTICE,E_DEPRECATED,E_USER_DEPRECATED,E_ALL,' +
  58. 'E_STRICT,__COMPILER_HALT_OFFSET__,TRUE,FALSE,NULL,__CLASS__,__DIR__,' +
  59. '__FILE__,__FUNCTION__,__LINE__,__METHOD__,__NAMESPACE__,__TRAIT__'
  60. );
  61. /**
  62. * Order of operation ENUMs.
  63. * http://php.net/manual/en/language.operators.precedence.php
  64. */
  65. Blockly.PHP.ORDER_ATOMIC = 0; // 0 "" ...
  66. Blockly.PHP.ORDER_CLONE = 1; // clone
  67. Blockly.PHP.ORDER_NEW = 1; // new
  68. Blockly.PHP.ORDER_MEMBER = 2.1; // []
  69. Blockly.PHP.ORDER_FUNCTION_CALL = 2.2; // ()
  70. Blockly.PHP.ORDER_POWER = 3; // **
  71. Blockly.PHP.ORDER_INCREMENT = 4; // ++
  72. Blockly.PHP.ORDER_DECREMENT = 4; // --
  73. Blockly.PHP.ORDER_BITWISE_NOT = 4; // ~
  74. Blockly.PHP.ORDER_CAST = 4; // (int) (float) (string) (array) ...
  75. Blockly.PHP.ORDER_SUPPRESS_ERROR = 4; // @
  76. Blockly.PHP.ORDER_INSTANCEOF = 5; // instanceof
  77. Blockly.PHP.ORDER_LOGICAL_NOT = 6; // !
  78. Blockly.PHP.ORDER_UNARY_PLUS = 7.1; // +
  79. Blockly.PHP.ORDER_UNARY_NEGATION = 7.2; // -
  80. Blockly.PHP.ORDER_MULTIPLICATION = 8.1; // *
  81. Blockly.PHP.ORDER_DIVISION = 8.2; // /
  82. Blockly.PHP.ORDER_MODULUS = 8.3; // %
  83. Blockly.PHP.ORDER_ADDITION = 9.1; // +
  84. Blockly.PHP.ORDER_SUBTRACTION = 9.2; // -
  85. Blockly.PHP.ORDER_STRING_CONCAT = 9.3; // .
  86. Blockly.PHP.ORDER_BITWISE_SHIFT = 10; // << >>
  87. Blockly.PHP.ORDER_RELATIONAL = 11; // < <= > >=
  88. Blockly.PHP.ORDER_EQUALITY = 12; // == != === !== <> <=>
  89. Blockly.PHP.ORDER_REFERENCE = 13; // &
  90. Blockly.PHP.ORDER_BITWISE_AND = 13; // &
  91. Blockly.PHP.ORDER_BITWISE_XOR = 14; // ^
  92. Blockly.PHP.ORDER_BITWISE_OR = 15; // |
  93. Blockly.PHP.ORDER_LOGICAL_AND = 16; // &&
  94. Blockly.PHP.ORDER_LOGICAL_OR = 17; // ||
  95. Blockly.PHP.ORDER_IF_NULL = 18; // ??
  96. Blockly.PHP.ORDER_CONDITIONAL = 19; // ?:
  97. Blockly.PHP.ORDER_ASSIGNMENT = 20; // = += -= *= /= %= <<= >>= ...
  98. Blockly.PHP.ORDER_LOGICAL_AND_WEAK = 21; // and
  99. Blockly.PHP.ORDER_LOGICAL_XOR = 22; // xor
  100. Blockly.PHP.ORDER_LOGICAL_OR_WEAK = 23; // or
  101. Blockly.PHP.ORDER_COMMA = 24; // ,
  102. Blockly.PHP.ORDER_NONE = 99; // (...)
  103. /**
  104. * List of outer-inner pairings that do NOT require parentheses.
  105. * @type {!Array.<!Array.<number>>}
  106. */
  107. Blockly.PHP.ORDER_OVERRIDES = [
  108. // (foo()).bar() -> foo().bar()
  109. // (foo())[0] -> foo()[0]
  110. [Blockly.PHP.ORDER_MEMBER, Blockly.PHP.ORDER_FUNCTION_CALL],
  111. // (foo[0])[1] -> foo[0][1]
  112. // (foo.bar).baz -> foo.bar.baz
  113. [Blockly.PHP.ORDER_MEMBER, Blockly.PHP.ORDER_MEMBER],
  114. // !(!foo) -> !!foo
  115. [Blockly.PHP.ORDER_LOGICAL_NOT, Blockly.PHP.ORDER_LOGICAL_NOT],
  116. // a * (b * c) -> a * b * c
  117. [Blockly.PHP.ORDER_MULTIPLICATION, Blockly.PHP.ORDER_MULTIPLICATION],
  118. // a + (b + c) -> a + b + c
  119. [Blockly.PHP.ORDER_ADDITION, Blockly.PHP.ORDER_ADDITION],
  120. // a && (b && c) -> a && b && c
  121. [Blockly.PHP.ORDER_LOGICAL_AND, Blockly.PHP.ORDER_LOGICAL_AND],
  122. // a || (b || c) -> a || b || c
  123. [Blockly.PHP.ORDER_LOGICAL_OR, Blockly.PHP.ORDER_LOGICAL_OR]
  124. ];
  125. /**
  126. * Allow for switching between one and zero based indexing for lists and text,
  127. * one based by default.
  128. */
  129. Blockly.PHP.ONE_BASED_INDEXING = true;
  130. /**
  131. * Initialise the database of variable names.
  132. * @param {!Blockly.Workspace} workspace Workspace to generate code from.
  133. */
  134. Blockly.PHP.init = function(workspace) {
  135. // Create a dictionary of definitions to be printed before the code.
  136. Blockly.PHP.definitions_ = Object.create(null);
  137. // Create a dictionary mapping desired function names in definitions_
  138. // to actual function names (to avoid collisions with user functions).
  139. Blockly.PHP.functionNames_ = Object.create(null);
  140. if (!Blockly.PHP.variableDB_) {
  141. Blockly.PHP.variableDB_ =
  142. new Blockly.Names(Blockly.PHP.RESERVED_WORDS_, '$');
  143. } else {
  144. Blockly.PHP.variableDB_.reset();
  145. }
  146. var defvars = [];
  147. var variables = Blockly.Variables.allVariables(workspace);
  148. for (var i = 0; i < variables.length; i++) {
  149. defvars[i] = Blockly.PHP.variableDB_.getName(variables[i],
  150. Blockly.Variables.NAME_TYPE) + ';';
  151. }
  152. Blockly.PHP.definitions_['variables'] = defvars.join('\n');
  153. };
  154. /**
  155. * Prepend the generated code with the variable definitions.
  156. * @param {string} code Generated code.
  157. * @return {string} Completed code.
  158. */
  159. Blockly.PHP.finish = function(code) {
  160. // Convert the definitions dictionary into a list.
  161. var definitions = [];
  162. for (var name in Blockly.PHP.definitions_) {
  163. definitions.push(Blockly.PHP.definitions_[name]);
  164. }
  165. // Clean up temporary data.
  166. delete Blockly.PHP.definitions_;
  167. delete Blockly.PHP.functionNames_;
  168. Blockly.PHP.variableDB_.reset();
  169. return definitions.join('\n\n') + '\n\n\n' + code;
  170. };
  171. /**
  172. * Naked values are top-level blocks with outputs that aren't plugged into
  173. * anything. A trailing semicolon is needed to make this legal.
  174. * @param {string} line Line of generated code.
  175. * @return {string} Legal line of code.
  176. */
  177. Blockly.PHP.scrubNakedValue = function(line) {
  178. return line + ';\n';
  179. };
  180. /**
  181. * Encode a string as a properly escaped PHP string, complete with
  182. * quotes.
  183. * @param {string} string Text to encode.
  184. * @return {string} PHP string.
  185. * @private
  186. */
  187. Blockly.PHP.quote_ = function(string) {
  188. string = string.replace(/\\/g, '\\\\')
  189. .replace(/\n/g, '\\\n')
  190. .replace(/'/g, '\\\'');
  191. return '\'' + string + '\'';
  192. };
  193. /**
  194. * Common tasks for generating PHP from blocks.
  195. * Handles comments for the specified block and any connected value blocks.
  196. * Calls any statements following this block.
  197. * @param {!Blockly.Block} block The current block.
  198. * @param {string} code The PHP code created for this block.
  199. * @return {string} PHP code with comments and subsequent blocks added.
  200. * @private
  201. */
  202. Blockly.PHP.scrub_ = function(block, code) {
  203. var commentCode = '';
  204. // Only collect comments for blocks that aren't inline.
  205. if (!block.outputConnection || !block.outputConnection.targetConnection) {
  206. // Collect comment for this block.
  207. var comment = block.getCommentText();
  208. comment = Blockly.utils.wrap(comment, Blockly.PHP.COMMENT_WRAP - 3);
  209. if (comment) {
  210. commentCode += Blockly.PHP.prefixLines(comment, '// ') + '\n';
  211. }
  212. // Collect comments for all value arguments.
  213. // Don't collect comments for nested statements.
  214. for (var i = 0; i < block.inputList.length; i++) {
  215. if (block.inputList[i].type == Blockly.INPUT_VALUE) {
  216. var childBlock = block.inputList[i].connection.targetBlock();
  217. if (childBlock) {
  218. var comment = Blockly.PHP.allNestedComments(childBlock);
  219. if (comment) {
  220. commentCode += Blockly.PHP.prefixLines(comment, '// ');
  221. }
  222. }
  223. }
  224. }
  225. }
  226. var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
  227. var nextCode = Blockly.PHP.blockToCode(nextBlock);
  228. return commentCode + code + nextCode;
  229. };
  230. /**
  231. * Gets a property and adjusts the value while taking into account indexing.
  232. * @param {!Blockly.Block} block The block.
  233. * @param {string} atId The property ID of the element to get.
  234. * @param {number=} opt_delta Value to add.
  235. * @param {boolean=} opt_negate Whether to negate the value.
  236. * @param {number=} opt_order The highest order acting on this value.
  237. * @return {string|number}
  238. */
  239. Blockly.PHP.getAdjusted = function(block, atId, opt_delta, opt_negate,
  240. opt_order) {
  241. var delta = opt_delta || 0;
  242. var order = opt_order || Blockly.PHP.ORDER_NONE;
  243. if (Blockly.PHP.ONE_BASED_INDEXING) {
  244. delta--;
  245. }
  246. var defaultAtIndex = Blockly.PHP.ONE_BASED_INDEXING ? '1' : '0';
  247. if (delta > 0) {
  248. var at = Blockly.PHP.valueToCode(block, atId,
  249. Blockly.PHP.ORDER_ADDITION) || defaultAtIndex;
  250. } else if (delta < 0) {
  251. var at = Blockly.PHP.valueToCode(block, atId,
  252. Blockly.PHP.ORDER_SUBTRACTION) || defaultAtIndex;
  253. } else if (opt_negate) {
  254. var at = Blockly.PHP.valueToCode(block, atId,
  255. Blockly.PHP.ORDER_UNARY_NEGATION) || defaultAtIndex;
  256. } else {
  257. var at = Blockly.PHP.valueToCode(block, atId, order) ||
  258. defaultAtIndex;
  259. }
  260. if (Blockly.isNumber(at)) {
  261. // If the index is a naked number, adjust it right now.
  262. at = parseFloat(at) + delta;
  263. if (opt_negate) {
  264. at = -at;
  265. }
  266. } else {
  267. // If the index is dynamic, adjust it in code.
  268. if (delta > 0) {
  269. at = at + ' + ' + delta;
  270. var innerOrder = Blockly.PHP.ORDER_ADDITION;
  271. } else if (delta < 0) {
  272. at = at + ' - ' + -delta;
  273. var innerOrder = Blockly.PHP.ORDER_SUBTRACTION;
  274. }
  275. if (opt_negate) {
  276. if (delta) {
  277. at = '-(' + at + ')';
  278. } else {
  279. at = '-' + at;
  280. }
  281. var innerOrder = Blockly.PHP.ORDER_UNARY_NEGATION;
  282. }
  283. innerOrder = Math.floor(innerOrder);
  284. order = Math.floor(order);
  285. if (innerOrder && order >= innerOrder) {
  286. at = '(' + at + ')';
  287. }
  288. }
  289. return at;
  290. };