Code of smartpascal.js

/**
 * @license
 * Visual Blocks Language
 *
 * Copyright 2012 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Helper functions for generating Smart Pascal for blocks.
 * @author nmorrison@pp4s.co.uk (Norman Morrison) 
 * Adapted from JavaScript by fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.SmartPascal');

goog.require('Blockly.Generator');


/**
 * SmartPascal code generator.
 * @type {!Blockly.Generator}
 */
Blockly.SmartPascal = new Blockly.Generator('SmartPascal');

/**
 * List of illegal variable names.
 * This is not intended to be a security feature.  Blockly is 100% client-side,
 * so bypassing this list is trivial.  This is intended to prevent users from
 * accidentally clobbering a built-in object or function.
 * @private
 */
Blockly.SmartPascal.addReservedWords(
    'Blockly,' +      'boolean,byte,bytebool,cardinal,char,comp,currency,double,extended,integer,int64,longbool,longint,longword,qword,real,single,shortint,shortstring,smallint,string,tdatetime,word,wordbool' +
'abstract,and,array,class,const,constructor,div,exit,export,file,function,implementation,import,in,inherited,initialization,interface,label,lambda,mod,module,new,nil,not,only,or,packed,pow,pragma,private,procedure,program,property,protected,public,override,qualified,record,restricted,set,type,unit,uses,var,virtual' +
'asm,begin,case,do,downto,else,end,except,for,goto,if,of,otherwise,repeat,then,to,try,until,while,with'+ 
'class,enum,export,extends,import,super,implements,interface,let,package,private,protected,public,static,yield, const,null,true,false,' +    'Array,ArrayBuffer,Boolean,Date,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Error,eval,EvalError,Float32Array,Float64Array,Function,Infinity,Int16Array,Int32Array,Int8Array,isFinite,isNaN,Iterator,JSON,Math,NaN,Number,Object,parseFloat,parseInt,RangeError,ReferenceError,RegExp,StopIteration,String,SyntaxError,TypeError,Uint16Array,Uint32Array,Uint8Array,Uint8ClampedArray,undefined,uneval,URIError,' +    'Attr,CDATASection,CharacterData,Comment,console,DocumentFragment,DocumentType,DomConfiguration,DOMError,DOMErrorHandler,DOMException,DOMImplementation,DOMImplementationList,DOMImplementationRegistry,DOMImplementationSource,DOMLocator,DOMObject,DOMString,DOMStringList,DOMTimeStamp,DOMUserData,Entity,EntityReference,MediaQueryList,MediaQueryListListener,NameList,NamedNodeMap,Node,NodeFilter,NodeIterator,NodeList,Notation,Plugin,PluginArray,ProcessingInstruction,SharedWorker,Text,TimeRanges,Treewalker,TypeInfo,UserDataHandler,Worker,WorkerGlobalScope');

/**
 * Order of operation ENUMs. Copied from JavaScript at
 * https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence
 */
Blockly.SmartPascal.ORDER_ATOMIC = 0;           // 0 "" ...
Blockly.SmartPascal.ORDER_NEW = 1.1;            // new
Blockly.SmartPascal.ORDER_MEMBER = 1.2;         // . []
Blockly.SmartPascal.ORDER_FUNCTION_CALL = 2;    // ()
Blockly.SmartPascal.ORDER_INCREMENT = 3;        // ++
Blockly.SmartPascal.ORDER_DECREMENT = 3;        // --
Blockly.SmartPascal.ORDER_BITWISE_NOT = 4.1;    // ~
Blockly.SmartPascal.ORDER_UNARY_PLUS = 4.2;     // +
Blockly.SmartPascal.ORDER_UNARY_NEGATION = 4.3; // -
Blockly.SmartPascal.ORDER_LOGICAL_NOT = 4.4;    // !
Blockly.SmartPascal.ORDER_TYPEOF = 4.5;         // typeof
Blockly.SmartPascal.ORDER_VOID = 4.6;           // void
Blockly.SmartPascal.ORDER_DELETE = 4.7;         // delete
Blockly.SmartPascal.ORDER_DIVISION = 5.1;       // /
Blockly.SmartPascal.ORDER_MULTIPLICATION = 5.2; // *
Blockly.SmartPascal.ORDER_MODULUS = 5.3;        // %
Blockly.SmartPascal.ORDER_SUBTRACTION = 6.1;    // -
Blockly.SmartPascal.ORDER_ADDITION = 6.2;       // +
Blockly.SmartPascal.ORDER_BITWISE_SHIFT = 7;    // << >> >>>
Blockly.SmartPascal.ORDER_RELATIONAL = 8;       // < <= > >=
Blockly.SmartPascal.ORDER_IN = 8;               // in
Blockly.SmartPascal.ORDER_INSTANCEOF = 8;       // instanceof
Blockly.SmartPascal.ORDER_EQUALITY = 9;         // == != === !==
Blockly.SmartPascal.ORDER_BITWISE_AND = 10;     // &
Blockly.SmartPascal.ORDER_BITWISE_XOR = 11;     // ^
Blockly.SmartPascal.ORDER_BITWISE_OR = 12;      // |
Blockly.SmartPascal.ORDER_LOGICAL_AND = 13;     // &&
Blockly.SmartPascal.ORDER_LOGICAL_OR = 14;      // ||
Blockly.SmartPascal.ORDER_CONDITIONAL = 15;     // ?:
Blockly.SmartPascal.ORDER_ASSIGNMENT = 16;      // = += -= *= /= %= <<= >>= ...
Blockly.SmartPascal.ORDER_COMMA = 17;           // ,
Blockly.SmartPascal.ORDER_NONE = 99;            // (...)

/**
 * List of outer-inner pairings that do NOT require parentheses.
 * @type {!Array.<!Array.<number>>}
 */
Blockly.SmartPascal.ORDER_OVERRIDES = [
  // (foo()).bar -> foo().bar
  // (foo())[0] -> foo()[0]
  [Blockly.SmartPascal.ORDER_FUNCTION_CALL, Blockly.SmartPascal.ORDER_MEMBER],
  // (foo())() -> foo()()
  [Blockly.SmartPascal.ORDER_FUNCTION_CALL, Blockly.SmartPascal.ORDER_FUNCTION_CALL],
  // (foo.bar).baz -> foo.bar.baz
  // (foo.bar)[0] -> foo.bar[0]
  // (foo[0]).bar -> foo[0].bar
  // (foo[0])[1] -> foo[0][1]
  [Blockly.SmartPascal.ORDER_MEMBER, Blockly.SmartPascal.ORDER_MEMBER],
  // (foo.bar)() -> foo.bar()
  // (foo[0])() -> foo[0]()
  [Blockly.SmartPascal.ORDER_MEMBER, Blockly.SmartPascal.ORDER_FUNCTION_CALL],

  // !(!foo) -> !!foo
  [Blockly.SmartPascal.ORDER_LOGICAL_NOT, Blockly.SmartPascal.ORDER_LOGICAL_NOT],
  // a * (b * c) -> a * b * c
  [Blockly.SmartPascal.ORDER_MULTIPLICATION, Blockly.SmartPascal.ORDER_MULTIPLICATION],
  // a + (b + c) -> a + b + c
  [Blockly.SmartPascal.ORDER_ADDITION, Blockly.SmartPascal.ORDER_ADDITION],
  // a && (b && c) -> a && b && c
  [Blockly.SmartPascal.ORDER_LOGICAL_AND, Blockly.SmartPascal.ORDER_LOGICAL_AND],
  // a || (b || c) -> a || b || c
  [Blockly.SmartPascal.ORDER_LOGICAL_OR, Blockly.SmartPascal.ORDER_LOGICAL_OR]
];

/**
 * Initialise the database of variable names.
 * @param {!Blockly.Workspace} workspace Workspace to generate code from.
 */
Blockly.SmartPascal.init = function(workspace) {
  // Create a dictionary of definitions to be printed before the code.
  Blockly.SmartPascal.definitions_ = Object.create(null);
  // Create a dictionary mapping desired function names in definitions_
  // to actual function names (to avoid collisions with user functions).
  Blockly.SmartPascal.functionNames_ = Object.create(null);

  if (!Blockly.SmartPascal.variableDB_) {
    Blockly.SmartPascal.variableDB_ =
        new Blockly.Names(Blockly.SmartPascal.RESERVED_WORDS_);
  } else {
    Blockly.SmartPascal.variableDB_.reset();
  }

  var currentVar = ''; 
  var declarationCode = '';
  var lcCurrentVar = '';
 // var defvars = [];
  var variables = workspace.variableList;
  if (variables.length) {
    for (var i = 0; i < variables.length; i++) {
      currentVar = Blockly.SmartPascal.variableDB_.getName(variables[i],
          Blockly.Variables.NAME_TYPE);
      if (currentVar.length > 1) {   // Do not declare single character variables
        lcCurrentVar = currentVar.toLowerCase();      
        declarationCode += 'var ' + currentVar + ': ';    

        if (lcCurrentVar.indexOf('array') >= 0) { 
          if (lcCurrentVar.indexOf('str') >= 0 ) {
            declarationCode += 'TStrArray;\n';
          }
          else if (lcCurrentVar.indexOf('int') >= 0) {
           declarationCode += 'TIntArray;\n';
          }
          else if (lcCurrentVar.indexOf('float') >= 0) {
           declarationCode += 'TFloatArray;\n';
          }
          else {
           declarationCode += 'Variant;\n'; 
          } 
        }
        else if (lcCurrentVar.indexOf('str') >= 0) {  
           declarationCode += 'String;\n';
        } 
        else if (lcCurrentVar.indexOf('int') >= 0) {
           declarationCode += 'Integer;\n';
        } 
        else if (lcCurrentVar.indexOf('float') >= 0) {
           declarationCode += 'Float;\n';
        } 
        else if (lcCurrentVar.indexOf('bool') >= 0) {
           declarationCode += 'Boolean;\n';
        }
        else {
          declarationCode += 'Variant;\n';
        }
      }
    }
    Blockly.SmartPascal.definitions_['variables'] = declarationCode;    
  }
};

/**
 * Prepend the generated code with the variable definitions.
 * @param {string} code Generated code.
 * @return {string} Completed code.
 */
Blockly.SmartPascal.finish = function(code) {
  // Convert the definitions dictionary into a list.
  var definitions = [];
  for (var name in Blockly.SmartPascal.definitions_) {
    definitions.push(Blockly.SmartPascal.definitions_[name]);
  }
  // Clean up temporary data.
  delete Blockly.SmartPascal.definitions_;
  delete Blockly.SmartPascal.functionNames_;
  Blockly.SmartPascal.variableDB_.reset();
  return definitions.join('\n\n') + '\n\n\n' + code;
};

/**
 * Naked values are top-level blocks with outputs that aren't plugged into
 * anything.  A trailing semicolon is needed to make this legal.
 * @param {string} line Line of generated code.
 * @return {string} Legal line of code.
 */
Blockly.SmartPascal.scrubNakedValue = function(line) {
  return line + ';\n';
};

/**
 * Encode a string as a properly escaped SmartPascal string, complete with
 * quotes.
 * @param {string} string Text to encode.
 * @return {string} SmartPascal string.
 * @private
 */
Blockly.SmartPascal.quote_ = function(string) {
  // Can't use goog.string.quote since Google's style guide recommends
  // JS string literals use single quotes.
  string = string.replace(/\\/g, '\\\\')
                 .replace(/\n/g, '\\\n')
                 .replace(/'/g, '\\\'');
  return '\'' + string + '\'';
};

/**
 * Common tasks for generating SmartPascal from blocks.
 * Handles comments for the specified block and any connected value blocks.
 * Calls any statements following this block.
 * @param {!Blockly.Block} block The current block.
 * @param {string} code The SmartPascal code created for this block.
 * @return {string} SmartPascal code with comments and subsequent blocks added.
 * @private
 */
Blockly.SmartPascal.scrub_ = function(block, code) {
  var commentCode = '';
  // Only collect comments for blocks that aren't inline.
  if (!block.outputConnection || !block.outputConnection.targetConnection) {
    // Collect comment for this block.
    var comment = block.getCommentText();
    comment = Blockly.utils.wrap(comment, Blockly.SmartPascal.COMMENT_WRAP - 3);
    if (comment) {
      if (block.getProcedureDef) {
        // Use a comment block for function comments.
        commentCode += '{\n' +
                       Blockly.SmartPascal.prefixLines(comment + '\n', '  ') +
                        '}\n';
      } else {
        commentCode += Blockly.SmartPascal.prefixLines(comment + '\n', '// ');
      }
    }
    // Collect comments for all value arguments.
    // Don't collect comments for nested statements.
    for (var i = 0; i < block.inputList.length; i++) {
      if (block.inputList[i].type == Blockly.INPUT_VALUE) {
        var childBlock = block.inputList[i].connection.targetBlock();
        if (childBlock) {
          var comment = Blockly.SmartPascal.allNestedComments(childBlock);
          if (comment) {
            commentCode += Blockly.SmartPascal.prefixLines(comment, '// ');
          }
        }
      }
    }
  }
  var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
  var nextCode = Blockly.SmartPascal.blockToCode(nextBlock);
  return commentCode + code + nextCode;
};

/**
 * Gets a property and adjusts the value while taking into account indexing.
 * @param {!Blockly.Block} block The block.
 * @param {string} atId The property ID of the element to get.
 * @param {number=} opt_delta Value to add.
 * @param {boolean=} opt_negate Whether to negate the value.
 * @param {number=} opt_order The highest order acting on this value.
 * @return {string|number}
 */
Blockly.SmartPascal.getAdjusted = function(block, atId, opt_delta, opt_negate,
    opt_order) {
  var delta = opt_delta || 0;
  var order = opt_order || Blockly.SmartPascal.ORDER_NONE;
  if (block.workspace.options.oneBasedIndex) {
    delta--;
  }
  var defaultAtIndex = block.workspace.options.oneBasedIndex ? '1' : '0';
  if (delta > 0) {
    var at = Blockly.SmartPascal.valueToCode(block, atId,
        Blockly.SmartPascal.ORDER_ADDITION) || defaultAtIndex;
  } else if (delta < 0) {
    var at = Blockly.SmartPascal.valueToCode(block, atId,
        Blockly.SmartPascal.ORDER_SUBTRACTION) || defaultAtIndex;
  } else if (opt_negate) {
    var at = Blockly.SmartPascal.valueToCode(block, atId,
        Blockly.SmartPascal.ORDER_UNARY_NEGATION) || defaultAtIndex;
  } else {
    var at = Blockly.SmartPascal.valueToCode(block, atId, order) ||
        defaultAtIndex;
  }

  if (Blockly.isNumber(at)) {
    // If the index is a naked number, adjust it right now.
    at = parseFloat(at) + delta;
    if (opt_negate) {
      at = -at;
    }
  } else {
    // If the index is dynamic, adjust it in code.
    if (delta > 0) {
      at = at + ' + ' + delta;
      var innerOrder = Blockly.SmartPascal.ORDER_ADDITION;
    } else if (delta < 0) {
      at = at + ' - ' + -delta;
      var innerOrder = Blockly.SmartPascal.ORDER_SUBTRACTION;
    }
    if (opt_negate) {
      if (delta) {
        at = '-(' + at + ')';
      } else {
        at = '-' + at;
      }
      var innerOrder = Blockly.SmartPascal.ORDER_UNARY_NEGATION;
    }
    innerOrder = Math.floor(innerOrder);
    order = Math.floor(order);
    if (innerOrder && order >= innerOrder) {
      at = '(' + at + ')';
    }
  }
  return at;
};

Programming - a skill for life!

Notes on the conversion of Blockly output from JavaScript to Smart Pascal with links to the pages of new JavaScript code