text:
@interface KSCrashReportFilterJSON_Tests : XCTestCase @end

@implementation KSCrashReportFilterJSON_Tests

- (void) testFilterJSONEncode
{
    NSArray* decoded = [NSArray arrayWithObjects:
                        [NSArray arrayWithObjects:@"1", @"2", @"3", nil],
                        [NSArray arrayWithObjects:@"4", @"5", @"6", nil],
                        [NSArray arrayWithObjects:@"7", @"8", @"9", nil],
                        nil];
    NSArray* encoded = [NSArray arrayWithObjects:
                        [@"[\"1\",\"2\",\"3\"]" dataUsingEncoding:NSUTF8StringEncoding],
                        [@"[\"4\",\"5\",\"6\"]" dataUsingEncoding:NSUTF8StringEncoding],
                        [@"[\"7\",\"8\",\"9\"]" dataUsingEncoding:NSUTF8StringEncoding],
                        nil];

    id<KSCrashReportFilter> filter = [KSCrashReportFilterJSONEncode filterWithOptions:0];
    [filter filterReports:decoded onCompletion:^(NSArray* filteredReports,
                                                 BOOL completed,
                                                 NSError* error2)
     {
         XCTAssertTrue(completed, @"");
         XCTAssertNil(error2, @"");
         XCTAssertEqualObjects(encoded, filteredReports, @"");
     }];
}

- (void) testFilterJSONEncodeInvalid
{
    NSArray* decoded = [NSArray arrayWithObjects:
                        [NSException exceptionWithName:@"" reason:@"" userInfo:nil],
                        nil];

    id<KSCrashReportFilter> filter = [KSCrashReportFilterJSONEncode filterWithOptions:0];
    [filter filterReports:decoded onCompletion:^(__unused NSArray* filteredReports,
                                                 BOOL completed,
                                                 NSError* error2)
     {
         XCTAssertFalse(completed, @"");
         XCTAssertNotNil(error2, @"");
     }];
}

- (void) testFilterJSONDencode
{
    NSArray* decoded = [NSArray arrayWithObjects:
                        [NSArray arrayWithObjects:@"1", @"2", @"3", nil],
                        [NSArray arrayWithObjects:@"4", @"5", @"6", nil],
                        [NSArray arrayWithObjects:@"7", @"8", @"9", nil],
                        nil];
    NSArray* encoded = [NSArray arrayWithObjects:
                        [@"[\"1\",\"2\",\"3\"]" dataUsingEncoding:NSUTF8StringEncoding],
                        [@"[\"4\",\"5\",\"6\"]" dataUsingEncoding:NSUTF8StringEncoding],
                        [@"[\"7\",\"8\",\"9\"]" dataUsingEncoding:NSUTF8StringEncoding],
                        nil];

    id<KSCrashReportFilter> filter = [KSCrashReportFilterJSONDecode filterWithOptions:0];
    [filter filterReports:encoded onCompletion:^(NSArray* filteredReports,
                                                 BOOL completed,
                                                 NSError* error2)
     {
         XCTAssertTrue(completed, @"");
         XCTAssertNil(error2, @"");
         XCTAssertEqualObjects(decoded, filteredReports, @"");
     }];
}

- (void) testFilterJSONDencodeInvalid
{
    NSArray* encoded = [NSArray arrayWithObjects:
                        [@"[\"1\"\",\"2\",\"3\"]" dataUsingEncoding:NSUTF8StringEncoding],
                        nil];

    id<KSCrashReportFilter> filter = [KSCrashReportFilterJSONDecode filterWithOptions:0];
    [filter filterReports:encoded onCompletion:^(__unused NSArray* filteredReports,
                                                 BOOL completed,
                                                 NSError* error2)
     {
         XCTAssertFalse(completed, @"");
         XCTAssertNotNil(error2, @"");
     }];
}

@end


text:
namespace System.Xml
{

using System;
using System.Text;

#if ECMA_COMPAT
internal
#else
public
#endif
class XmlCDataSection : XmlCharacterData
{
	// Constructor.
	internal XmlCDataSection(XmlNode parent, String data)
			: base(parent, data)
			{
				// Nothing to do here.
			}
	protected internal XmlCDataSection(String data, XmlDocument doc)
			: base(data, doc)
			{
				// Nothing to do here.
			}

	// Get the local name of this node.
	public override String LocalName
			{
				get
				{
					return "#cdata-section";
				}
			}

	// Get the qualified name of this node.
	public override String Name
			{
				get
				{
					return "#cdata-section";
				}
			}

	// Get the node type.
	public override XmlNodeType NodeType
			{
				get
				{
					return XmlNodeType.CDATA;
				}
			}

	// Clone this node.
	public override XmlNode CloneNode(bool deep)
			{
				return OwnerDocument.CreateCDataSection(Data);
			}

	// Writes the contents of this node to a specified XmlWriter.
	public override void WriteContentTo(XmlWriter w)
			{
				// Nothing needs to be done here for CDATA nodes.
			}

	// Write this node and all of its contents to a specified XmlWriter.
	public override void WriteTo(XmlWriter w)
			{
				w.WriteCData(Data);
			}

}; // class XmlCDataSection

}; // namespace System.Xml

redpajama_set_name: RedPajamaGithub


text:
//===--- Parser.h - Swift Language Parser -----------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file defines the Parser interface.
//
//===----------------------------------------------------------------------===//

#ifndef SWIFT_PARSER_H
#define SWIFT_PARSER_H

#include "swift/AST/AST.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/LocalContext.h"
#include "swift/Parse/PersistentParserState.h"
#include "swift/Parse/Token.h"
#include "swift/Parse/ParserResult.h"
#include "swift/Basic/OptionSet.h"
#include "swift/Config.h"
#include "llvm/ADT/SetVector.h"

namespace llvm {
  template <typename PT1, typename PT2, typename PT3> class PointerUnion3;
}

namespace swift {
  class DiagnosticEngine;
  class Lexer;
  class ScopeInfo;
  struct TypeLoc;
  class TupleType;
  class SILParserState;
  class SourceManager;
  class PersistentParserState;
  class CodeCompletionCallbacks;
  class DelayedParsingCallbacks;

  struct EnumElementInfo;

  /// Different contexts in which BraceItemList are parsed.
  enum class BraceItemListKind {
    /// A statement list terminated by a closing brace. The default.
    Brace,
    /// A statement list in a case block. The list is terminated
    /// by a closing brace or a 'case' or 'default' label.
    Case,
    /// The top-level of a file, when not in parse-as-library mode (i.e. the
    /// repl or a script).
    TopLevelCode,
    /// The top-level of a file, when in parse-as-library mode.
    TopLevelLibrary,
    /// The body of the inactive clause of an #if/#else/#endif block
    InactiveConditionalBlock,
    /// The body of the active clause of an #if/#else/#endif block
    ActiveConditionalBlock
  };

class Parser {
  Parser(const Parser&) = delete;
  void operator=(const Parser&) = delete;

  bool IsInputIncomplete = false;
  SourceLoc DelayedDeclEnd;
  std::vector<Token> SplitTokens;

public:
  SourceManager &SourceMgr;
  DiagnosticEngine &Diags;
  SourceFile &SF;
  Lexer *L;
  SILParserState *SIL;    // Non-null when parsing a .sil file.
  PersistentParserState *State;
  std::unique_ptr<PersistentParserState> OwnedState;
  DeclContext *CurDeclContext;
  ASTContext &Context;
  CodeCompletionCallbacks *CodeCompletion = nullptr;
  std::vector<std::pair<SourceLoc, std::vector<ParamDecl*>>> AnonClosureVars;

  bool IsParsingInterfaceTokens = false;

  /// DisabledVars is a list of variables for whom local name lookup is
  /// disabled.  This is used when parsing a PatternBindingDecl to reject self
  /// uses and to disable uses of the bound variables in a let/else block.  The
  /// diagnostic to emit is stored in DisabledVarReason.
  ArrayRef<VarDecl *> DisabledVars;
  Diag<> DisabledVarReason;

  llvm::SmallPtrSet<Decl *, 2> AlreadyHandledDecls;
  enum {
    /// InVarOrLetPattern has this value when not parsing a pattern.
    IVOLP_NotInVarOrLet,

    /// InVarOrLetPattern has this value when we're in a matching pattern, but
    /// not within a var/let pattern.  In this phase, identifiers are references
    /// to the enclosing scopes, not a variable binding.
    IVOLP_InMatchingPattern,

    /// InVarOrLetPattern has this value when parsing a pattern in which bound
    /// variables are implicitly immutable, but allowed to be marked mutable by
    /// using a 'var' pattern.  This happens in for-each loop patterns.
    IVOLP_ImplicitlyImmutable,

    /// When InVarOrLetPattern has this value, bound variables are mutable, and
    /// nested let/var patterns are not permitted. This happens when parsing a
    /// 'var' decl or when parsing inside a 'var' pattern.
    IVOLP_InVar,

    /// When InVarOrLetPattern has this value, bound variables are immutable,and
    /// nested let/var patterns are not permitted. This happens when parsing a
    /// 'let' decl or when parsing inside a 'let' pattern.
    IVOLP_InLet
  } InVarOrLetPattern = IVOLP_NotInVarOrLet;

  bool InPoundLineEnvironment = false;

  LocalContext *CurLocalContext = nullptr;

  DelayedParsingCallbacks *DelayedParseCB = nullptr;

  bool isDelayedParsingEnabled() const { return DelayedParseCB != nullptr; }

  void setDelayedParsingCallbacks(DelayedParsingCallbacks *DelayedParseCB) {
    this->DelayedParseCB = DelayedParseCB;
  }

  void setCodeCompletionCallbacks(CodeCompletionCallbacks *Callbacks) {
    CodeCompletion = Callbacks;
  }

  bool isCodeCompletionFirstPass() {
    return L->isCodeCompletion() && !CodeCompletion;
  }

  bool allowTopLevelCode() const {
    return SF.isScriptMode();
  }

  const std::vector<Token> &getSplitTokens() { return SplitTokens; }

  void markSplitToken(tok Kind, StringRef Txt);

  /// Returns true if the parser reached EOF with incomplete source input, due
  /// for example, a missing right brace.
  bool isInputIncomplete() const { return IsInputIncomplete; }

  void checkForInputIncomplete() {
    IsInputIncomplete = IsInputIncomplete || Tok.is(tok::eof);
  }

  /// \brief This is the current token being considered by the parser.
  Token Tok;

  /// \brief The location of the previous token.
  SourceLoc PreviousLoc;

  /// A RAII object for temporarily changing CurDeclContext.
  class ContextChange {
  protected:
    Parser &P;
    DeclContext *OldContext; // null signals that this has been popped
    LocalContext *OldLocal;

    ContextChange(const ContextChange &) = delete;
    ContextChange &operator=(const ContextChange &) = delete;

  public:
    ContextChange(Parser &P, DeclContext *DC,
                  LocalContext *newLocal = nullptr)
      : P(P), OldContext(P.CurDeclContext), OldLocal(P.CurLocalContext) {
      assert(DC && "pushing null context?");
      P.CurDeclContext = DC;
      P.CurLocalContext = newLocal;
    }

    /// Prematurely pop the DeclContext installed by the constructor.
    /// Makes the destructor a no-op.
    void pop() {
      assert(OldContext && "already popped context!");
      popImpl();
      OldContext = nullptr;
    }

    ~ContextChange() {
      if (OldContext) popImpl();
    }

  private:
    void popImpl() {
      P.CurDeclContext = OldContext;
      P.CurLocalContext = OldLocal;
    }
  };

  /// A RAII object for parsing a new local context.
  class ParseFunctionBody : public LocalContext {
  private:
    ContextChange CC;
  public:
    ParseFunctionBody(Parser &P, DeclContext *DC) : CC(P, DC, this) {
      assert(!isa<TopLevelCodeDecl>(DC) &&
             "top-level code should be parsed using TopLevelCodeContext!");
    }

    void pop() {
      CC.pop();
    }
  };

  /// Describes the kind of a lexical structure marker, indicating
  /// what kind of structural element we started parsing at a
  /// particular location.
  enum class StructureMarkerKind : unsigned char {
    /// The start of a declaration.
    Declaration,
    /// The start of a statement.
    Statement,
    /// An open parentheses.
    OpenParen,
    /// An open brace.
    OpenBrace,
    /// An open square bracket.
    OpenSquare,
    /// An #if conditional clause.
    IfConfig,
  };

  /// A structure marker, which identifies the location at which the
  /// parser saw an entity it is parsing.
  struct StructureMarker {
    /// The location at which the marker occurred.
    SourceLoc Loc;

    /// The kind of marker.
    StructureMarkerKind Kind;

    /// The leading whitespace for this marker, if it has already been
    /// computed.
    Optional<StringRef> LeadingWhitespace;
  };

  /// An RAII object that notes when we have seen a structure marker.
  class StructureMarkerRAII {
    Parser &P;

  public:
    StructureMarkerRAII(Parser &parser, SourceLoc loc,
                               StructureMarkerKind kind)
      : P(parser) {
      P.StructureMarkers.push_back({loc, kind, None});
    }

    StructureMarkerRAII(Parser &parser, const Token &tok);

    ~StructureMarkerRAII() {
      P.StructureMarkers.pop_back();
    }
  };
  friend class StructureMarkerRAII;

  /// The stack of structure markers indicating the locations of
  /// structural elements actively being parsed, including the start
  /// of declarations, statements, and opening operators of various
  /// kinds.
  ///
  /// This vector is managed by \c StructureMarkerRAII objects.
  llvm::SmallVector<StructureMarker, 16> StructureMarkers;

public:
  Parser(unsigned BufferID, SourceFile &SF, SILParserState *SIL,
         PersistentParserState *PersistentState = nullptr);
  Parser(std::unique_ptr<Lexer> Lex, SourceFile &SF,
         SILParserState *SIL = nullptr,
         PersistentParserState *PersistentState = nullptr);
  ~Parser();

  bool isInSILMode() const { return SIL != nullptr; }

  //===--------------------------------------------------------------------===//
  // Routines to save and restore parser state.

  class ParserPosition {
  public:
    ParserPosition() = default;
    ParserPosition &operator=(const ParserPosition &) = default;

    bool isValid() const {
      return LS.isValid();
    }

  private:
    ParserPosition(Lexer::State LS, SourceLoc PreviousLoc):
        LS(LS), PreviousLoc(PreviousLoc)
    {}
    Lexer::State LS;
    SourceLoc PreviousLoc;
    friend class Parser;
  };

  ParserPosition getParserPosition() {
    return ParserPosition(L->getStateForBeginningOfToken(Tok),
                          PreviousLoc);
  }

  ParserPosition getParserPosition(const PersistentParserState::ParserPos &Pos){
    return ParserPosition(L->getStateForBeginningOfTokenLoc(Pos.Loc),
                          Pos.PrevLoc);
  }

  /// \brief Return parser position after the first character of token T
  ParserPosition getParserPositionAfterFirstCharacter(Token T);

  void restoreParserPosition(ParserPosition PP) {
    L->restoreState(PP.LS);

    // We might be at tok::eof now, so ensure that consumeToken() does not
    // assert about lexing past eof.
    Tok.setKind(tok::unknown);
    consumeToken();

    PreviousLoc = PP.PreviousLoc;
  }

  void backtrackToPosition(ParserPosition PP) {
    assert(PP.isValid());

    L->backtrackToState(PP.LS);

    // We might be at tok::eof now, so ensure that consumeToken() does not
    // assert about lexing past eof.
    Tok.setKind(tok::unknown);
    consumeToken();

    PreviousLoc = PP.PreviousLoc;
  }

  /// RAII object that, when it is destructed, restores the parser and lexer to
  /// their positions at the time the object was constructed.  Will not jump
  /// forward in the token stream.
  class BacktrackingScope {
    Parser &P;
    ParserPosition PP;
    bool Backtrack = true;

  public:
    BacktrackingScope(Parser &P) : P(P), PP(P.getParserPosition()) {}

    ~BacktrackingScope() {
      if (Backtrack)
        P.backtrackToPosition(PP);
    }

    void cancelBacktrack() { Backtrack = false; }
  };

  /// RAII object that, when it is destructed, restores the parser and lexer to
  /// their positions at the time the object was constructed.
  struct ParserPositionRAII {
  private:
    Parser &P;
    ParserPosition PP;

  public:
    ParserPositionRAII(Parser &P) : P(P), PP(P.getParserPosition()) {}

    ~ParserPositionRAII() {
      P.restoreParserPosition(PP);
    }
  };

  //===--------------------------------------------------------------------===//
  // Utilities

  /// \brief Return the next token that will be installed by \c consumeToken.
  const Token &peekToken();

  SourceLoc consumeToken();
  SourceLoc consumeToken(tok K) {
    assert(Tok.is(K) && "Consuming wrong token kind");
    return consumeToken();
  }

  SourceLoc consumeIdentifier(Identifier *Result = nullptr) {
    assert(Tok.isAny(tok::identifier, tok::kw_self, tok::kw_Self, tok::kw_throws));
    if (Result)
      *Result = Context.getIdentifier(Tok.getText());
    return consumeToken();
  }

  /// \brief Retrieve the location just past the end of the previous
  /// source location.
  SourceLoc getEndOfPreviousLoc();

  /// \brief If the current token is the specified kind, consume it and
  /// return true.  Otherwise, return false without consuming it.
  bool consumeIf(tok K) {
    if (Tok.isNot(K)) return false;
    consumeToken(K);
    return true;
  }

  /// \brief If the current token is the specified kind, consume it and
  /// return true.  Otherwise, return false without consuming it.
  bool consumeIf(tok K, SourceLoc &consumedLoc) {
    if (Tok.isNot(K)) return false;
    consumedLoc = consumeToken(K);
    return true;
  }

  bool consumeIfNotAtStartOfLine(tok K) {
    if (Tok.isAtStartOfLine()) return false;
    return consumeIf(K);
  }

  /// \brief Read tokens until we get to one of the specified tokens, then
  /// return without consuming it.  Because we cannot guarantee that the token
  /// will ever occur, this skips to some likely good stopping point.
  void skipUntil(tok T1, tok T2 = tok::unknown);
  void skipUntilAnyOperator();

  /// \brief Skip until a token that starts with '>', and consume it if found.
  /// Applies heuristics that are suitable when trying to find the end of a list
  /// of generic parameters, generic arguments, or list of types in a protocol
  /// composition.
  SourceLoc skipUntilGreaterInTypeList(bool protocolComposition = false);

  /// skipUntilDeclStmtRBrace - Skip to the next decl or '}'.
  void skipUntilDeclRBrace();

  void skipUntilDeclStmtRBrace(tok T1);

  /// \brief Skip to the next decl, statement or '}'.
  void skipUntilDeclStmtRBrace() {
    skipUntilDeclStmtRBrace(tok::unknown);
  }

  void skipUntilDeclRBrace(tok T1, tok T2 = tok::unknown);

  /// Skip a single token, but match parentheses, braces, and square brackets.
  ///
  /// Note: this does \em not match angle brackets ("<" and ">")! These are
  /// matched in the source when they refer to a generic type,
  /// but not when used as comparison operators.
  void skipSingle();

  /// \brief Skip until the next '#else', '#endif' or until eof.
  void skipUntilConditionalBlockClose();

  /// Parse an #endif.
  bool parseEndIfDirective(SourceLoc &Loc);

public:
  InFlightDiagnostic diagnose(SourceLoc Loc, Diagnostic Diag) {
    if (Diags.isDiagnosticPointsToFirstBadToken(Diag.getID()) &&
        Loc == Tok.getLoc() && Tok.isAtStartOfLine())
      Loc = getEndOfPreviousLoc();
    return Diags.diagnose(Loc, Diag);
  }

  InFlightDiagnostic diagnose(Token Tok, Diagnostic Diag) {
    return diagnose(Tok.getLoc(), Diag);
  }

  template<typename ...DiagArgTypes, typename ...ArgTypes>
  InFlightDiagnostic diagnose(SourceLoc Loc, Diag<DiagArgTypes...> DiagID,
                              ArgTypes &&...Args) {
    return diagnose(Loc, Diagnostic(DiagID, std::forward<ArgTypes>(Args)...));
  }

  template<typename ...DiagArgTypes, typename ...ArgTypes>
  InFlightDiagnostic diagnose(Token Tok, Diag<DiagArgTypes...> DiagID,
                              ArgTypes &&...Args) {
    return diagnose(Tok.getLoc(),
                    Diagnostic(DiagID, std::forward<ArgTypes>(Args)...));
  }

  void diagnoseRedefinition(ValueDecl *Prev, ValueDecl *New);

  /// \brief Check whether the current token starts with '<'.
  bool startsWithLess(Token Tok) {
    return Tok.isAnyOperator() && Tok.getText()[0] == '<';
  }

  /// \brief Check whether the current token starts with '>'.
  bool startsWithGreater(Token Tok) {
    return Tok.isAnyOperator() && Tok.getText()[0] == '>';
  }

  /// \brief Consume the starting '<' of the current token, which may either
  /// be a complete '<' token or some kind of operator token starting with '<',
  /// e.g., '<>'.
  SourceLoc consumeStartingLess();

  /// \brief Consume the starting '>' of the current token, which may either
  /// be a complete '>' token or some kind of operator token starting with '>',
  /// e.g., '>>'.
  SourceLoc consumeStartingGreater();

  /// \brief Consume the starting character of the current token, and split the
  /// remainder of the token into a new token (or tokens).
  SourceLoc consumeStartingCharacterOfCurrentToken();

  swift::ScopeInfo &getScopeInfo() { return State->getScopeInfo(); }

  /// \brief Add the given Decl to the current scope.
  void addToScope(ValueDecl *D) {
    getScopeInfo().addToScope(D, *this);
  }

  ValueDecl *lookupInScope(DeclName Name) {
    if (Context.LangOpts.EnableASTScopeLookup)
      return nullptr;

    return getScopeInfo().lookupValueName(Name);
  }

  //===--------------------------------------------------------------------===//
  // Primitive Parsing

  /// \brief Consume an identifier (but not an operator) if present and return
  /// its name in \p Result.  Otherwise, emit an error.
  ///
  /// \returns false on success, true on error.
  bool parseIdentifier(Identifier &Result, SourceLoc &Loc, const Diagnostic &D);

  /// Consume an identifier with a specific expected name.  This is useful for
  /// contextually sensitive keywords that must always be present.
  bool parseSpecificIdentifier(StringRef expected, SourceLoc &Loc,
                               const Diagnostic &D);

  template<typename ...DiagArgTypes, typename ...ArgTypes>
  bool parseIdentifier(Identifier &Result, Diag<DiagArgTypes...> ID,
                       ArgTypes... Args) {
    SourceLoc L;
    return parseIdentifier(Result, L, Diagnostic(ID, Args...));
  }

  template<typename ...DiagArgTypes, typename ...ArgTypes>
  bool parseIdentifier(Identifier &Result, SourceLoc &L,
                       Diag<DiagArgTypes...> ID, ArgTypes... Args) {
    return parseIdentifier(Result, L, Diagnostic(ID, Args...));
  }

  template<typename ...DiagArgTypes, typename ...ArgTypes>
  bool parseSpecificIdentifier(StringRef expected,
                               Diag<DiagArgTypes...> ID, ArgTypes... Args) {
    SourceLoc L;
    return parseSpecificIdentifier(expected, L, Diagnostic(ID, Args...));
  }

  /// \brief Consume an identifier or operator if present and return its name
  /// in \p Result.  Otherwise, emit an error and return true.
  bool parseAnyIdentifier(Identifier &Result, SourceLoc &Loc,
                          const Diagnostic &D);

  template<typename ...DiagArgTypes, typename ...ArgTypes>
  bool parseAnyIdentifier(Identifier &Result, Diag<DiagArgTypes...> ID,
                          ArgTypes... Args) {
    SourceLoc L;
    return parseAnyIdentifier(Result, L, Diagnostic(ID, Args...));
  }

  template<typename ...DiagArgTypes, typename ...ArgTypes>
  bool parseAnyIdentifier(Identifier &Result, SourceLoc &L,
                          Diag<DiagArgTypes...> ID, ArgTypes... Args) {
    return parseAnyIdentifier(Result, L, Diagnostic(ID, Args...));
  }

  /// \brief The parser expects that \p K is next token in the input.  If so,
  /// it is consumed and false is returned.
  ///
  /// If the input is malformed, this emits the specified error diagnostic.
  bool parseToken(tok K, SourceLoc &TokLoc, const Diagnostic &D);

  template<typename ...DiagArgTypes, typename ...ArgTypes>
  bool parseToken(tok K, Diag<DiagArgTypes...> ID, ArgTypes... Args) {
    SourceLoc L;
    return parseToken(K, L, Diagnostic(ID, Args...));
  }
  template<typename ...DiagArgTypes, typename ...ArgTypes>
  bool parseToken(tok K, SourceLoc &L,
                  Diag<DiagArgTypes...> ID, ArgTypes... Args) {
    return parseToken(K, L, Diagnostic(ID, Args...));
  }

  /// \brief Parse the specified expected token and return its location
  /// on success.  On failure, emit the specified error diagnostic, and
  /// a note at the specified note location.
  bool parseMatchingToken(tok K, SourceLoc &TokLoc, Diag<> ErrorDiag,
                          SourceLoc OtherLoc);

  /// \brief Parse the list of statements, expressions, or declarations.
  ParserStatus parseList(tok RightK, SourceLoc LeftLoc, SourceLoc &RightLoc,
                         tok SeparatorK, bool OptionalSep,
                         bool AllowSepAfterLast, Diag<> ErrorDiag,
                         std::function<ParserStatus()> callback);

  void consumeTopLevelDecl(ParserPosition BeginParserPosition,
                           TopLevelCodeDecl *TLCD);

  ParserStatus parseBraceItems(SmallVectorImpl<ASTNode> &Decls,
                               BraceItemListKind Kind =
                                   BraceItemListKind::Brace,
                               BraceItemListKind ConditionalBlockKind =
                                   BraceItemListKind::Brace);
  ParserResult<BraceStmt> parseBraceItemList(Diag<> ID);

  void parseIfConfigClauseElements(bool isActive,
                                   BraceItemListKind Kind,
                                   SmallVectorImpl<ASTNode> &Elements);

  void parseTopLevelCodeDeclDelayed();

  //===--------------------------------------------------------------------===//
  // Decl Parsing

  /// Return true if parser is at the start of a decl or decl-import.
  bool isStartOfDecl();

  bool parseTopLevel();

  /// Flags that control the parsing of declarations.
  enum ParseDeclFlags {
    PD_Default              = 0,
    PD_AllowTopLevel        = 1 << 1,
    PD_HasContainerType     = 1 << 2,
    PD_DisallowInit         = 1 << 3,
    PD_AllowDestructor      = 1 << 4,
    PD_AllowEnumElement     = 1 << 5,
    PD_InProtocol           = 1 << 6,
    PD_InClass              = 1 << 7,
    PD_InExtension          = 1 << 8,
    PD_InStruct             = 1 << 9,
    PD_InEnum               = 1 << 10,
    PD_InLoop               = 1 << 11
  };

  /// Options that control the parsing of declarations.
  typedef OptionSet<ParseDeclFlags> ParseDeclOptions;

  /// Skips the current token if it is '}', and emits a diagnostic.
  ///
  /// \returns true if any tokens were skipped.
  bool skipExtraTopLevelRBraces();

  void delayParseFromBeginningToHere(ParserPosition BeginParserPosition,
                                     ParseDeclOptions Flags);
  void consumeDecl(ParserPosition BeginParserPosition, ParseDeclOptions Flags,
                   bool IsTopLevel);

  // When compiling for the Debugger, some Decl's need to be moved from the
  // current scope.  In which case although the Decl will be returned in the
  // ParserResult, it should not be inserted into the Decl list for the current
  // context.  markWasHandled asserts that the Decl is already where it
  // belongs, and declWasHandledAlready is used to check this assertion.
  // To keep the handled decl array small, we remove the Decl when it is
  // checked, so you can only call declWasAlreadyHandled once for a given
  // decl.

  void markWasHandled(Decl *D) {
    AlreadyHandledDecls.insert(D);
  }

  bool declWasHandledAlready(Decl *D) {
    return AlreadyHandledDecls.erase(D);
  }

  ParserStatus parseDecl(ParseDeclOptions Flags,
                         llvm::function_ref<void(Decl*)> Handler);

  void parseDeclDelayed();

  ParserResult<TypeDecl> parseDeclTypeAlias(ParseDeclOptions Flags,
                                            DeclAttributes &Attributes);

  ParserResult<TypeDecl> parseDeclAssociatedType(ParseDeclOptions Flags,
                                                 DeclAttributes &Attributes);

  ParserResult<IfConfigDecl> parseDeclIfConfig(ParseDeclOptions Flags);
  /// Parse a #line/#sourceLocation directive.
  /// 'isLine = true' indicates parsing #line instead of #sourcelocation
  ParserStatus parseLineDirective(bool isLine = false);

  void setLocalDiscriminator(ValueDecl *D);

  /// Parse the optional attributes before a declaration.
  bool parseDeclAttributeList(DeclAttributes &Attributes,
                              bool &FoundCodeCompletionToken,
                              bool StopAtTypeAttributes = false,
                              bool InParam = false);

  /// Parse a specific attribute.
  bool parseDeclAttribute(DeclAttributes &Attributes, SourceLoc AtLoc);

  bool parseNewDeclAttribute(DeclAttributes &Attributes, SourceLoc AtLoc,
                             DeclAttrKind DK);

  /// Parse a version tuple of the form x[.y[.z]]. Returns true if there was
  /// an error parsing.
  bool parseVersionTuple(clang::VersionTuple &Version, SourceRange &Range,
                         const Diagnostic &D);

  bool parseTypeAttributeList(TypeAttributes &Attributes) {
    if (Tok.is(tok::at_sign))
      return parseTypeAttributeListPresent(Attributes);
    return false;
  }
  bool parseTypeAttributeListPresent(TypeAttributes &Attributes);
  bool parseTypeAttribute(TypeAttributes &Attributes,
                          bool justChecking = false);

  ParserResult<ImportDecl> parseDeclImport(ParseDeclOptions Flags,
                                           DeclAttributes &Attributes);
  ParserStatus parseInheritance(SmallVectorImpl<TypeLoc> &Inherited,
                                SourceLoc *classRequirementLoc);
  ParserResult<ExtensionDecl> parseDeclExtension(ParseDeclOptions Flags,
                                                 DeclAttributes &Attributes);
  ParserResult<EnumDecl> parseDeclEnum(ParseDeclOptions Flags,
                                       DeclAttributes &Attributes);
  ParserStatus parseDeclEnumCase(ParseDeclOptions Flags, DeclAttributes &Attributes,
                                 SmallVectorImpl<Decl *> &decls);
  bool parseNominalDeclMembers(SourceLoc LBLoc, SourceLoc &RBLoc,
                               Diag<> ErrorDiag, ParseDeclOptions flags,
                               llvm::function_ref<void(Decl*)> handler);
  ParserResult<StructDecl>
  parseDeclStruct(ParseDeclOptions Flags, DeclAttributes &Attributes);
  ParserResult<ClassDecl>
  parseDeclClass(SourceLoc ClassLoc,
                 ParseDeclOptions Flags, DeclAttributes &Attributes);
  ParserStatus parseDeclVar(ParseDeclOptions Flags, DeclAttributes &Attributes,
                            SmallVectorImpl<Decl *> &Decls,
                            SourceLoc StaticLoc,
                            StaticSpellingKind StaticSpelling,
                            SourceLoc TryLoc);

  void consumeGetSetBody(AbstractFunctionDecl *AFD, SourceLoc LBLoc);

  struct ParsedAccessors {
    SourceLoc LBLoc, RBLoc;
    FuncDecl *Get = nullptr;
    FuncDecl *Set = nullptr;
    FuncDecl *Addressor = nullptr;
    FuncDecl *MutableAddressor = nullptr;
    FuncDecl *WillSet = nullptr;
    FuncDecl *DidSet = nullptr;

    void record(Parser &P, AbstractStorageDecl *storage, bool invalid,
                ParseDeclOptions flags, SourceLoc staticLoc,
                const DeclAttributes &attrs,
                TypeLoc elementTy, ParameterList *indices,
                SmallVectorImpl<Decl *> &decls);
  };

  bool parseGetSetImpl(ParseDeclOptions Flags,
                       ParameterList *Indices, TypeLoc ElementTy,
                       ParsedAccessors &accessors,
                       SourceLoc &LastValidLoc,
                       SourceLoc StaticLoc, SourceLoc VarLBLoc,
                       SmallVectorImpl<Decl *> &Decls);
  bool parseGetSet(ParseDeclOptions Flags,
                   ParameterList *Indices, TypeLoc ElementTy,
                   ParsedAccessors &accessors,
                   SourceLoc StaticLoc, SmallVectorImpl<Decl *> &Decls);
  void recordAccessors(AbstractStorageDecl *storage, ParseDeclOptions flags,
                       TypeLoc elementTy, const DeclAttributes &attrs,
                       SourceLoc staticLoc, ParsedAccessors &accessors);
  void parseAccessorBodyDelayed(AbstractFunctionDecl *AFD);
  VarDecl *parseDeclVarGetSet(Pattern *pattern, ParseDeclOptions Flags,
                              SourceLoc StaticLoc, bool hasInitializer,
                              const DeclAttributes &Attributes,
                              SmallVectorImpl<Decl *> &Decls);

  void consumeAbstractFunctionBody(AbstractFunctionDecl *AFD,
                                   const DeclAttributes &Attrs);
  ParserResult<FuncDecl> parseDeclFunc(SourceLoc StaticLoc,
                                       StaticSpellingKind StaticSpelling,
                                       ParseDeclOptions Flags,
                                       DeclAttributes &Attributes);
  bool parseAbstractFunctionBodyDelayed(AbstractFunctionDecl *AFD);
  ParserResult<ProtocolDecl> parseDeclProtocol(ParseDeclOptions Flags,
                                               DeclAttributes &Attributes);

  ParserStatus parseDeclSubscript(ParseDeclOptions Flags,
                                  DeclAttributes &Attributes,
                                  SmallVectorImpl<Decl *> &Decls);

  ParserResult<ConstructorDecl>
  parseDeclInit(ParseDeclOptions Flags, DeclAttributes &Attributes);
  ParserResult<DestructorDecl>
  parseDeclDeinit(ParseDeclOptions Flags, DeclAttributes &Attributes);

  void addPatternVariablesToScope(ArrayRef<Pattern *> Patterns);
  void addParametersToScope(ParameterList *PL);

  ParserResult<OperatorDecl> parseDeclOperator(ParseDeclOptions Flags,
                                               DeclAttributes &Attributes);
  ParserResult<OperatorDecl> parseDeclOperatorImpl(SourceLoc OperatorLoc,
                                                   Identifier Name,
                                                   SourceLoc NameLoc,
                                                   DeclAttributes &Attrs);

  ParserResult<PrecedenceGroupDecl>
  parseDeclPrecedenceGroup(ParseDeclOptions flags, DeclAttributes &attributes);

  //===--------------------------------------------------------------------===//
  // SIL Parsing.

  bool parseDeclSIL();
  bool parseDeclSILStage();
  bool parseSILVTable();
  bool parseSILGlobal();
  bool parseSILWitnessTable();
  bool parseSILDefaultWitnessTable();
  bool parseSILCoverageMap();
  bool parseSILScope();

  //===--------------------------------------------------------------------===//
  // Type Parsing

  ParserResult<TypeRepr> parseType();
  ParserResult<TypeRepr> parseType(Diag<> MessageID,
                                   bool HandleCodeCompletion = true);

  /// \brief Parse any type, but diagnose all types except type-identifier.
  ///
  /// In some places the grammar allows type-identifier, but when it is not
  /// ambiguous, we want to parse any type for recovery purposes.
  ///
  /// \param MessageID a generic diagnostic for a syntax error in the type
  /// \param NonIdentifierTypeMessageID a diagnostic for a non-identifier type
  ///
  /// \returns null, IdentTypeRepr or ErrorTypeRepr.
  ParserResult<TypeRepr>
  parseTypeIdentifierWithRecovery(Diag<> MessageID,
                                  Diag<TypeLoc> NonIdentifierTypeMessageID);

  ParserResult<TypeRepr> parseTypeSimple();
  ParserResult<TypeRepr> parseTypeSimple(Diag<> MessageID,
                                         bool HandleCodeCompletion = true);
  bool parseGenericArguments(SmallVectorImpl<TypeRepr*> &Args,
                             SourceLoc &LAngleLoc,
                             SourceLoc &RAngleLoc);

  ParserResult<TypeRepr> parseTypeIdentifier();
  ParserResult<TypeRepr> parseTypeIdentifierOrTypeComposition();
  ParserResult<ProtocolCompositionTypeRepr> parseAnyType();

  ParserResult<TupleTypeRepr> parseTypeTupleBody();
  ParserResult<TypeRepr> parseTypeArray(TypeRepr *Base);

  /// Parse a collection type.
  ///   type-simple:
  ///     '[' type ']'
  ///     '[' type ':' type ']'
  ParserResult<TypeRepr> parseTypeCollection();
  ParserResult<OptionalTypeRepr> parseTypeOptional(TypeRepr *Base);

  ParserResult<ImplicitlyUnwrappedOptionalTypeRepr>
    parseTypeImplicitlyUnwrappedOptional(TypeRepr *Base);

  bool isOptionalToken(const Token &T) const;
  SourceLoc consumeOptionalToken();

  bool isImplicitlyUnwrappedOptionalToken(const Token &T) const;
  SourceLoc consumeImplicitlyUnwrappedOptionalToken();

  TypeRepr *applyAttributeToType(TypeRepr *Ty, const TypeAttributes &Attr);

  //===--------------------------------------------------------------------===//
  // Pattern Parsing

  /// A structure for collecting information about the default
  /// arguments of a context.
  struct DefaultArgumentInfo {
    llvm::SmallVector<DefaultArgumentInitializer *, 4> ParsedContexts;
    unsigned NextIndex : 31;

    /// Track whether or not one of the parameters in a signature's argument
    /// list accepts a default argument.
    unsigned HasDefaultArgument : 1;

    /// Claim the next argument index.  It's important to do this for
    /// all the arguments, not just those that have default arguments.
    unsigned claimNextIndex() { return NextIndex++; }

    /// Set the parsed context for all the initializers to the given
    /// function.
    void setFunctionContext(AbstractFunctionDecl *AFD);

    DefaultArgumentInfo(bool inTypeContext) {
      NextIndex = inTypeContext ? 1 : 0;
      HasDefaultArgument = false;
    }
  };

  /// Describes a parsed parameter.
  struct ParsedParameter {
    /// Any declaration attributes attached to the parameter.
    DeclAttributes Attrs;

    /// The location of the 'let', 'var', or 'inout' keyword, if present.
    SourceLoc LetVarInOutLoc;

    enum SpecifierKindTy {
      Let,
      Var,
      InOut
    };
    SpecifierKindTy SpecifierKind = Let; // Defaults to let.

    /// The location of the first name.
    ///
    /// \c FirstName is the name.
    SourceLoc FirstNameLoc;

    /// The location of the second name, if present.
    ///
    /// \p SecondName is the name.
    SourceLoc SecondNameLoc;

    /// The location of the '...', if present.
    SourceLoc EllipsisLoc;

    /// The first name.
    Identifier FirstName;

    /// The second name, the presence of which is indicated by \c SecondNameLoc.
    Identifier SecondName;

    /// The type following the ':'.
    TypeRepr *Type = nullptr;

    /// The default argument for this parameter.
    Expr *DefaultArg = nullptr;

    /// True if we emitted a parse error about this parameter.
    bool isInvalid = false;
  };

  /// Describes the context in which the given parameter is being parsed.
  enum class ParameterContextKind {
    /// An operator.
    Operator,
    /// A function.
    Function,
    /// An initializer.
    Initializer,
    /// A closure.
    Closure,
    /// A subscript.
    Subscript,
    /// A curried argument clause.
    Curried,
  };

  /// Parse a parameter-clause.
  ///
  /// \verbatim
  ///   parameter-clause:
  ///     '(' ')'
  ///     '(' parameter (',' parameter)* '...'? )'
  ///
  ///   parameter:
  ///     'inout'? ('let' | 'var')? '`'? identifier-or-none identifier-or-none?
  ///         (':' type)? ('...' | '=' expr)?
  ///
  ///   identifier-or-none:
  ///     identifier
  ///     '_'
  /// \endverbatim
  ParserStatus parseParameterClause(SourceLoc &leftParenLoc,
                                    SmallVectorImpl<ParsedParameter> &params,
                                    SourceLoc &rightParenLoc,
                                    DefaultArgumentInfo *defaultArgs,
                                    ParameterContextKind paramContext);

  ParserResult<ParameterList> parseSingleParameterClause(
                          ParameterContextKind paramContext,
                          SmallVectorImpl<Identifier> *namePieces = nullptr);

  ParserStatus parseFunctionArguments(SmallVectorImpl<Identifier> &NamePieces,
                                    SmallVectorImpl<ParameterList*> &BodyParams,
                                      ParameterContextKind paramContext,
                                      DefaultArgumentInfo &defaultArgs);
  ParserStatus parseFunctionSignature(Identifier functionName,
                                      DeclName &fullName,
                              SmallVectorImpl<ParameterList *> &bodyParams,
                                      DefaultArgumentInfo &defaultArgs,
                                      SourceLoc &throws,
                                      bool &rethrows,
                                      TypeRepr *&retType);
  ParserStatus parseConstructorArguments(DeclName &FullName,
                                         ParameterList *&BodyParams,
                                         DefaultArgumentInfo &defaultArgs);

  //===--------------------------------------------------------------------===//
  // Pattern Parsing

  ParserResult<Pattern> parseTypedPattern();
  ParserResult<Pattern> parsePattern();

  /// \brief Parse a tuple pattern element.
  ///
  /// \code
  ///   pattern-tuple-element:
  ///     pattern ('=' expr)?
  /// \endcode
  ///
  /// \returns The tuple pattern element, if successful.
  std::pair<ParserStatus, Optional<TuplePatternElt>>
  parsePatternTupleElement();
  ParserResult<Pattern> parsePatternTuple();

  ParserResult<Pattern>
  parseOptionalPatternTypeAnnotation(ParserResult<Pattern> P,
                                     bool isOptional);
  ParserResult<Pattern> parseMatchingPattern(bool isExprBasic);
  ParserResult<Pattern> parseMatchingPatternAsLetOrVar(bool isLet,
                                                       SourceLoc VarLoc,
                                                       bool isExprBasic);

  Pattern *createBindingFromPattern(SourceLoc loc, Identifier name, bool isLet);

  /// \brief Determine whether this token can only start a matching pattern
  /// production and not an expression.
  bool isOnlyStartOfMatchingPattern();

  //===--------------------------------------------------------------------===//
  // Speculative type list parsing
  //===--------------------------------------------------------------------===//

  /// Returns true if we can parse a generic argument list at the current
  /// location in expression context. This parses types without generating
  /// AST nodes from the '<' at the current location up to a matching '>'. If
  /// the type list parse succeeds, and the closing '>' is followed by one
  /// of the following tokens:
  ///   lparen_following rparen lsquare_following rsquare lbrace rbrace
  ///   period_following comma semicolon
  /// then this function returns true, and the expression will parse as a
  /// generic parameter list. If the parse fails, or the closing '>' is not
  /// followed by one of the above tokens, then this function returns false,
  /// and the expression will parse with the '<' as an operator.
  bool canParseAsGenericArgumentList();
  bool canParseAttributes();

  bool canParseType();
  bool canParseTypeIdentifier();
  bool canParseTypeIdentifierOrTypeComposition();
  bool canParseOldStyleProtocolComposition();
  bool canParseTypeTupleBody();
  bool canParseTypeAttribute();
  bool canParseGenericArguments();

  bool canParseTypedPattern();

  //===--------------------------------------------------------------------===//
  // Expression Parsing
  ParserResult<Expr> parseExpr(Diag<> ID) {
    return parseExprImpl(ID, /*isExprBasic=*/false);
  }
  ParserResult<Expr> parseExprBasic(Diag<> ID) {
    return parseExprImpl(ID, /*isExprBasic=*/true);
  }
  ParserResult<Expr> parseExprImpl(Diag<> ID, bool isExprBasic = false);
  ParserResult<Expr> parseExprIs();
  ParserResult<Expr> parseExprAs();
  ParserResult<Expr> parseExprArrow();
  ParserResult<Expr> parseExprSequence(Diag<> ID,
                                       bool isExprBasic,
                                       bool isForConditionalDirective = false);
  ParserResult<Expr> parseExprSequenceElement(Diag<> ID,
                                              bool isExprBasic);
  ParserResult<Expr> parseExprPostfix(Diag<> ID, bool isExprBasic);
  ParserResult<Expr> parseExprUnary(Diag<> ID, bool isExprBasic);
  ParserResult<Expr> parseExprKeyPath();
  ParserResult<Expr> parseExprSelector();
  ParserResult<Expr> parseExprSuper(bool isExprBasic);
  ParserResult<Expr> parseExprConfiguration();
  ParserResult<Expr> parseExprStringLiteral();
  ParserResult<Expr> parseExprTypeOf();

  /// If the token is an escaped identifier being used as an argument
  /// label, but doesn't need to be, diagnose it.
  void diagnoseEscapedArgumentLabel(const Token &tok);

  /// Parse an unqualified-decl-name.
  ///
  ///   unqualified-decl-name:
  ///     identifier
  ///     identifier '(' ((identifier | '_') ':') + ')'
  ///
  /// \param afterDot Whether this identifier is coming after a period, which
  /// enables '.init' and '.default' like expressions.
  /// \param loc Will be populated with the location of the name.
  /// \param diag The diagnostic to emit if this is not a name.
  DeclName parseUnqualifiedDeclName(bool afterDot, DeclNameLoc &loc,
                                    const Diagnostic &diag);

  Expr *parseExprIdentifier();
  Expr *parseExprEditorPlaceholder(Token PlaceholderTok,
                                   Identifier PlaceholderId);

  /// \brief Parse a closure expression after the opening brace.
  ///
  /// \verbatim
  ///   expr-closure:
  ///     '{' closure-signature? brace-item-list* '}'
  ///
  ///   closure-signature:
  ///     '|' closure-signature-arguments? '|' closure-signature-result?
  ///
  ///   closure-signature-arguments:
  ///     pattern-tuple-element (',' pattern-tuple-element)*
  ///
  ///   closure-signature-result:
  ///     '->' type
  /// \endverbatim
  ParserResult<Expr> parseExprClosure();

  /// \brief Parse the closure signature, if present.
  ///
  /// \verbatim
  ///   closure-signature:
  ///     parameter-clause func-signature-result? 'in'
  ///     identifier (',' identifier)* func-signature-result? 'in'
  /// \endverbatim
  ///
  /// \param captureList The entries in the capture list.
  /// \param params The parsed parameter list, or null if none was provided.
  /// \param arrowLoc The location of the arrow, if present.
  /// \param explicitResultType The explicit result type, if specified.
  /// \param inLoc The location of the 'in' keyword, if present.
  ///
  /// \returns true if an error occurred, false otherwise.
  bool parseClosureSignatureIfPresent(
                                SmallVectorImpl<CaptureListEntry> &captureList,
                                      ParameterList *&params,
                                      SourceLoc &throwsLoc,
                                      SourceLoc &arrowLoc,
                                      TypeRepr *&explicitResultType,
                                      SourceLoc &inLoc);

  Expr *parseExprAnonClosureArg();
  ParserResult<Expr> parseExprList(tok LeftTok, tok RightTok);

  /// Parse an expression list, keeping all of the pieces separated.
  ParserStatus parseExprList(tok leftTok, tok rightTok,
                             bool isPostfix,
                             bool isExprBasic,
                             SourceLoc &leftLoc,
                             SmallVectorImpl<Expr *> &exprs,
                             SmallVectorImpl<Identifier> &exprLabels,
                             SmallVectorImpl<SourceLoc> &exprLabelLocs,
                             SourceLoc &rightLoc,
                             Expr *&trailingClosure);

  ParserResult<Expr> parseTrailingClosure(SourceRange calleeRange);

  // NOTE: used only for legacy support for old object literal syntax.
  // Will be removed in the future.
  bool isCollectionLiteralStartingWithLSquareLit();

  /// Parse an object literal.
  ///
  /// \param LK The literal kind as determined by the first token.
  /// \param NewName New name for a legacy literal.
  ParserResult<Expr> parseExprObjectLiteral(ObjectLiteralExpr::LiteralKind LK,
                                            bool isExprBasic,
                                            StringRef NewName = StringRef());
  ParserResult<Expr> parseExprCallSuffix(ParserResult<Expr> fn,
                                         bool isExprBasic);
  ParserResult<Expr> parseExprCollection(SourceLoc LSquareLoc = SourceLoc());
  ParserResult<Expr> parseExprArray(SourceLoc LSquareLoc, Expr *FirstExpr);
  ParserResult<Expr> parseExprDictionary(SourceLoc LSquareLoc, Expr *FirstKey);

  UnresolvedDeclRefExpr *parseExprOperator();

  //===--------------------------------------------------------------------===//
  // Statement Parsing

  bool isStartOfStmt();
  ParserResult<Stmt> parseStmt();
  ParserStatus parseExprOrStmt(ASTNode &Result);
  ParserResult<Stmt> parseStmtBreak();
  ParserResult<Stmt> parseStmtContinue();
  ParserResult<Stmt> parseStmtReturn(SourceLoc tryLoc);
  ParserResult<Stmt> parseStmtThrow(SourceLoc tryLoc);
  ParserResult<Stmt> parseStmtDefer();
  ParserStatus parseStmtCondition(StmtCondition &Result, Diag<> ID,
                                  StmtKind ParentKind);
  ParserResult<PoundAvailableInfo> parseStmtConditionPoundAvailable();
  ParserResult<Stmt> parseStmtIf(LabeledStmtInfo LabelInfo);
  ParserResult<Stmt> parseStmtGuard();
  ParserResult<Stmt> parseStmtIfConfig(BraceItemListKind Kind
                                        = BraceItemListKind::Brace);
  ParserResult<Stmt> parseStmtWhile(LabeledStmtInfo LabelInfo);
  ParserResult<Stmt> parseStmtRepeat(LabeledStmtInfo LabelInfo);
  ParserResult<Stmt> parseStmtDo(LabeledStmtInfo LabelInfo);
  ParserResult<CatchStmt> parseStmtCatch();
  ParserResult<Stmt> parseStmtFor(LabeledStmtInfo LabelInfo);
  ParserResult<Stmt> parseStmtForCStyle(SourceLoc ForLoc,
                                        LabeledStmtInfo LabelInfo);
  ParserResult<Stmt> parseStmtForEach(SourceLoc ForLoc,
                                      LabeledStmtInfo LabelInfo);
  ParserResult<Stmt> parseStmtSwitch(LabeledStmtInfo LabelInfo);
  ParserResult<CaseStmt> parseStmtCase();

  /// Evaluate the condition of an #if directive.
  ConditionalCompilationExprState
  evaluateConditionalCompilationExpr(Expr *condition);

  //===--------------------------------------------------------------------===//
  // Generics Parsing

  ParserResult<GenericParamList> parseGenericParameters();
  ParserResult<GenericParamList> parseGenericParameters(SourceLoc LAngleLoc);
  ParserResult<GenericParamList> maybeParseGenericParams();
  void
  diagnoseWhereClauseInGenericParamList(const GenericParamList *GenericParams);

  enum class WhereClauseKind : unsigned {
    Declaration,
    Protocol,
    AssociatedType
  };
  ParserStatus
  parseFreestandingGenericWhereClause(GenericParamList *&GPList,
                             WhereClauseKind kind=WhereClauseKind::Declaration);

  ParserStatus parseGenericWhereClause(SourceLoc &WhereLoc,
                               SmallVectorImpl<RequirementRepr> &Requirements,
                                       bool &FirstTypeInComplete);

  //===--------------------------------------------------------------------===//
  // Availability Specification Parsing

  /// Parse a comma-separated list of availability specifications.
  ParserStatus
  parseAvailabilitySpecList(SmallVectorImpl<AvailabilitySpec *> &Specs);

  ParserResult<AvailabilitySpec> parseAvailabilitySpec();
  ParserResult<VersionConstraintAvailabilitySpec> parseVersionConstraintSpec();
};

/// Describes a parsed declaration name.
struct ParsedDeclName {
  /// The name of the context of which the corresponding entity should
  /// become a member.
  StringRef ContextName;

  /// The base name of the declaration.
  StringRef BaseName;

  /// The argument labels for a function declaration.
  SmallVector<StringRef, 4> ArgumentLabels;

  /// Whether this is a function name (vs. a value name).
  bool IsFunctionName = false;

  /// Whether this is a getter for the named property.
  bool IsGetter = false;

  /// Whether this is a setter for the named property.
  bool IsSetter = false;

  /// For a declaration name that makes the declaration into an
  /// instance member, the index of the "Self" parameter.
  Optional<unsigned> SelfIndex;

  /// Determine whether this is a valid name.
  explicit operator bool() const { return !BaseName.empty(); }

  /// Whether this declaration name turns the declaration into a
  /// member of some named context.
  bool isMember() const { return !ContextName.empty(); }

  /// Whether the result is translated into an instance member.
  bool isInstanceMember() const {
    return isMember() && static_cast<bool>(SelfIndex);
  }

  /// Whether the result is translated into a static/class member.
  bool isClassMember() const {
    return isMember() && !static_cast<bool>(SelfIndex);
  }

  /// Whether this is a property accessor.
  bool isPropertyAccessor() const { return IsGetter || IsSetter; }

  /// Whether this is an operator.
  bool isOperator() const {
    return Lexer::isOperator(BaseName);
  }

  /// Form a declaration name from this parsed declaration name.
  DeclName formDeclName(ASTContext &ctx) const;
};

/// Parse a stringified Swift declaration name,
/// e.g. "Foo.translateBy(self:x:y:)".
ParsedDeclName parseDeclName(StringRef name) LLVM_READONLY;

/// Form a Swift declaration name from its constituent parts.
DeclName formDeclName(ASTContext &ctx,
                      StringRef baseName,
                      ArrayRef<StringRef> argumentLabels,
                      bool isFunctionName);

/// Parse a stringified Swift declaration name, e.g. "init(frame:)".
DeclName parseDeclName(ASTContext &ctx, StringRef name);

} // end namespace swift

#endif


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Documenting workflows • Arbor</title>

	<meta name="twitter:title" content="Documenting workflows">

	<meta name="twitter:site" content="@lukejharmon">
	<meta name="twitter:creator" content="@lukejharmon">

	<meta name="twitter:card" content="summary">
	<meta name="twitter:image" content="/images/120x120.gif">

	<meta property="og:locale" content="en_US">
	<meta property="og:type" content="article">
	<meta property="og:title" content="Documenting workflows">

	<meta property="og:url" content="/styleGuide/workflows/">
	<meta property="og:site_name" content="Arbor">

    <link rel="canonical" href="/styleGuide/workflows/">

    <link href="/atom.xml" type="application/atom+xml" rel="alternate" title="Arbor Atom Feed">
    <link href="/sitemap.xml" type="application/xml" rel="sitemap" title="Sitemap">

    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="cleartype" content="on">

    <link rel="stylesheet" href="/css/main.css">

    Arbor

Arbor

Help

Use Arbor

Docs & tutorials

Developers

Contact

Arbor Table of Contents

Help

Get help

Use Arbor

Run Arbor over the web or install it yourself

Docs & tutorials

Full documentation for functions and workflows

Developers

Add to the Arbor code base

Contact

Contact us

<button type="button" id="js-menu-trigger" class="sliding-menu-button lines-button x2" role="button" aria-label="Toggle Navigation">

</button>

Documenting workflows

Structure of an Arbor workflow documentation page

Pages should have the following sections.

yaml header

The beginning of the markdown text file is the yaml header. For all documentation files, the layout should be "documentation."  "arbortype" should be "workflow". If you include an image then a matching file must also be in the "images" folder in the archive - and then that image will be displayed at the top of the page.

---
layout: documentation
title: matchTreeAndTraits
author: Arbor core team
categories: collections ancestralStates
arbortype: workflow
arborcollection: ancestralStates
description: "match a tree and tip data"
image: acearbor.png

---

Documentation

Overview: brief description of workflow

The overview should give a brief (one sentence) overview of what the workflow in the collection does.

More details

This can give additional details about the workflow, such as which algorithms are included.

References

Include all references to the functions in the workflow.

Home

Getting Started

About

Team

© 2018 Arbor powered by Jekyll + Skinny Bones.


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/common.css">
        <link rel="stylesheet" href="css/main.css">

Агентство недвижимости в Днепропетровске

								097  321 68 31

								063  697 76 76

								067  955 00 50

ул. Демьяна Бедного, 15

topestate.dp.ua@gmail.com

Продажа

Аренда

Свежие предложения

Блокнот

Полезно знать

О нас

Добро пожаловать на сайт Агентства недвижимости «TOP ESTATE»

Наше агентство предоставляет полный спектр услуг на рынке недвижимости г. Днепропетровска. Мы предлагаем
						оптимальное решение для желающих арендовать или сдать свою недвижимость в Днепропетровске на длительный
						срок.

Обратившись к нам, Вы можете ознакомиться с широким выбором объектов недвижимости, от бюджетных вариантов
					эконом - класса, до апартаментов элит класса.

На нашем сайте представлена ежедневно обновляемая база данных квартир на длительный срок. Так же на нашем
						сайте представлен ФотоКаталог объектов недвижимости благодаря которому Вы сможете, не тратя своего времени,
						ни выходя из дома или офиса подобрать интересующий Вас вариант. Обратившись к нам, Вы найдете Ваш идеальный вариант для жизни, отдыха, или бизнеса по оптимальной цене!

Обращаем Ваше внимание на то, что активность рынка аренды гораздо выше активности рынка продаж,
                        поэтому на сайте опубликованы не все имеющиеся в базе варианты квартир  и не все квартиры могут быть
                        актуальными на момент Вашего звонка или электронного письма, особенно это касается не дорогих
                        бюджетных вариантов. Для получения более подробной и актуальной информации просим связываться с
                        нами по телефону, если у Вас такой возможности нет, отправьте письмо на наш электронный адрес.

Оплата у собственников квартир - 2 месяца предоплаты (первый месяц и залог) залог возвращается
                        арендатору после окончания срока действия договора. В случае нанесения ущерба квартире собственника,
                        с залога вычитается сумма необходимая для компенсации нанесенного ущерба.

Стоимость услуг для Арендаторов - 50% от месячной
						стоимости аренды квартиры (разово). Оплата услуг
                        производится по факту вселения, после подписания
                        договора аренды квартиры и передачи ключей!

						Агенство недвижимости в Днепропетровске «Top Estate»


text:
Bootstrap Skeleton for WordPress ChangeLog
==========================================


text:
<?php include_once '../bootstrap.php' ?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
    <title>Embeded - Store for JUI</title>
	<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
	<link rel="icon" href="/favicon.ico" type="image/x-icon">
	<script type="text/javascript" src="/bower_components/codemirror/lib/codemirror.js"></script>
	<link href="/bower_components/codemirror/lib/codemirror.css" rel="stylesheet" />
	<script src="/bower_components/codemirror/mode/javascript/javascript.js"></script>

	<?php if (!$_GET['only']) { ?>
	<script src="/bower_components/codemirror/mode/htmlmixed/htmlmixed.js"></script>
	<script src="/bower_components/codemirror/mode/xml/xml.js"></script>
	<script src="/bower_components/codemirror/mode/css/css.js"></script>
	<?php } ?>

	<link href="/bower_components/codemirror/theme/twilight.css" rel="stylesheet" />
    <script type="text/javascript" src="/bower_components/jquery/dist/jquery.min.js"></script>
	<link href="/jui-all/jui/dist/ui.min.css" rel="stylesheet" />
	<link href="/jui-all/jui/dist/ui-jennifer.min.css" rel="stylesheet" />
	<link href="/jui-all/jui-grid/dist/grid.min.css" rel="stylesheet" />
	<link href="/jui-all/jui-grid/dist/grid.jennifer.min.css" rel="stylesheet" />
	<link href="/css/embed.css" rel="stylesheet" />
	<script type="text/javascript" src="/jui-all/jui-core/dist/core.min.js"></script>
	<script type="text/javascript" src="/jui-all/jui/dist/ui.min.js"></script>
	<script type="text/javascript" src="/jui-all/jui-grid/dist/grid.min.js"></script>
	<script type="text/javascript" src="/jui-all/jui-chart/dist/chart.min.js"></script>
	<?php echo $meta ?>
</head>
<body class="jui">


text:
// Type definitions for es6-promises
// Project: https://github.com/jakearchibald/ES6-Promises
// Definitions by: François de Campredon <https://github.com/fdecampredon/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped

interface Thenable<R> {
	then<U>(onFulfill: (value: R) => Thenable<U>,  onReject: (error: any) => Thenable<U>): Thenable<U>;
    then<U>(onFulfill: (value: R) => Thenable<U>, onReject?: (error: any) => U): Thenable<U>;
    then<U>(onFulfill: (value: R) => U, onReject: (error: any) => Thenable<U>): Thenable<U>;
    then<U>(onFulfill?: (value: R) => U, onReject?: (error: any) => U): Thenable<U>;

}

declare class Promise<R> implements Thenable<R> {
    /**
     * If you call resolve in the body of the callback passed to the constructor,
     * your promise is fulfilled with result object passed to resolve.
     * If you call reject your promise is rejected with the object passed to resolve.
     * For consistency and debugging (eg stack traces), obj should be an instanceof Error.
     * Any errors thrown in the constructor callback will be implicitly passed to reject().
     */
	constructor(callback: (resolve : (result: R) => void, reject: (error: any) => void) => void);
    /**
     * If you call resolve in the body of the callback passed to the constructor,
     * your promise will be fulfilled/rejected with the outcome of thenable passed to resolve.
     * If you call reject your promise is rejected with the object passed to resolve.
     * For consistency and debugging (eg stack traces), obj should be an instanceof Error.
     * Any errors thrown in the constructor callback will be implicitly passed to reject().
     */
	constructor(callback: (resolve : (thenable: Thenable<R>) => void, reject: (error: any) => void) => void);

    /**
     * onFulFill is called when/if "promise" resolves. onRejected is called when/if "promise" rejects.
     * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called.
     * Both callbacks have a single parameter , the fulfillment value or rejection reason.
     * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve.
     * If an error is thrown in the callback, the returned promise rejects with that error.
     *
     * @param onFulFill called when/if "promise" resolves
     * @param onReject called when/if "promise" rejects
     */
	then<U>(onFulfill: (value: R) => Thenable<U>,  onReject: (error: any) => Thenable<U>): Promise<U>;
    /**
     * onFulFill is called when/if "promise" resolves. onRejected is called when/if "promise" rejects.
     * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called.
     * Both callbacks have a single parameter , the fulfillment value or rejection reason.
     * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve.
     * If an error is thrown in the callback, the returned promise rejects with that error.
     *
     * @param onFulFill called when/if "promise" resolves
     * @param onReject called when/if "promise" rejects
     */
    then<U>(onFulfill: (value: R) => Thenable<U>, onReject?: (error: any) => U): Promise<U>;
    /**
     * onFulFill is called when/if "promise" resolves. onRejected is called when/if "promise" rejects.
     * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called.
     * Both callbacks have a single parameter , the fulfillment value or rejection reason.
     * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve.
     * If an error is thrown in the callback, the returned promise rejects with that error.
     *
     * @param onFulFill called when/if "promise" resolves
     * @param onReject called when/if "promise" rejects
     */
    then<U>(onFulfill: (value: R) => U, onReject: (error: any) => Thenable<U>): Promise<U>;
    /**
     * onFulFill is called when/if "promise" resolves. onRejected is called when/if "promise" rejects.
     * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called.
     * Both callbacks have a single parameter , the fulfillment value or rejection reason.
     * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve.
     * If an error is thrown in the callback, the returned promise rejects with that error.
     *
     * @param onFulFill called when/if "promise" resolves
     * @param onReject called when/if "promise" rejects
     */
    then<U>(onFulfill?: (value: R) => U, onReject?: (error: any) => U): Promise<U>;

    /**
     * Sugar for promise.then(undefined, onRejected)
     *
     * @param onReject called when/if "promise" rejects
     */
	catch<U>(onReject?: (error: any) => Thenable<U>): Promise<U>;
    /**
     * Sugar for promise.then(undefined, onRejected)
     *
     * @param onReject called when/if "promise" rejects
     */
	catch<U>(onReject?: (error: any) => U): Promise<U>;
}

declare module Promise {

	/**
	 * Returns promise (only if promise.constructor == Promise)
	 */
	function cast<R>(promise: Promise<R>): Promise<R>;
    /**
	 * Make a promise that fulfills to obj.
	 */
	function cast<R>(object?: R): Promise<R>;

    /**
     * Make a new promise from the thenable.
     * A thenable is promise-like in as far as it has a "then" method.
     * This also creates a new promise if you pass it a genuine JavaScript promise, making it less efficient for casting than Promise.cast.
     */
	function resolve<R>(thenable: Thenable<R>): Promise<R>;
    /**
     * Make a promise that fulfills to obj. Same as Promise.cast(obj) in this situation.
     */
	function resolve<R>(object?: R): Promise<R>;

	/**
	 * Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error
	 */
	function reject(error?: any): Promise<any>;

    /**
     * Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects.
     * the array passed to all can be a mixture of promise-like objects and other objects.
     * The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value.
     */
	function all<R>(promises: Promise<R>[]): Promise<R[]>;

    /**
     * Make a Promise that fulfills when any item fulfills, and rejects if any item rejects.
     */
	function race<R>(promises: Promise<R>[]): Promise<R>;
}


text:
package org.apache.cassandra.notifications;

import org.apache.cassandra.io.sstable.SSTableReader;

import java.util.List;

public class SSTableAddedNotification implements INotification
{
    public SSTableReader added;
    public SSTableAddedNotification(SSTableReader added)
    {
        this.added = added;
    }
}


text:
import java.util.Queue;

public interface Destructible {
    Queue<Message> destroy();
}


text:
package com.ibm.wuhan.bus.web.tag;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.SkipPageException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class RefererTag extends SimpleTagSupport {

	private String site;
	private String page;

	public void setSite(String site) {
		this.site = site;
	}

	public void setPage(String page) {
		this.page = page;
	}

	@Override
	public void doTag() throws JspException, IOException {

		PageContext pageContext = (PageContext) this.getJspContext();
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
		// 1 得到来访者的 referer
		String referer = request.getHeader("referer");
		if (referer == null || !referer.startsWith(site)) {

			if (page.startsWith(request.getContextPath())) {
				response.sendRedirect(page);
			} else if (page.startsWith("/")) {
				response.sendRedirect(request.getContextPath() + page);
			} else {
				response.sendRedirect(request.getContextPath() + "/" + page);
			}
			throw new SkipPageException();
		}else{

		}

		// 2 判断来访者页面是不是 要防盗链的网站 site

	}

}


text:
// ==========================================================================
// Validators
// Author: Charles Jolley
// ==========================================================================

require('foundation/object');

/**
  @class

  Validators provide a way for you to implement simple form field validation
  and transformation.  To use a validator, simply name the validator in the
  "validate" attribute in your text field.  For example, if you want to
  validate a field using the PhoneNumberValidator use this:

  <input value="1234567890" validate="phone-number" />

  Validators get notified at three points.  You can implement one or all
  of these methods to support validation.  All of the validate methods except
  for validateKeypress behave the same way.  You are passed a form, field,
  and possibly the oldValue.  You are expected to return Validator.OK or
  an error string.  Inside this method you typically do one of all of the
  following:

  1. You can simply validate the field value and return OK or an error str

  2. You can modify the field value (for example, you could format the
     string to match some predefined format).

  3. If you need to roundtrip the server first to perform validation, you can
     return Validator.OK, then save the form and field info until after the
     roundtrip.  On return, if there is a problem, first verify the field
     value has not changed and then call form.errorFor(field,str) ;

  @extends SC.Object
  @author Charles Jolley
  @version 1.0
*/
SC.Validator = SC.Object.extend(
/** @scope SC.Validator.prototype */ {

  // ..........................................
  // OBJECT VALUE CONVERSION
  //
  // The following methods are used to convert the string value of a field
  // to and from an object value.  The default implementations return
  // the string, but you can override this to provide specific behaviors.
  // For example, you might add or remove a dollar sign or convert the
  // value to a number.

/**
  Returns the value to set in the field for the passed object value.

  The form and view to be set MAY (but will not always) be passed also.  You
  should override this method to help convert an input object into a value
  that can be displayed by the field.  For example, you might convert a
  date to a property formatted string or a number to a properly formatted
  value.

  @param {Object} object The object to transform
  @param {SC.FormView} form The form this field belongs to. (optional)
  @param {SC.View} view The view the value is required for.
  @returns {Object} a value (usually a string) suitable for display
*/
  fieldValueForObject: function(object, form, view) { return object; },

  /**
    Returns the object value for the passed string.

    The form and view MAY (but wil not always) be passed also.  You should
    override this method to convert a field value, such as string, into an
    object value suitable for consumption by the rest of the app.  For example
    you may convert a string into a date or a number.

    @param {String} value the field value.  (Usually a String).
    @param {SC.FormView} form The form this field belongs to. (optional)
    @param {SC.View} view The view this value was pulled from.
    @returns {Object} an object suitable for consumption by the app.
  */
  objectForFieldValue: function(value, form, view) { return value; },

  // ..........................................
  // VALIDATION PRIMITIVES
  //

  /**
    Validate the field value.

    You can implement standard behavior for your validator by using the
    vaidate and validateError methods.  validate() should return false
    if the field is not valid.

    @param {SC.FormView} form the form this view belongs to
    @param {SC.View} field the field to validate.  Responds to fieldValue.
    @returns {Boolean} YES if field is valid.
  */
  validate: function(form, field) { return true; },

  /**
    Returns an error object if the field is invalid.

    This is the other standard validator method that can be used to impement
    basic validation.  This should return an error object explaining why
    the field is not valid.  It will only be called if validate() returned
    false.

    @param {SC.FormView} form the form this view belongs to
    @param {SC.View} field the field to validate.  Responds to fieldValue.
    @returns {SC.Error} an error object
  */
  validateError: function(form, field) {
    return $error(
      "Invalid.General(%@)".loc(field.get('fieldValue')),
      field.get('fieldKey')) ;
  },

  // ..........................................
  // VALIDATION API
  //

  /**
    Invoked just before the user ends editing of the field.

    The default implementation calls your validate() method and then
    validateError() if valiate() returns NO.  This method should return
    SC.Validator.OK if validation succeeded or an error object if it fails.

    @param {SC.FormView} form the form for the field
    @param {SC.View} field the field to validate
    @param {Object} oldValue: the value of the field before the change

    @returns SC.Validator.OK or an error object.

  */
  validateChange: function(form, field, oldValue) {
    return (this.validate(form,field)) ? SC.Validator.OK : this.validateError(form, field);
  },

  /**
    Invoked just before the form is submitted.

    This method gives your validators one last chance to perform validation
    on the form as a whole.  The default version does the same thing as the
    validateChange() method.

    @param {SC.FormView} form the form for the field
    @param {SC.View} field the field to validate

    @returns SC.Validator.OK or an error object.

  */
  validateSubmit: function(form, field) {
    return (this.validate(form,field)) ? SC.Validator.OK : this.validateError(form, field);
  },

  /**
    Invoked 1ms after the user types a key (if a change is allowed).

    You can use this validate the new partial string and return an error if
    needed. The default will validate a partial only if there was already an
    error. This allows the user to try to get it right before you bug them.

    Unlike the other methods, you should return SC.Validator.NO_CHANGE if you
    did not actually validate the partial string.  If you return
    SC.Validator.OK then any showing errors will be hidden.

    @param {SC.FormView} form the form for the field
    @param {SC.View} field the field to validate

    @returns SC.Validator.OK, SC.Validator.NO_CHANGE or an error object.
  */
  validatePartial: function(form, field) {
    if (!field.get('isValid')) {
      return (this.validate(form,field)) ? SC.Validator.OK : this.validateError(form, field);
    } else return SC.Validator.NO_CHANGE ;
  },

  /**
    Invoked when the user presses a key.

    This method is used to restrict the letters and numbers the user is
    allowed to enter.  You should not use this method to perform full
    validation on the field.  Instead use validatePartial().

    @param {SC.FormView} form the form for the field
    @param {SC.View} field the field to validate
    @param {String} char the characters being added

    @returns {Boolean} YES if allowed, NO otherwise
  */
  validateKeypress: function(form, field,charStr) { return true; },

  // .....................................
  // OTHER METHODS

  /**
    Called on all validators when they are attached to a field.

    You can use this to do any setup that you need.  The default does nothing.

    @param {SC.FormView} form the form for the field
    @param {SC.View} field the field to validate
  */
  attachTo: function(form,field) { },

  /**
    Called on a validator just before it is removed from a field.  You can
    tear down any setup you did for the attachTo() method.

    @param {SC.FormView} form the form for the field
    @param {SC.View} field the field to validate
  */
  detachFrom: function(form, field) {}

}) ;

SC.Validator.mixin(/** @scope SC.Validator */ {

  /**
    Return value when validation was performed and value is OK.
  */
  OK: true,

  /**
    Return value when validation was not performed.
  */
  NO_CHANGE: false,

  /**
    Invoked by a field whenever a validator is attached to the field.

    The passed validatorKey can be a validator instance, a validator class
    or a string naming a validator. To make your validator
    visible, you should name your validator under the SC.Validator base.
    for example SC.Validator.Number would get used for the 'number'
    validator key.

    This understands validatorKey strings in the following format:

    * 'key' or 'multiple_words' will find validators Key and MultipleWords

    * if you want to share a single validator among multiple fields (for
      example to validate that two passwords are the same) set a name inside
      brackets. i.e. 'password[pwd]'.

    @param {SC.FormView} form the form for the field
    @param {SC.View} field the field to validate
    @param {Object} validatorKey the key to validate

    @returns {SC.Validaotr} validator instance or null
  */
  findFor: function(form,field, validatorKey) {

    // Convert the validator into a validator instance.
    var validator ;
    if (!validatorKey) return ; // nothing to do...

    if (validatorKey instanceof SC.Validator) {
      validator = validatorKey ;
    } else if (validatorKey.isClass) {
      validator = validatorKey.create() ;

    } else if ($type(validatorKey) == T_STRING) {

      // extract optional key name
      var name = null ;
      var m = validatorKey.match(/^(.+)\[(.*)\]/) ;
      if (m) {
        validatorKey = m[1] ; name = m[2];
      }

      // convert the validatorKey name into a class.
      validatorKey = ('-' + validatorKey).camelize() ;
      var validatorClass = SC.Validator[validatorKey] ;
      if (validatorClass == null) {
        throw "validator %@ not found for %@".fmt(validatorKey, field) ;
        return null ;
      } else if (name) {

        // if a key was also passed, then find the validator in the list of
        // validators for the form.  Otherwise, just create a new instance.
        if (!form) {
          throw "named validator (%@) could not be found for field %@ because the field does not belong to a form".fmt(name,field) ;
          return null ;
        }

        if (!form._validatorHash) form._validatorHash = {} ;
        var validator = (name) ? form._validatorHash[name] : null ;
        if (!validator) validator = validatorClass.create() ;
        if (name) form._validatorHash[name] = validator ;
      } else validator = validatorClass.create() ;
    }

    return validator ;
  },

  /**
    Convenience class method to call the fieldValueForObject() instance
    method you define in your subclass.
  */
  fieldValueForObject: function(object, form, field) {
    return this.prototype.fieldValueForObject(object,form,field) ;
  },

  /**
    Convenience class method to call the objectForFieldValue() instance
    method you define in your subclass.
  */
  objectForFieldValue: function(value, form, field) {
    return this.prototype.objectForFieldValue(value,form,field) ;
  }

}) ;


text:
import csv
import math

seasia_countries = ['vn', 'id', 'th', 'sg', 'my', 'ph', 'mm', 'kh', 'la', 'bn', 'tl']
fieldnames = [
    'furry_status',
    'age',
    'gender',
    'gender_alignment',
    'orientation',
    'country',
    'religion',
    'occupation',
    'education',
    'howfurry',
    'howoften_write',
    'howoften_draw',
    'opinion_artwork',
    'opinion_writing',
    'opinion_online_communities',
    'opinion_conventions',
    'opinion_fursuiting',
    'importance_artwork',
    'importance_writing',
    'importance_online_communities',
    'importance_conventions',
    'importance_fursuiting',
]

def parse(row, into):
    if not row['birthdate']:
        row['birthdate'] = 2017
    into.writerow({
        'furry_status': row['furry_status'],
        'age': 2017 - int(math.floor(float(row['birthdate']))),
        'gender': row['gender'],
        'gender_alignment': row['gender_alignment'],
        'orientation': row['orientation'],
        'country': row['country'],
        'religion': row['religion'],
        'occupation': row['occupation'],
        'education': row['education'],
        'howfurry': row['howfurry'],
        'howoften_write': row['howoften_write'],
        'howoften_draw': row['howoften_draw'],
        'opinion_artwork': row['opinion_artwork'],
        'opinion_writing': row['opinion_writing'],
        'opinion_online_communities': row['opinion_online_communities'],
        'opinion_conventions': row['opinion_conventions'],
        'opinion_fursuiting': row['opinion_fursuiting'],
        'importance_artwork': row['importance_artwork'],
        'importance_writing': row['importance_writing'],
        'importance_online_communities': row['importance_online_communities'],
        'importance_conventions': row['importance_conventions'],
        'importance_fursuiting': row['importance_fursuiting'],
    })

with open('arts2016seasia.csv', 'wb') as seasia_file, open('arts2016total.csv', 'wb') as total_file, open('results.csv') as results_file:
    seasia_csv = csv.DictWriter(seasia_file, fieldnames)
    seasia_csv.writeheader()
    total_csv = csv.DictWriter(total_file, fieldnames)
    total_csv.writeheader()
    results_csv = csv.DictReader(results_file)
    for row in results_csv:
        if row['year'] != '2016':
            continue
        parse(row, total_csv)
        if row['country'] in seasia_countries:
            parse(row, seasia_csv)


text:
/**
 * Created by zpl on 15-3-22.
 * 拦截器
 */
angular.module('Editor').
    factory('httpInterceptor',['$q','$cookies', function($q,$cookies){
        var isNeedAuth=function(uri,method){
            //check url is contain api
            if(uri.indexOf('api')>0){
                if(uri.split('coderun')>1){
                    return false;
                }
                if(method == 'POST' || method== 'PUT' ||method=='DELETE'){
                    return true;
                }
            }
            return false;
        };
        var httpInterceptor = {
            request: function(config) {
                if(config.url.indexOf('api')>0){
                    config.url =apiService + config.url;
                }
                if (isNeedAuth(config.url,config.method)) {
                    if(($cookies.get("token"))==undefined) {
                        return $q.reject({status:401,error:'请登陆'});
                    }
                    config.headers['x-session-token'] = $cookies.get("token");
                }
                return config;
            },
            response : function(response) {
                return response;
            },
            responseError : function(response) {
                if (response.status == 401) {
                    alert('must login');
                    window.location.href = ssoUrl+window.location.href;
                    return $q.reject(response);
                } else if (response.status === 404) {
                    alert("404!");
                    return $q.reject(response);
                }
            },
            requestError : function(config){
                return $q.reject(config);
            }
        };
        return httpInterceptor;
    }
    ]);


text:
Sunny is a multi-cloud datastore client for [Node.js](http://nodejs.org).
Sunny aims for an efficient, event-based common interface to various cloud
stores to enable cloud-agnostic programming that retains flexibility and
speed.

* [Sunny.js Documentation](http://sunnyjs.org): Guides and API documentation.
* [Sunny.js GitHub Page](http://github.com/ryan-roemer/node-sunny): Source
  repository and issue tracker.

## Features
* Abstracts cloud provider differences. Focus on writing your application,
  not juggling "x-amz-" vs. "x-goog-" headers.
* Fully configurable headers, cloud headers, cloud metadata.
* Sensible and cloud-agnostic error handling.
* "One-shot" requests whenever possible.
* SSL support.
* Blob GET/PUT operations implement Node [Readable][ReadStream] and
  [Writable][WriteStream] Stream interfaces.

[ReadStream]: http://nodejs.org/docs/v0.4.9/api/streams.html#readable_Stream
[WriteStream]: http://nodejs.org/docs/v0.4.9/api/streams.html#writable_Stream

## Cloud providers
Sunny has full blob support for:

* [Amazon S3][S3]: Amazon Simple Storage Service.
* [Google Storage][GSFD]: Google Storage for Developers.

[S3]: http://aws.amazon.com/s3/
[GSFD]: http://code.google.com/apis/storage/

Future support is planned for:

* [Rackspace Cloud Files][CF]: Rackspace Cloud Files
* [OpenStack Storage][OS]: OpenStack Storage
* (Maybe) local file system as a dummy cloud provider.

[CF]: http://www.rackspacecloud.com/cloud_hosting_products/files/
[OS]: http://openstack.org/projects/storage/

## Installation / Getting Started
Install Sunny directly from [npm][NPM]:

    $ npm install sunny

or the [GitHub][SGH] repository:

    $ git clone git@github.com:ryan-roemer/node-sunny.git
    $ npm install ./node-sunny

[NPM]: http://npmjs.org/
[SGH]: https://github.com/ryan-roemer/node-sunny

Please read the docs (in source at "docs/") and review the "live" tests
(in source at "test/live") that perform the entire range of Sunny operations
against real cloud datastores.

## Project Goals
### A common cloud interface.
The cloud providers that Sunny supports (or will support) provide similar, but
not quite equivalent interfaces. Amazon S3 and Google Storage share a nearly
identical interface, as well as Rackspace Cloud Files and OpenStack Storage.
However, there are some subtle differences, particularly with naming, errors,
status codes, etc.

### Extensible and accessible.
Notwithstanding the goal for a common API, Sunny aims to provide access to
as much of the internals of a given cloud datastore as possible. In the current
development phase, that means exposing as many of the query / header / metadata
features and functionality in the underlying store as won't make maintaining
a common interface unpalatable.

### Strong bias for "one-shot" requests.
Most cloud operations can be performed with a single HTTP request. However,
many cloud client libraries add in extra HTTP calls along the way for say
a blob file GET request (perhaps first requesting an authorization URL,
checking the container path for existence, etc.).

Sunny aims to perform the minimum amount of calls possible by default. That
said, sometimes it is good to have a few sanity check intermediate operations,
so Sunny can make calls with validation (e.g., checking a bucket exists first).

## Cloud Operations
### Supported
Sunny currently supports the following cloud operations:

* List containers:
  ``connection.getContainers()``
* PUT / DELETE container:
  ``container.put()``,
  ``container.del()``
* List blobs in a container:
  ``container.getBlobs()``
* PUT / HEAD / GET / DELETE blob:
  ``blob.put()``,
  ``blob.putFromFile()``,
  ``blob.head()``,
  ``blob.get()``,
  ``blob.getToFile()``,
  ``blob.del()``

### Future
Sunny is under rapid development. Some areas for enhancements:

* Copy blob.
* Update blob metadata without PUT.
* Set blob / container ACL, policies, etc.


text:
module MongoMapper
  module Plugins
    module EmbeddedCallbacks
      extend ActiveSupport::Concern

      included do
        extend  ::ActiveModel::Callbacks

        define_model_callbacks :save, :create, :update, :destroy, :only => [:before, :after]
        define_model_callbacks :touch, :only => [:after]

        embedded_callbacks_on
      end

      module ClassMethods
        def embedded_callbacks_on
          @embedded_callbacks_status = true
        end

        def embedded_callbacks_off
          @embedded_callbacks_status = false
        end

        def embedded_callbacks_on?
          @embedded_callbacks_status == true
        end

        def embedded_callbacks_off?
          !embedded_callbacks_on?
        end
      end

      def run_callbacks(callback, *args, &block)

        if self.class.embedded_callbacks_on?
          embedded_docs = []

          embedded_associations.each do |association|
            embedded_docs += Array(get_proxy(association).send(:load_target))
          end

          block = embedded_docs.inject(block) do |chain, doc|
            if doc.class.respond_to?("_#{callback}_callbacks")
              lambda { doc.run_callbacks(callback, *args, &chain) }
            else
              chain
            end
          end
        end

        super callback, *args, &block
      end
    end
  end
end


text:
//  Copyright 2021 Google LLC. All Rights Reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

using NtApiDotNet.Utilities.Reflection;

#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member

namespace NtApiDotNet.Net.Firewall
{
    [SDKName("IKEEXT_AUTHENTICATION_IMPERSONATION_TYPE")]
    public enum IkeExtAuthenticationImpersonationType
    {
        [SDKName("IKEEXT_IMPERSONATION_NONE")]
        None = 0,
        [SDKName("IKEEXT_IMPERSONATION_SOCKET_PRINCIPAL")]
        SocketPrincipal = (None + 1),
    }
}

#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member


text:
using namespace consensus;

class ReplicatedLogTest : public BaseTest {
 public:
  void SetUp() override {
    options.initial_cluster[1] = "127.0.0.1:12321";
    options.id = 1;
    options.heartbeat_interval = 100;
    options.election_timeout = 1000;
    options.memstore = new yaraft::MemoryStorage;

    yaraft::MemStoreUptr memstore;
    options.wal = wal::TEST_CreateWalStore(GetTestDir(), &memstore).release();
    options.memstore = memstore.release();
  }

  void TearDown() override {
    delete replicatedLog;
    delete options.wal;
  }

 protected:
  ReplicatedLog* replicatedLog;
  ReplicatedLogOptions options;
};

TEST_F(ReplicatedLogTest, WriteToNonLeader) {
  TestDirGuard g(CreateTestDirGuard());
  ASSIGN_IF_ASSERT_OK(ReplicatedLog::New(options), replicatedLog);

  Status s = replicatedLog->Write("abc");
  ASSERT_EQ(s.Code(), Error::WalWriteToNonLeader);
}

TEST_F(ReplicatedLogTest, WriteLeader) {
  TestDirGuard g(CreateTestDirGuard());
  ASSIGN_IF_ASSERT_OK(ReplicatedLog::New(options), replicatedLog);

  while (replicatedLog->GetInfo().currentTerm != 1) {
    sleep(1);
  }

  for (int i = 0; i < 4; i++) {
    Status s = replicatedLog->Write("abc");
    ASSERT_OK(s);
  }

  ASSERT_EQ(replicatedLog->GetInfo().logIndex, 5);
  ASSERT_EQ(replicatedLog->GetInfo().commitIndex, 5);
  ASSERT_EQ(replicatedLog->GetInfo().currentTerm, 1);
  ASSERT_EQ(replicatedLog->GetInfo().currentLeader, 1);
}


text:
package com.stripe.model;

public class ProductSearchResult extends StripeSearchResult<Product> {}


text:
#ifndef vnsw_agent_vrouter_uve_entry_h
#define vnsw_agent_vrouter_uve_entry_h

#include <uve/vrouter_uve_entry_base.h>
#include <uve/agent_uve_stats.h>

//The class that defines data-structures to store VRouter information
//required for sending VRouter UVE.
class VrouterUveEntry : public VrouterUveEntryBase {
public:
    typedef std::map<std::string, RouteTableSize> RouteTableSizeMap;
    typedef std::pair<std::string, RouteTableSize> RouteTableSizePair;
    typedef boost::shared_ptr<RouteTableSizeMap> RouteTableSizeMapPtr;

    VrouterUveEntry(Agent *agent);
    virtual ~VrouterUveEntry();
    L4PortBitmap port_bitmap() { return port_bitmap_; }

    virtual bool SendVrouterMsg();
    void SendVrouterControlStats();
    void UpdateBitmap(uint8_t proto, uint16_t sport, uint16_t dport);

protected:
    uint8_t bandwidth_count_;
    L4PortBitmap port_bitmap_;
    FlowRateComputeInfo flow_info_;
private:
    void DispatchVrouterControlStats(const VrouterControlStats &uve) const;
    void InitPrevStats() const;
    void FetchDropStats(AgentDropStats &ds) const;
    bool SetVrouterPortBitmap(VrouterStatsAgent &vr_stats);
    uint64_t CalculateBandwitdh(uint64_t bytes, int speed_mbps,
                               int diff_seconds, double *utilization_bps) const;
    uint64_t GetBandwidthUsage(StatsManager::InterfaceStats *s,
                              bool dir_in, int mins, double *util) const;
    bool BuildPhysicalInterfaceBandwidth(std::vector<AgentIfBandwidth> &list,
                                         uint8_t mins) const;
    bool BuildPhysicalInterfaceBandwidth(map<string,uint64_t> &imp,
                                         map<string,uint64_t> &omp,
                                         uint8_t mins, double &in_util,
                                         double &out_util) const;
    bool BuildPhysicalInterfaceFlowRate(std::map<std::string,
                                        VrouterFlowRate> *rate) const;
    bool BuildPhysicalInterfaceList(std::map<std::string, PhyIfStats> &list,
                                    std::map<std::string, PhyIfInfo> &info,
                                    std::map<std::string, AgentDropStats> &dsmap) const;
    std::string GetMacAddress(const MacAddress &mac) const;
    void BuildXmppStatsList(std::map<std::string, AgentXmppStats> *stats) const;
    void FetchIFMapStats(AgentUve::DerivedStatsMap *ds) const;
    void VrfWalkDone(DBTableBase *base, RouteTableSizeMapPtr list);
    bool AppendVrf(DBTablePartBase *part, DBEntryBase *entry,
                   RouteTableSizeMapPtr list);
    bool StartVrfWalk();
    void BuildAndSendVrouterControlStats(RouteTableSizeMapPtr list);

    uint64_t start_time_;
    DBTableWalker::WalkId vrf_walk_id_;
    DISALLOW_COPY_AND_ASSIGN(VrouterUveEntry);
};

#endif // vnsw_agent_vrouter_uve_entry_h