VariablesParseState.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. "use strict";
  2. /**
  3. * This class represents the Variables that are defined in an Expression tree.
  4. *
  5. * All copies from a given instance share enough information to ensure unique Ids are assigned
  6. * and to propagate back to the original instance enough information to correctly construct a
  7. * Variables instance.
  8. *
  9. * @class VariablesParseState
  10. * @namespace mungedb-aggregate.pipeline.expressions
  11. * @module mungedb-aggregate
  12. * @constructor
  13. */
  14. var Variables = require("./Variables"),
  15. VariablesIdGenerator = require("./VariablesIdGenerator");
  16. var VariablesParseState = module.exports = function VariablesParseState(idGenerator){
  17. if (!(idGenerator instanceof VariablesIdGenerator)) throw new Error("idGenerator is required and must be of type VariablesIdGenerator");
  18. this._idGenerator = idGenerator;
  19. this._variables = {};
  20. }, klass = VariablesParseState, proto = klass.prototype;
  21. /**
  22. * Assigns a named variable a unique Id. This differs from all other variables, even
  23. * others with the same name.
  24. *
  25. * The special variables ROOT and CURRENT are always implicitly defined with CURRENT
  26. * equivalent to ROOT. If CURRENT is explicitly defined by a call to this function, it
  27. * breaks that equivalence.
  28. *
  29. * NOTE: Name validation is responsibility of caller.
  30. */
  31. proto.defineVariable = function defineVariable(name) {
  32. // caller should have validated before hand by using Variables::uassertValidNameForUserWrite
  33. if (name === "ROOT")
  34. throw new Error("Can't redefine ROOT; massert code 17275");
  35. var id = this._idGenerator.generateId();
  36. this._variables[name] = id;
  37. return id;
  38. };
  39. /**
  40. * Returns the current Id for a variable. uasserts if the variable isn't defined.
  41. * @method getVariable
  42. * @param name {String} The name of the variable
  43. */
  44. proto.getVariable = function getVariable(name) {
  45. var it = this._variables[name];
  46. if (typeof it === "number")
  47. return it;
  48. if (name !== "ROOT" && name !== "CURRENT")
  49. throw new Error("Use of undefined variable " + name + "; uassert code 17276");
  50. return Variables.ROOT_ID;
  51. };