UNPKG

1.71 kBJavaScriptView Raw
1"use strict";
2const engine = require("php-parser");
3
4function parse(text, parsers, opts) {
5 const inMarkdown = opts && opts.parentParser === "markdown";
6
7 if (!text && inMarkdown) {
8 return "";
9 }
10
11 // Todo https://github.com/glayzzle/php-parser/issues/170
12 text = text.replace(/\?>\r?\n<\?/g, "?>\n___PSEUDO_INLINE_PLACEHOLDER___<?");
13
14 // initialize a new parser instance
15 const parser = new engine({
16 parser: {
17 extractDoc: true,
18 },
19 ast: {
20 withPositions: true,
21 withSource: true,
22 },
23 });
24
25 const hasOpenPHPTag = text.indexOf("<?php") !== -1;
26 const parseAsEval = inMarkdown && !hasOpenPHPTag;
27
28 let ast;
29 try {
30 ast = parseAsEval ? parser.parseEval(text) : parser.parseCode(text);
31 } catch (err) {
32 if (err instanceof SyntaxError && "lineNumber" in err) {
33 err.loc = {
34 start: {
35 line: err.lineNumber,
36 column: err.columnNumber,
37 },
38 };
39
40 delete err.lineNumber;
41 delete err.columnNumber;
42 }
43
44 throw err;
45 }
46
47 ast.extra = {
48 parseAsEval,
49 };
50
51 // https://github.com/glayzzle/php-parser/issues/155
52 // currently inline comments include the line break at the end, we need to
53 // strip those out and update the end location for each comment manually
54 ast.comments.forEach((comment) => {
55 if (comment.value[comment.value.length - 1] === "\r") {
56 comment.value = comment.value.slice(0, -1);
57 comment.loc.end.offset = comment.loc.end.offset - 1;
58 }
59 if (comment.value[comment.value.length - 1] === "\n") {
60 comment.value = comment.value.slice(0, -1);
61 comment.loc.end.offset = comment.loc.end.offset - 1;
62 }
63 });
64
65 return ast;
66}
67
68module.exports = parse;