ParserHelpers.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const path = require("path");
  7. const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
  8. const ConstDependency = require("./dependencies/ConstDependency");
  9. const UnsupportedFeatureWarning = require("./UnsupportedFeatureWarning");
  10. const ParserHelpers = exports;
  11. ParserHelpers.addParsedVariableToModule = function(parser, name, expression) {
  12. if(!parser.state.current.addVariable) return false;
  13. var deps = [];
  14. parser.parse(expression, {
  15. current: {
  16. addDependency: function(dep) {
  17. dep.userRequest = name;
  18. deps.push(dep);
  19. }
  20. },
  21. module: parser.state.module
  22. });
  23. parser.state.current.addVariable(name, expression, deps);
  24. return true;
  25. };
  26. ParserHelpers.requireFileAsExpression = function(context, pathToModule) {
  27. var moduleJsPath = path.relative(context, pathToModule);
  28. if(!/^[A-Z]:/i.test(moduleJsPath)) {
  29. moduleJsPath = "./" + moduleJsPath.replace(/\\/g, "/");
  30. }
  31. return "require(" + JSON.stringify(moduleJsPath) + ")";
  32. };
  33. ParserHelpers.toConstantDependency = function(value) {
  34. return function constDependency(expr) {
  35. var dep = new ConstDependency(value, expr.range);
  36. dep.loc = expr.loc;
  37. this.state.current.addDependency(dep);
  38. return true;
  39. };
  40. };
  41. ParserHelpers.evaluateToString = function(value) {
  42. return function stringExpression(expr) {
  43. return new BasicEvaluatedExpression().setString(value).setRange(expr.range);
  44. };
  45. };
  46. ParserHelpers.evaluateToBoolean = function(value) {
  47. return function booleanExpression(expr) {
  48. return new BasicEvaluatedExpression().setBoolean(value).setRange(expr.range);
  49. };
  50. };
  51. ParserHelpers.expressionIsUnsupported = function(message) {
  52. return function unsupportedExpression(expr) {
  53. var dep = new ConstDependency("(void 0)", expr.range);
  54. dep.loc = expr.loc;
  55. this.state.current.addDependency(dep);
  56. if(!this.state.module) return;
  57. this.state.module.warnings.push(new UnsupportedFeatureWarning(this.state.module, message));
  58. return true;
  59. };
  60. };
  61. ParserHelpers.skipTraversal = function skipTraversal() {
  62. return true;
  63. };
  64. ParserHelpers.approve = function approve() {
  65. return true;
  66. };