tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

parser-helper.js (2189B)


      1 /* This Source Code Form is subject to the terms of the Mozilla Public
      2 * License, v. 2.0. If a copy of the MPL was not distributed with this
      3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
      4 "use strict";
      5 
      6 const DevToolsUtils = require("resource://devtools/shared/DevToolsUtils.js");
      7 const lazy = {};
      8 ChromeUtils.defineESModuleGetters(
      9  lazy,
     10  {
     11    Reflect: "resource://gre/modules/reflect.sys.mjs",
     12  },
     13  { global: "contextual" }
     14 );
     15 
     16 /**
     17 * Gets a collection of parser methods for a specified source.
     18 *
     19 * @param string source
     20 *        The source text content.
     21 * @param boolean logExceptions
     22 */
     23 function getSyntaxTrees(source, logExceptions) {
     24  // The source may not necessarily be JS, in which case we need to extract
     25  // all the scripts. Fastest/easiest way is with a regular expression.
     26  // Don't worry, the rules of using a <script> tag are really strict,
     27  // this will work.
     28  const regexp = /<script[^>]*?(?:>([^]*?)<\/script\s*>|\/>)/gim;
     29  const syntaxTrees = [];
     30  const scriptMatches = [];
     31  let scriptMatch;
     32 
     33  if (source.match(/^\s*</)) {
     34    // First non whitespace character is &lt, so most definitely HTML.
     35    while ((scriptMatch = regexp.exec(source))) {
     36      // Contents are captured at index 1 or nothing: Self-closing scripts
     37      // won't capture code content
     38      scriptMatches.push(scriptMatch[1] || "");
     39    }
     40  }
     41 
     42  // If there are no script matches, send the whole source directly to the
     43  // reflection API to generate the AST nodes.
     44  if (!scriptMatches.length) {
     45    // Reflect.parse throws when encounters a syntax error.
     46    try {
     47      syntaxTrees.push(lazy.Reflect.parse(source));
     48    } catch (e) {
     49      if (logExceptions) {
     50        DevToolsUtils.reportException("Parser:get", e);
     51      }
     52    }
     53  } else {
     54    // Generate the AST nodes for each script.
     55    for (const script of scriptMatches) {
     56      // Reflect.parse throws when encounters a syntax error.
     57      try {
     58        syntaxTrees.push(lazy.Reflect.parse(script));
     59      } catch (e) {
     60        if (logExceptions) {
     61          DevToolsUtils.reportException("Parser:get", e);
     62        }
     63      }
     64    }
     65  }
     66 
     67  return syntaxTrees;
     68 }
     69 
     70 exports.getSyntaxTrees = getSyntaxTrees;