code.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. "use strict";
  2. var Class = require("rtl.js").Class;
  3. var Type = require("type.js");
  4. var NullCodeGenerator = Class.extend({
  5. init: function NullCodeGenerator(){},
  6. write: function(){},
  7. openScope: function(){},
  8. closeScope: function(){}
  9. });
  10. exports.Generator = Class.extend({
  11. init: function CodeGenerator(){
  12. this.__result = "";
  13. this.__indent = "";
  14. },
  15. write: function(s){
  16. this.__result += s.replace(/\n/g, "\n" + this.__indent);
  17. },
  18. openScope: function(){
  19. this.__indent += "\t";
  20. this.__result += "{\n" + this.__indent;
  21. },
  22. closeScope: function(ending){
  23. this.__indent = this.__indent.substr(1);
  24. this.__result = this.__result.substr(0, this.__result.length - 1) + "}";
  25. if (ending)
  26. this.write(ending);
  27. else
  28. this.write("\n");
  29. },
  30. getResult: function(){return this.__result;}
  31. });
  32. exports.SimpleGenerator = Class.extend({
  33. init: function SimpleCodeGenerator(code){this.__result = code ? code : "";},
  34. write: function(s){this.__result += s;},
  35. result: function(){return this.__result;}
  36. });
  37. var Expression = Class.extend({
  38. init: function Expression(code, type, designator, constValue, maxPrecedence){
  39. this.__code = code;
  40. this.__type = type;
  41. this.__designator = designator;
  42. this.__constValue = constValue;
  43. this.__maxPrecedence = maxPrecedence;
  44. },
  45. code: function(){return this.__code;},
  46. type: function(){return this.__type;},
  47. designator: function(){return this.__designator;},
  48. constValue: function(){return this.__constValue;},
  49. maxPrecedence: function(){return this.__maxPrecedence;},
  50. isTerm: function(){return !this.__designator && this.__maxPrecedence === undefined;},
  51. deref: function(){
  52. if (!this.__designator)
  53. return this;
  54. if (this.__type instanceof Type.Array || this.__type instanceof Type.Record)
  55. return this;
  56. var info = this.__designator.info();
  57. if (!(info instanceof Type.VariableRef))
  58. return this;
  59. return new Expression(this.__code + ".get()", this.__type);
  60. },
  61. ref: function(){
  62. if (!this.__designator)
  63. return this;
  64. var info = this.__designator.info();
  65. if (info instanceof Type.VariableRef)
  66. return this;
  67. return new Expression(this.__designator.refCode(), this.__type);
  68. }
  69. });
  70. function adjustPrecedence(e, precedence){
  71. var code = e.code();
  72. if (e.maxPrecedence() > precedence)
  73. code = "(" + code + ")";
  74. return code;
  75. }
  76. exports.nullGenerator = new NullCodeGenerator();
  77. exports.Expression = Expression;
  78. exports.adjustPrecedence = adjustPrecedence;