You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
1.2 KiB

4 years ago
  1. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  2. import { print } from "@webassemblyjs/wast-printer";
  3. var SHOW_LINES_AROUND_POINTER = 5;
  4. function repeat(char, nb) {
  5. return Array(nb).fill(char).join("");
  6. } // TODO(sven): allow arbitrary ast nodes
  7. export function codeFrameFromAst(ast, loc) {
  8. return codeFrameFromSource(print(ast), loc);
  9. }
  10. export function codeFrameFromSource(source, loc) {
  11. var start = loc.start,
  12. end = loc.end;
  13. var length = 1;
  14. if (_typeof(end) === "object") {
  15. length = end.column - start.column + 1;
  16. }
  17. return source.split("\n").reduce(function (acc, line, lineNbr) {
  18. if (Math.abs(start.line - lineNbr) < SHOW_LINES_AROUND_POINTER) {
  19. acc += line + "\n";
  20. } // Add a new line with the pointer padded left
  21. if (lineNbr === start.line - 1) {
  22. acc += repeat(" ", start.column - 1);
  23. acc += repeat("^", length);
  24. acc += "\n";
  25. }
  26. return acc;
  27. }, "");
  28. }