DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Implementation

Mercurial (b6d82b1a6b02)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef frontend_BinASTParserPerTokenizer_h
#define frontend_BinASTParserPerTokenizer_h

/**
 * A Binary AST parser.
 *
 * At the time of this writing, this parser implements the grammar of ES5
 * and trusts its input (in particular, variable declarations).
 */

#include "mozilla/Maybe.h"

#include "frontend/BCEParserHandle.h"
#include "frontend/BinASTEnum.h"
#include "frontend/BinASTParserBase.h"
#include "frontend/BinASTToken.h"
#include "frontend/BinASTTokenReaderContext.h"
#include "frontend/BinASTTokenReaderMultipart.h"
#include "frontend/FullParseHandler.h"
#include "frontend/ParseContext.h"
#include "frontend/ParseNode.h"
#include "frontend/SharedContext.h"

#include "js/CompileOptions.h"
#include "js/GCHashTable.h"
#include "js/GCVector.h"
#include "js/Result.h"

#include "vm/ErrorReporting.h"

namespace js {
namespace frontend {

template <typename Tok>
class BinASTParser;

/**
 * The parser for a Binary AST.
 *
 * By design, this parser never needs to backtrack or look ahead. Errors are not
 * recoverable.
 */
template <typename Tok>
class BinASTParserPerTokenizer : public BinASTParserBase,
                                 public ErrorReporter,
                                 public BCEParserHandle {
 public:
  using Tokenizer = Tok;

  using AutoList = typename Tokenizer::AutoList;
  using AutoTaggedTuple = typename Tokenizer::AutoTaggedTuple;
  using BinASTFields = typename Tokenizer::BinASTFields;
  using Chars = typename Tokenizer::Chars;
  using RootContext = BinASTTokenReaderBase::RootContext;
  using Context = BinASTTokenReaderBase::Context;

 public:
  // Auto-generated types.
  using AssertedDeclaredKind = binast::AssertedDeclaredKind;
  using VariableDeclarationKind = binast::VariableDeclarationKind;

 public:
  BinASTParserPerTokenizer(JSContext* cx, LifoAlloc& alloc,
                           UsedNameTracker& usedNames,
                           const JS::ReadOnlyCompileOptions& options,
                           HandleScriptSourceObject sourceObject,
                           Handle<LazyScript*> lazyScript = nullptr);
  ~BinASTParserPerTokenizer() {}

  /**
   * Parse a buffer, returning a node (which may be nullptr) in case of success
   * or Nothing() in case of error.
   *
   * The instance of `ParseNode` MAY NOT survive the
   * `BinASTParserPerTokenizer`. Indeed, destruction of the
   * `BinASTParserPerTokenizer` will also destroy the `ParseNode`.
   *
   * In case of error, the parser reports the JS error.
   */
  JS::Result<ParseNode*> parse(GlobalSharedContext* globalsc,
                               const uint8_t* start, const size_t length,
                               BinASTSourceMetadata** metadataPtr = nullptr);
  JS::Result<ParseNode*> parse(GlobalSharedContext* globalsc,
                               const Vector<uint8_t>& data,
                               BinASTSourceMetadata** metadataPtr = nullptr);

  JS::Result<FunctionNode*> parseLazyFunction(ScriptSource* scriptSource,
                                              const size_t firstOffset);

 protected:
  MOZ_MUST_USE JS::Result<ParseNode*> parseAux(
      GlobalSharedContext* globalsc, const uint8_t* start, const size_t length,
      BinASTSourceMetadata** metadataPtr = nullptr);

  // --- Raise errors.
  //
  // These methods return a (failed) JS::Result for convenience.

  MOZ_MUST_USE mozilla::GenericErrorResult<JS::Error&> raiseInvalidClosedVar(
      JSAtom* name);
  MOZ_MUST_USE mozilla::GenericErrorResult<JS::Error&>
  raiseMissingVariableInAssertedScope(JSAtom* name);
  MOZ_MUST_USE mozilla::GenericErrorResult<JS::Error&>
  raiseMissingDirectEvalInAssertedScope();
  MOZ_MUST_USE mozilla::GenericErrorResult<JS::Error&> raiseInvalidKind(
      const char* superKind, const BinASTKind kind);
  MOZ_MUST_USE mozilla::GenericErrorResult<JS::Error&> raiseInvalidVariant(
      const char* kind, const BinASTVariant value);
  MOZ_MUST_USE mozilla::GenericErrorResult<JS::Error&> raiseMissingField(
      const char* kind, const BinASTField field);
  MOZ_MUST_USE mozilla::GenericErrorResult<JS::Error&> raiseEmpty(
      const char* description);
  MOZ_MUST_USE mozilla::GenericErrorResult<JS::Error&> raiseOOM();
  MOZ_MUST_USE mozilla::GenericErrorResult<JS::Error&> raiseError(
      const char* description);
  MOZ_MUST_USE mozilla::GenericErrorResult<JS::Error&> raiseError(
      BinASTKind kind, const char* description);

  // Ensure that this parser will never be used again.
  void poison();

  // The owner or the target of Asserted*Scope.
  enum class AssertedScopeKind {
    Block,
    Catch,
    Global,
    Parameter,
    Var,
  };

  // --- Auxiliary parsing functions

  // Build a function object for a function-producing production. Called AFTER
  // creating the scope.
  JS::Result<FunctionBox*> buildFunctionBox(GeneratorKind generatorKind,
                                            FunctionAsyncKind functionAsyncKind,
                                            FunctionSyntaxKind syntax,
                                            ParseNode* name);

  JS::Result<FunctionNode*> makeEmptyFunctionNode(const size_t start,
                                                  const BinASTKind kind,
                                                  FunctionBox* funbox);
  MOZ_MUST_USE JS::Result<Ok> setFunctionParametersAndBody(FunctionNode* fun,
                                                           ListNode* params,
                                                           ParseNode* body);

  MOZ_MUST_USE JS::Result<Ok> finishEagerFunction(FunctionBox* funbox,
                                                  uint32_t nargs);
  MOZ_MUST_USE JS::Result<Ok> finishLazyFunction(FunctionBox* funbox,
                                                 uint32_t nargs, size_t start,
                                                 size_t end);

  // Add name to a given scope.
  MOZ_MUST_USE JS::Result<Ok> addScopeName(
      AssertedScopeKind scopeKind, HandleAtom name, ParseContext::Scope* scope,
      DeclarationKind declKind, bool isCaptured, bool allowDuplicateName);

  void captureFunctionName();

  // Map AssertedScopeKind and AssertedDeclaredKind for single binding to
  // corresponding ParseContext::Scope to store the binding, and
  // DeclarationKind for the binding.
  MOZ_MUST_USE JS::Result<Ok> getDeclaredScope(AssertedScopeKind scopeKind,
                                               AssertedDeclaredKind kind,
                                               ParseContext::Scope*& scope,
                                               DeclarationKind& declKind);
  MOZ_MUST_USE JS::Result<Ok> getBoundScope(AssertedScopeKind scopeKind,
                                            ParseContext::Scope*& scope,
                                            DeclarationKind& declKind);

  MOZ_MUST_USE JS::Result<Ok> checkBinding(JSAtom* name);

  MOZ_MUST_USE JS::Result<Ok> checkPositionalParameterIndices(
      Handle<GCVector<JSAtom*>> positionalParams, ListNode* params);

  MOZ_MUST_USE JS::Result<Ok> checkFunctionLength(uint32_t expectedLength);

  // When leaving a scope, check that none of its bindings are known closed over
  // and un-marked.
  MOZ_MUST_USE JS::Result<Ok> checkClosedVars(ParseContext::Scope& scope);

  // As a convenience, a helper that checks the body, parameter, and recursive
  // binding scopes.
  MOZ_MUST_USE JS::Result<Ok> checkFunctionClosedVars();

  // --- Utilities.

  MOZ_MUST_USE JS::Result<Ok> prependDirectivesToBody(ListNode* body,
                                                      ListNode* directives);

  MOZ_MUST_USE JS::Result<Ok> prependDirectivesImpl(ListNode* body,
                                                    ParseNode* directive);

  // Optionally force a strict context without restarting the parse when we see
  // a strict directive.
  void forceStrictIfNecessary(SharedContext* sc, ListNode* directives);

 protected:
  // Implement ErrorReportMixin.
  const JS::ReadOnlyCompileOptions& options_;

  const JS::ReadOnlyCompileOptions& options() const override {
    return this->options_;
  }

  JSContext* getContext() const override { return cx_; };

  MOZ_MUST_USE bool strictMode() const override { return pc_->sc()->strict(); }

  MOZ_MUST_USE bool computeErrorMetadata(ErrorMetadata* err,
                                         const ErrorOffset& offset) override;

 private:
  void doTrace(JSTracer* trc) final;

 public:
  virtual ObjectBox* newObjectBox(JSObject* obj) override {
    MOZ_ASSERT(obj);

    /*
     * We use JSContext.tempLifoAlloc to allocate parsed objects and place them
     * on a list in this Parser to ensure GC safety. Thus the tempLifoAlloc
     * arenas containing the entries must be alive until we are done with
     * scanning, parsing and code generation for the whole script or top-level
     * function.
     */

    ObjectBox* objbox = alloc_.new_<ObjectBox>(obj, traceListHead_);
    if (!objbox) {
      ReportOutOfMemory(cx_);
      return nullptr;
    }

    traceListHead_ = objbox;

    return objbox;
  }

  virtual ErrorReporter& errorReporter() override { return *this; }
  virtual const ErrorReporter& errorReporter() const override { return *this; }

  virtual FullParseHandler& astGenerator() override { return handler_; }

 public:
  // Implement ErrorReporter.

  virtual void lineAndColumnAt(size_t offset, uint32_t* line,
                               uint32_t* column) const override {
    *line = lineAt(offset);
    *column = columnAt(offset);
  }
  virtual uint32_t lineAt(size_t offset) const override { return 0; }
  virtual uint32_t columnAt(size_t offset) const override { return offset; }

  virtual bool isOnThisLine(size_t offset, uint32_t lineNum,
                            bool* isOnSameLine) const override {
    if (lineNum != 0) {
      return false;
    }
    *isOnSameLine = true;
    return true;
  }

  virtual void currentLineAndColumn(uint32_t* line,
                                    uint32_t* column) const override {
    *line = 0;
    *column = offset();
  }
  size_t offset() const {
    if (tokenizer_.isSome()) {
      return tokenizer_->offset();
    }

    return 0;
  }
  virtual bool hasTokenizationStarted() const override {
    return tokenizer_.isSome();
  }
  virtual const char* getFilename() const override {
    return this->options_.filename();
  }

 protected:
  Rooted<LazyScript*> lazyScript_;
  FullParseHandler handler_;

  mozilla::Maybe<Tokenizer> tokenizer_;
  VariableDeclarationKind variableDeclarationKind_;

  FunctionTreeHolder treeHolder_;

  friend class BinASTParseContext;
  friend class AutoVariableDeclarationKind;

  // Helper class: Restore field `variableDeclarationKind` upon leaving a scope.
  class MOZ_RAII AutoVariableDeclarationKind {
   public:
    explicit AutoVariableDeclarationKind(
        BinASTParserPerTokenizer<Tok>* parser MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
        : parser_(parser), kind(parser->variableDeclarationKind_) {
      MOZ_GUARD_OBJECT_NOTIFIER_INIT;
    }
    ~AutoVariableDeclarationKind() { parser_->variableDeclarationKind_ = kind; }

   private:
    BinASTParserPerTokenizer<Tok>* parser_;
    BinASTParserPerTokenizer<Tok>::VariableDeclarationKind kind;
    MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
  };

 private:
  // Some methods in this class require access to auto-generated methods in
  // BinASTParser which derives this class.
  // asFinalParser methods provide the access to BinASTParser class methods
  // of this instance.
  using FinalParser = BinASTParser<Tok>;

  inline FinalParser* asFinalParser();
  inline const FinalParser* asFinalParser() const;
};

class BinASTParseContext : public ParseContext {
 public:
  template <typename Tok>
  BinASTParseContext(JSContext* cx, BinASTParserPerTokenizer<Tok>* parser,
                     SharedContext* sc, Directives* newDirectives)
      : ParseContext(cx, parser->pc_, sc, *parser, parser->usedNames_,
                     parser->treeHolder_, newDirectives,
                     /* isFull = */ true) {}
};

void TraceBinASTParser(JSTracer* trc, JS::AutoGCRooter* parser);

extern template class BinASTParserPerTokenizer<BinASTTokenReaderContext>;
extern template class BinASTParserPerTokenizer<BinASTTokenReaderMultipart>;

}  // namespace frontend
}  // namespace js

#endif  // frontend_BinASTParserPerTokenizer_h