text:
<?xml version="1.0" encoding="UTF-8"?>

<TEI xmlns="http://www.tei-c.org/ns/1.0" xml:base="http://digital-archiv.at:8081/exist/rest/db/files/thun/xml/" xml:id="diepenbrock-an-thun_1850-06-04_A3-XXI-D70a.xml">
    <teiHeader>
        <fileDesc>
            <titleStmt>
                <title>
                    <persName key="diepenbrock-melchior" role="sender:kleriker">Melchior
                        Diepenbrock</persName> an <persName key="thun-hohenstein-leo" role="recipient">Leo Thun</persName>
                    <lb/>
                    <placeName>Breslau</placeName>,
                        <date when="1850-06-04">4. Juni 1850</date>
                </title>
            </titleStmt>
            <publicationStmt>

            </publicationStmt>
            <sourceDesc>
                <msDesc>
                    <msIdentifier>
                        <institution>Staatliches Gebietsarchiv Leitmeritz, Zweigstelle
                            Tetschen-Bodenbach</institution>
                        <repository>Familienarchiv Thun-Hohenstein, Linie Tetschen, Nachlass Leo
                            Thun</repository>
                        <idno>A3 XXI D70</idno>
                    </msIdentifier>
                    <msContents>

Melchior Diepenbrock dankt für das Vertrauen, das Leo Thun ihm bei der
                            Suche nach fähigen Kandidaten für Lehrerstellen entgegengebracht hatte
                            und ist vollkommen damit einverstanden, dass der Minister noch weitere
                            Erkundigungen einholen will. Diepenbrock kann diesen Schritt umso mehr
                            verstehen, als die Auswahl der richtigen Lehrpersonen, eine wesentliche
                            Vorrausssetzung für den Aufschwung des Unterrichtswesens in Österreich
                            bilde. Im zweiten Teil des Briefs bedankt sich Diepenbrock für die Hilfe
                            für Albert Koch. Thun hatte sich nämlich bereit erklärt, Koch bei der
                            Suche nach einem geeigneten Ort für die Ausstellung des von Koch
                            entdeckten Skeletts einer urzeitlichen Wasserschlange behilflich zu
                            sein. Diepenbrock verspricht sich von der Ausstellung nicht nur
                            wissenschaftliche Erkenntnisse, sondern vor allem biete das Skelett auch
                            einen Beweis für den mosaischen Schöpfungsbericht und könne daher auch
                            ungläubige Betrachter zum Glauben bekehren. Zuletzt empfiehlt
                            Diepenbrock nochmals Franz Schmölders und Karl Grysar.

                    </msContents>
                    <physDesc>

Unter dieser Signatur sind noch zwei weitere Briefe Diepenbrocks an Thun
                                abgelegt:<lb/>
                            <ref target="thun/thun-korrespondenz/tetschen/diepenbrock-an-thun_1850-05-28_A3-XXI-D70.xml">Melchior Diepenbrock an Leo Thun. Breslau, 28. Mai
                                1850</ref>.<lb/>
                            <ref target="thun/thun-korrespondenz/tetschen/diepenbrock-an-thun_1850-08-27_A3-XXI-D70b.xml">Melchior Diepenbrock an Leo Thun. Johannesberg bei Jauernig, 27.
                                August 1850</ref>.

                    </physDesc>
                </msDesc>
            </sourceDesc>
        </fileDesc>
        <revisionDesc docStatus="approved"/>
    </teiHeader>
    <text>

                <index>
                    <term>Personalfragen</term>
                    <term>Personalvermittlung</term>
                    <term>Gymnasien</term>
                </index>

Breslau, den 4. Juni 1850

Eurer Excellenz

geehrtes Schreiben vom 1. dieses Monats will ich vor allem mit der aufrichtigsten
                    Versicherung beantworten, daß es mir nicht nur nicht unangenehm, sondern
                    vielmehr im allerhöchsten Grade erwünscht ist, wenn Hochdieselben über die
                    Personalvorschläge, welche Ihr Vertrauen mir zu machen gestattet, auch noch
                    anderweitige Erkundigungen einziehen. Die hohe Verantwortlichkeit Ihrer Stellung
                    fordert dies, und auch meine individuelle Verantwortlichkeit wird dadurch
                    erleichtert, was mir um so beruhigender, da ich doch nur wenige der genannten
                    Personen selbst kenne und mich also auch auf fremdes Urtheil verlassen muß.
                    Herrn Geheimer Rat <persName key="brueggemann-theodor">Brüggemanns</persName>
                    frühere Äußerung, auf welche Eure Excellenz zurückdeuten, scheint mir auch durch
                    etwas anderes veranlaßt, als durch diese sich von selbst verstehende, durch sich
                    selbst gerechtfertigte Sorgfalt für möglichst zuverlässige, also möglichst
                    vielseitige Renseignements. Ich meines Theils bitte Eure Excellenz hiermit
                    förmlich, neben den von mir gegebenen, noch alle sonst erreichbaren
                    Erkundigungen einziehen und meine Daten nur als unmaßgebliche Fingerzeige
                    ansehen zu wollen. Ich begreife vollkommen die großen Schwierigkeiten, welche
                    Eurer Excellenz auf dem Wege zur Regeneration des Studienwesens überall im Wege
                    liegen, und wievielerlei Rücksichten da nothwendig werden, um nur das Mögliche
                    zu erreichen und nicht am Unmöglichen zu scheitern.<lb/>Herr <persName key="koch-albert-carl">Dr. Koch</persName> war über die gnädige ihn und
                    seinen antediluvianischen Pflegling Hydrarchus Zeuglodon betreffende Zusicherung
                    Eurer Excellenz sehr erfreut und bittet mich, seinen respectvollsten Dank dafür
                    auszudrücken. Nach Beendigung des Wollmarktes, mit Ende dieses Monats, wünscht
                    er allerdings, seine Wanderung nach <placeName>Wien</placeName> antreten zu
                    können. Daß der Anblick dieses Riesenskeletts aus einer vorfluthlichen Thierwelt
                    geeignet ist, ernste Gedanken auch in den ungläubigsten Beschauern
                    hervorzubringen, zumal Herrn <persName key="koch-albert-carl">Dr.
                        Kochs</persName> fachkundige Erklärungen auf einer entschieden gläubigen
                    Harmonie mit dem mosaischen Schöpfungsberichte beruhen, davon hat sein
                    hie[si]ger Aufenthalt viele sehr auffallende Beweise geliefert, und schon aus
                    diesem Grunde möchte ich wünschen, daß er wie ein anderer Prophet Jonas aus dem
                    Bauche seines versteinerten Meerungeheuers auch den Wiener Niniviten seine in
                    fossiler Lapidarschrift geschriebene Predigt von den Wundern Gottes vorhalte.
                    Ich erlaube mir daher, die baldige Erfüllung seines Wunsches hinsichtlich der
                    Einräumung eines passenden Locales Eurer Excellenz nochmals ergebenst zu
                    empfehlen. Hier hatte ihm <persName key="henckel-von-donnersmark-carl-lazarus">Graf Henckel-Donnersmark</persName> seine geräumige Reitbahn eingeräumt;
                    sollte nicht in <placeName>Wien</placeName> irgendein grosser Herr ein ähnliches
                    Local für kurze Zeit zu einem Tempel der Wissenschaft zu weihen sich bestimmen
                    lassen?<lb/>Wenn mein Hirtenbrief nach Ihrer freundlichen Versicherung einigen
                    guten Eindruck gemacht hat, so habe ich Eurer Excellenz zunächst dafür zu
                    danken, da Ihr werthes Vertrauen mich zunächst zu dessen rechtzeitiger Erlassung
                    veranlaßt hat.<lb/>Über den <persName key="grysar-karl">Prof. Grysar</persName>
                    in <placeName key="koeln">Cöln</placeName> habe ich soeben den <persName key="schmoelders-franz-august">Prof. Dr. Schmölders</persName>, der ihn
                    genau kennt, befragt und von ihm erfahren, daß er ein ganz ausgezeichneter
                    Latinist, ein sehr wackerer Mann, tüchtiger Pädagog, jedoch etwas eigensinnig
                    und wenn auch nicht gerade sehr eifrig und prononcirt kirchlich, doch auch gewiß
                    kein schlechter Katholik und als Professor jedenfalls sehr empfehlenswürdig
                    sey.<lb/>Ich erlaube mir hierbei den <persName key="schmoelders-franz-august">Dr. Schmölders</persName> selbst nochmals zu empfehlen, dessen ruhiges,
                    besonnenes, bescheidenes und durchaus tüchtiges Wesen und einnehmende
                    Persönlichkeit ihn gewiß zu einer höchst schätzungswerthen Acquisition für
                        <country key="oesterreich">Österreich</country> machen würde.<lb/>Ich
                    schließe mit der erneuerten Versicherung ausgezeichnetster Hochachtung.

Eurer Excellenz

ergebenster Diener<lb/>Melchior Fb.

    </text>
</TEI>


text:
<meta charset="UTF-8">
<title>ActivityReference.initialize - RichUtils</title>
<link rel="stylesheet" href="../../../style.css">

RichUtils / pyxis.uzuki.live.richutilskt.module.reference / ActivityReference / initialize

initialize

@JvmStatic fun initialize(application: Application): Unit

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Proc. Calif. Acad. Sci. ser. 2, 5:663. 1895 "<I>leibergi</I>"

#### Original name
null

### Remarks
null


text:
namespace llvm {
namespace msf {

template <class StreamType, class RefType> class StreamRefBase {
public:
  StreamRefBase() : Stream(nullptr), ViewOffset(0), Length(0) {}
  StreamRefBase(const StreamType &Stream, uint32_t Offset, uint32_t Length)
      : Stream(&Stream), ViewOffset(Offset), Length(Length) {}

  uint32_t getLength() const { return Length; }
  const StreamType *getStream() const { return Stream; }

  RefType drop_front(uint32_t N) const {
    if (!Stream)
      return RefType();

    N = std::min(N, Length);
    return RefType(*Stream, ViewOffset + N, Length - N);
  }

  RefType keep_front(uint32_t N) const {
    if (!Stream)
      return RefType();
    N = std::min(N, Length);
    return RefType(*Stream, ViewOffset, N);
  }

  RefType slice(uint32_t Offset, uint32_t Len) const {
    return drop_front(Offset).keep_front(Len);
  }

  bool operator==(const RefType &Other) const {
    if (Stream != Other.Stream)
      return false;
    if (ViewOffset != Other.ViewOffset)
      return false;
    if (Length != Other.Length)
      return false;
    return true;
  }

protected:
  const StreamType *Stream;
  uint32_t ViewOffset;
  uint32_t Length;
};

class ReadableStreamRef
    : public StreamRefBase<ReadableStream, ReadableStreamRef> {
public:
  ReadableStreamRef() = default;
  ReadableStreamRef(const ReadableStream &Stream)
      : StreamRefBase(Stream, 0, Stream.getLength()) {}
  ReadableStreamRef(const ReadableStream &Stream, uint32_t Offset,
                    uint32_t Length)
      : StreamRefBase(Stream, Offset, Length) {}

  // Use StreamRef.slice() instead.
  ReadableStreamRef(const ReadableStreamRef &S, uint32_t Offset,
                    uint32_t Length) = delete;

  Error readBytes(uint32_t Offset, uint32_t Size,
                  ArrayRef<uint8_t> &Buffer) const {
    if (ViewOffset + Offset < Offset)
      return make_error<MSFError>(msf_error_code::insufficient_buffer);
    if (Size + Offset > Length)
      return make_error<MSFError>(msf_error_code::insufficient_buffer);
    return Stream->readBytes(ViewOffset + Offset, Size, Buffer);
  }

  // Given an offset into the stream, read as much as possible without copying
  // any data.
  Error readLongestContiguousChunk(uint32_t Offset,
                                   ArrayRef<uint8_t> &Buffer) const {
    if (Offset >= Length)
      return make_error<MSFError>(msf_error_code::insufficient_buffer);

    if (auto EC = Stream->readLongestContiguousChunk(Offset, Buffer))
      return EC;
    // This StreamRef might refer to a smaller window over a larger stream.  In
    // that case we will have read out more bytes than we should return, because
    // we should not read past the end of the current view.
    uint32_t MaxLength = Length - Offset;
    if (Buffer.size() > MaxLength)
      Buffer = Buffer.slice(0, MaxLength);
    return Error::success();
  }
};

class WritableStreamRef
    : public StreamRefBase<WritableStream, WritableStreamRef> {
public:
  WritableStreamRef() = default;
  WritableStreamRef(const WritableStream &Stream)
      : StreamRefBase(Stream, 0, Stream.getLength()) {}
  WritableStreamRef(const WritableStream &Stream, uint32_t Offset,
                    uint32_t Length)
      : StreamRefBase(Stream, Offset, Length) {}

  // Use StreamRef.slice() instead.
  WritableStreamRef(const WritableStreamRef &S, uint32_t Offset,
                    uint32_t Length) = delete;

  Error writeBytes(uint32_t Offset, ArrayRef<uint8_t> Data) const {
    if (Data.size() + Offset > Length)
      return make_error<MSFError>(msf_error_code::insufficient_buffer);
    return Stream->writeBytes(ViewOffset + Offset, Data);
  }

  Error commit() const { return Stream->commit(); }
};

} // end namespace msf
} // end namespace llvm

#endif // LLVM_DEBUGINFO_MSF_STREAMREF_H


text:
from flask.ext import restful
from service import app

from .json import output_json

class Api(restful.Api):
    def __init__(self, *args, **kwargs):
        super(Api, self).__init__(*args, **kwargs)
        self.representations = {
            'application/json': output_json,
            #####################################
            # Disable following representations
            #
            # 'application/xml': output_xml,
            # 'text/html': output_html,
            # 'text/csv': output_csv,
        }

api = Api(app)

from .user import UserApi
from .hello_world import HelloWorld

api.add_resource(UserApi, '/users/<string:uid>')


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _09.TopFiftySequenceMembers
{
    internal static class StartUp
    {
        static void Main()
        {
            Console.Write("Enter N: ");
            int number = int.Parse(Console.ReadLine());

            Queue<int> queue = new Queue<int>();

                queue.Enqueue(number);
            for (int i = 0; i < 50; i++)
            {
                number = queue.Dequeue();
                Console.WriteLine(number);
                queue.Enqueue(number + 1);
                queue.Enqueue(2 * number + 1);
                queue.Enqueue(number + 2);

            }

        }
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindSymbols.Finders;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.ChangeSignature
{
    /// <summary>
    /// For ChangeSignature, FAR on a delegate invoke method must cascade to BeginInvoke,
    /// cascade through method group conversions, and discover implicit invocations that do not
    /// mention the string "Invoke" or the delegate type itself. This implementation finds these
    /// symbols by binding most identifiers and invocation expressions in the solution.
    /// </summary>
    /// <remarks>
    /// TODO: Rewrite this to track backward through references instead of binding everything
    /// </remarks>
    internal class DelegateInvokeMethodReferenceFinder : AbstractReferenceFinder<IMethodSymbol>
    {
        public static readonly IReferenceFinder DelegateInvokeMethod = new DelegateInvokeMethodReferenceFinder();

        protected override bool CanFind(IMethodSymbol symbol)
        {
            return symbol.MethodKind == MethodKind.DelegateInvoke;
        }

        protected override async Task<ImmutableArray<SymbolAndProjectId>> DetermineCascadedSymbolsAsync(
            SymbolAndProjectId<IMethodSymbol> symbolAndProjectId,
            Solution solution,
            IImmutableSet<Project> projects,
            CancellationToken cancellationToken)
        {
            var result = ImmutableArray.CreateBuilder<SymbolAndProjectId>();

            var symbol = symbolAndProjectId.Symbol;
            var beginInvoke = symbol.ContainingType.GetMembers(WellKnownMemberNames.DelegateBeginInvokeName).FirstOrDefault();
            if (beginInvoke != null)
            {
                result.Add(symbolAndProjectId.WithSymbol(beginInvoke));
            }

            // All method group references
            foreach (var project in solution.Projects)
            {
                foreach (var document in project.Documents)
                {
                    var changeSignatureService = document.GetLanguageService<AbstractChangeSignatureService>();
                    result.AddRange(await changeSignatureService.DetermineCascadedSymbolsFromDelegateInvoke(
                        symbolAndProjectId, document, cancellationToken).ConfigureAwait(false));
                }
            }

            return result.ToImmutable();
        }

        protected override Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync(
            IMethodSymbol symbol,
            Project project,
            IImmutableSet<Document> documents,
            CancellationToken cancellationToken)
        {
            return Task.FromResult(project.Documents.ToImmutableArray());
        }

        protected override async Task<ImmutableArray<ReferenceLocation>> FindReferencesInDocumentAsync(
            IMethodSymbol methodSymbol,
            Document document,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            // FAR on the Delegate type and use those results to find Invoke calls

            var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>();

            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var nodes = root.DescendantNodes();

            var convertedAnonymousFunctions = nodes.Where(n => syntaxFactsService.IsAnonymousFunction(n))
                .Where(n =>
                    {
                        ISymbol convertedType = semanticModel.GetTypeInfo(n, cancellationToken).ConvertedType;

                        if (convertedType != null)
                        {
                            convertedType =
                                SymbolFinder.FindSourceDefinitionAsync(convertedType, document.Project.Solution, cancellationToken).WaitAndGetResult(cancellationToken)
                                    ?? convertedType;
                        }

                        return convertedType == methodSymbol.ContainingType;
                    });

            var invocations = nodes.Where(n => syntaxFactsService.IsInvocationExpression(n))
                .Where(e => semanticModel.GetSymbolInfo(e, cancellationToken).Symbol.OriginalDefinition == methodSymbol);

            var result = invocations.Concat(convertedAnonymousFunctions).Select(
                e => new ReferenceLocation(document, null, e.GetLocation(), isImplicit: false, isWrittenTo: false, candidateReason: CandidateReason.None));

            return result.ToImmutableArray();
        }
    }
}


text:
<?php
/**
 * Mega Man RPG Fotress-Battle Mission
 *
The fortress mission class for the Mega Man RPG Prototype.

 */
class rpg_mission_fortress extends rpg_mission {

    public static function prepare(&$this_fortress_battle, $this_prototype_data){

        // Pull in required object indexes
        static $mmrpg_players_index, $mmrpg_robots_index;
        if (empty($mmrpg_players_index)){ $mmrpg_players_index = rpg_player::get_index(true); }
        if (empty($mmrpg_robots_index)){ $mmrpg_robots_index = rpg_robot::get_index(true); }

        // Update the target user ID, player ID, and robot IDs
        $temp_target_user_id = MMRPG_SETTINGS_TARGET_PLAYERID;
        $temp_target_player_id = rpg_game::unique_player_id($temp_target_user_id, 0);
        if ($this_fortress_battle['battle_target_player']['player_token'] !== 'player'){
            $temp_target_player_info = $mmrpg_players_index[$this_fortress_battle['battle_target_player']['player_token']];
            $temp_target_player_id = rpg_game::unique_player_id($temp_target_user_id, $temp_target_player_info['player_id']);
        }
        $temp_battle_target_player = array('user_id' => 0, 'player_id' => 0);
        $this_fortress_battle['battle_target_player'] = array_merge($temp_battle_target_player, $this_fortress_battle['battle_target_player']);
        $this_fortress_battle['battle_target_player']['user_id'] = $temp_target_user_id;
        $this_fortress_battle['battle_target_player']['player_id'] = $temp_target_player_id;

        // Loop through target robots and re-generate unique IDs for each of them
        foreach ($this_fortress_battle['battle_target_player']['player_robots'] AS $key => $robot){
            $temp_target_robot_info = $mmrpg_robots_index[$robot['robot_token']];
            $temp_target_robot_id = rpg_game::unique_robot_id($temp_target_player_id, $temp_target_robot_info['robot_id'], ($key + 1));
            $this_fortress_battle['battle_target_player']['player_robots'][$key]['robot_id'] = $temp_target_robot_id;
        }

        // Calcuate appropriate zenny prizes and turn limits
        rpg_mission::calculate_mission_zenny_and_turns($this_fortress_battle, $this_prototype_data, $mmrpg_robots_index);

    }

}
?>


text:
//===- GlobalCombinerEmitter.cpp - Generate a combiner --------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
/// \file Generate a combiner implementation for GlobalISel from a declarative
/// syntax
///
//===----------------------------------------------------------------------===//

#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ScopedPrinter.h"
#include "llvm/Support/Timer.h"
#include "llvm/TableGen/Error.h"
#include "llvm/TableGen/StringMatcher.h"
#include "llvm/TableGen/TableGenBackend.h"
#include "CodeGenTarget.h"
#include "GlobalISel/CodeExpander.h"
#include "GlobalISel/CodeExpansions.h"
#include "GlobalISel/GIMatchDag.h"
#include "GlobalISel/GIMatchTree.h"
#include <cstdint>

using namespace llvm;

#define DEBUG_TYPE "gicombiner-emitter"

// FIXME: Use ALWAYS_ENABLED_STATISTIC once it's available.
unsigned NumPatternTotal = 0;
STATISTIC(NumPatternTotalStatistic, "Total number of patterns");

cl::OptionCategory
    GICombinerEmitterCat("Options for -gen-global-isel-combiner");
static cl::list<std::string>
    SelectedCombiners("combiners", cl::desc("Emit the specified combiners"),
                      cl::cat(GICombinerEmitterCat), cl::CommaSeparated);
static cl::opt<bool> ShowExpansions(
    "gicombiner-show-expansions",
    cl::desc("Use C++ comments to indicate occurence of code expansion"),
    cl::cat(GICombinerEmitterCat));
static cl::opt<bool> StopAfterParse(
    "gicombiner-stop-after-parse",
    cl::desc("Stop processing after parsing rules and dump state"),
    cl::cat(GICombinerEmitterCat));
static cl::opt<bool> StopAfterBuild(
    "gicombiner-stop-after-build",
    cl::desc("Stop processing after building the match tree"),
    cl::cat(GICombinerEmitterCat));

namespace {
typedef uint64_t RuleID;

// We're going to be referencing the same small strings quite a lot for operand
// names and the like. Make their lifetime management simple with a global
// string table.
StringSet<> StrTab;

StringRef insertStrTab(StringRef S) {
  if (S.empty())
    return S;
  return StrTab.insert(S).first->first();
}

class format_partition_name {
  const GIMatchTree &Tree;
  unsigned Idx;

public:
  format_partition_name(const GIMatchTree &Tree, unsigned Idx)
      : Tree(Tree), Idx(Idx) {}
  void print(raw_ostream &OS) const {
    Tree.getPartitioner()->emitPartitionName(OS, Idx);
  }
};
raw_ostream &operator<<(raw_ostream &OS, const format_partition_name &Fmt) {
  Fmt.print(OS);
  return OS;
}

/// Declares data that is passed from the match stage to the apply stage.
class MatchDataInfo {
  /// The symbol used in the tablegen patterns
  StringRef PatternSymbol;
  /// The data type for the variable
  StringRef Type;
  /// The name of the variable as declared in the generated matcher.
  std::string VariableName;

public:
  MatchDataInfo(StringRef PatternSymbol, StringRef Type, StringRef VariableName)
      : PatternSymbol(PatternSymbol), Type(Type), VariableName(VariableName) {}

  StringRef getPatternSymbol() const { return PatternSymbol; };
  StringRef getType() const { return Type; };
  StringRef getVariableName() const { return VariableName; };
};

class RootInfo {
  StringRef PatternSymbol;

public:
  RootInfo(StringRef PatternSymbol) : PatternSymbol(PatternSymbol) {}

  StringRef getPatternSymbol() const { return PatternSymbol; }
};

class CombineRule {
public:

  using const_matchdata_iterator = std::vector<MatchDataInfo>::const_iterator;

  struct VarInfo {
    const GIMatchDagInstr *N;
    const GIMatchDagOperand *Op;
    const DagInit *Matcher;

  public:
    VarInfo(const GIMatchDagInstr *N, const GIMatchDagOperand *Op,
            const DagInit *Matcher)
        : N(N), Op(Op), Matcher(Matcher) {}
  };

protected:
  /// A unique ID for this rule
  /// ID's are used for debugging and run-time disabling of rules among other
  /// things.
  RuleID ID;

  /// A unique ID that can be used for anonymous objects belonging to this rule.
  /// Used to create unique names in makeNameForAnon*() without making tests
  /// overly fragile.
  unsigned UID = 0;

  /// The record defining this rule.
  const Record &TheDef;

  /// The roots of a match. These are the leaves of the DAG that are closest to
  /// the end of the function. I.e. the nodes that are encountered without
  /// following any edges of the DAG described by the pattern as we work our way
  /// from the bottom of the function to the top.
  std::vector<RootInfo> Roots;

  GIMatchDag MatchDag;

  /// A block of arbitrary C++ to finish testing the match.
  /// FIXME: This is a temporary measure until we have actual pattern matching
  const CodeInit *MatchingFixupCode = nullptr;

  /// The MatchData defined by the match stage and required by the apply stage.
  /// This allows the plumbing of arbitrary data from C++ predicates between the
  /// stages.
  ///
  /// For example, suppose you have:
  ///   %A = <some-constant-expr>
  ///   %0 = G_ADD %1, %A
  /// you could define a GIMatchPredicate that walks %A, constant folds as much
  /// as possible and returns an APInt containing the discovered constant. You
  /// could then declare:
  ///   def apint : GIDefMatchData<"APInt">;
  /// add it to the rule with:
  ///   (defs root:$root, apint:$constant)
  /// evaluate it in the pattern with a C++ function that takes a
  /// MachineOperand& and an APInt& with:
  ///   (match [{MIR %root = G_ADD %0, %A }],
  ///             (constantfold operand:$A, apint:$constant))
  /// and finally use it in the apply stage with:
  ///   (apply (create_operand
  ///                [{ MachineOperand::CreateImm(${constant}.getZExtValue());
  ///                ]}, apint:$constant),
  ///             [{MIR %root = FOO %0, %constant }])
  std::vector<MatchDataInfo> MatchDataDecls;

  void declareMatchData(StringRef PatternSymbol, StringRef Type,
                        StringRef VarName);

  bool parseInstructionMatcher(const CodeGenTarget &Target, StringInit *ArgName,
                               const Init &Arg,
                               StringMap<std::vector<VarInfo>> &NamedEdgeDefs,
                               StringMap<std::vector<VarInfo>> &NamedEdgeUses);
  bool parseWipMatchOpcodeMatcher(const CodeGenTarget &Target,
                                  StringInit *ArgName, const Init &Arg);

public:
  CombineRule(const CodeGenTarget &Target, GIMatchDagContext &Ctx, RuleID ID,
              const Record &R)
      : ID(ID), TheDef(R), MatchDag(Ctx) {}
  CombineRule(const CombineRule &) = delete;

  bool parseDefs();
  bool parseMatcher(const CodeGenTarget &Target);

  RuleID getID() const { return ID; }
  unsigned allocUID() { return UID++; }
  StringRef getName() const { return TheDef.getName(); }
  const Record &getDef() const { return TheDef; }
  const CodeInit *getMatchingFixupCode() const { return MatchingFixupCode; }
  size_t getNumRoots() const { return Roots.size(); }

  GIMatchDag &getMatchDag() { return MatchDag; }
  const GIMatchDag &getMatchDag() const { return MatchDag; }

  using const_root_iterator = std::vector<RootInfo>::const_iterator;
  const_root_iterator roots_begin() const { return Roots.begin(); }
  const_root_iterator roots_end() const { return Roots.end(); }
  iterator_range<const_root_iterator> roots() const {
    return llvm::make_range(Roots.begin(), Roots.end());
  }

  iterator_range<const_matchdata_iterator> matchdata_decls() const {
    return make_range(MatchDataDecls.begin(), MatchDataDecls.end());
  }

  /// Export expansions for this rule
  void declareExpansions(CodeExpansions &Expansions) const {
    for (const auto &I : matchdata_decls())
      Expansions.declare(I.getPatternSymbol(), I.getVariableName());
  }

  /// The matcher will begin from the roots and will perform the match by
  /// traversing the edges to cover the whole DAG. This function reverses DAG
  /// edges such that everything is reachable from a root. This is part of the
  /// preparation work for flattening the DAG into a tree.
  void reorientToRoots() {
    SmallSet<const GIMatchDagInstr *, 5> Roots;
    SmallSet<const GIMatchDagInstr *, 5> Visited;
    SmallSet<GIMatchDagEdge *, 20> EdgesRemaining;

    for (auto &I : MatchDag.roots()) {
      Roots.insert(I);
      Visited.insert(I);
    }
    for (auto &I : MatchDag.edges())
      EdgesRemaining.insert(I);

    bool Progressed = false;
    SmallSet<GIMatchDagEdge *, 20> EdgesToRemove;
    while (!EdgesRemaining.empty()) {
      for (auto EI = EdgesRemaining.begin(), EE = EdgesRemaining.end();
           EI != EE; ++EI) {
        if (Visited.count((*EI)->getFromMI())) {
          if (Roots.count((*EI)->getToMI()))
            PrintError(TheDef.getLoc(), "One or more roots are unnecessary");
          Visited.insert((*EI)->getToMI());
          EdgesToRemove.insert(*EI);
          Progressed = true;
        }
      }
      for (GIMatchDagEdge *ToRemove : EdgesToRemove)
        EdgesRemaining.erase(ToRemove);
      EdgesToRemove.clear();

      for (auto EI = EdgesRemaining.begin(), EE = EdgesRemaining.end();
           EI != EE; ++EI) {
        if (Visited.count((*EI)->getToMI())) {
          (*EI)->reverse();
          Visited.insert((*EI)->getToMI());
          EdgesToRemove.insert(*EI);
          Progressed = true;
        }
        for (GIMatchDagEdge *ToRemove : EdgesToRemove)
          EdgesRemaining.erase(ToRemove);
        EdgesToRemove.clear();
      }

      if (!Progressed) {
        LLVM_DEBUG(dbgs() << "No progress\n");
        return;
      }
      Progressed = false;
    }
  }
};

/// A convenience function to check that an Init refers to a specific def. This
/// is primarily useful for testing for defs and similar in DagInit's since
/// DagInit's support any type inside them.
static bool isSpecificDef(const Init &N, StringRef Def) {
  if (const DefInit *OpI = dyn_cast<DefInit>(&N))
    if (OpI->getDef()->getName() == Def)
      return true;
  return false;
}

/// A convenience function to check that an Init refers to a def that is a
/// subclass of the given class and coerce it to a def if it is. This is
/// primarily useful for testing for subclasses of GIMatchKind and similar in
/// DagInit's since DagInit's support any type inside them.
static Record *getDefOfSubClass(const Init &N, StringRef Cls) {
  if (const DefInit *OpI = dyn_cast<DefInit>(&N))
    if (OpI->getDef()->isSubClassOf(Cls))
      return OpI->getDef();
  return nullptr;
}

/// A convenience function to check that an Init refers to a dag whose operator
/// is a specific def and coerce it to a dag if it is. This is primarily useful
/// for testing for subclasses of GIMatchKind and similar in DagInit's since
/// DagInit's support any type inside them.
static const DagInit *getDagWithSpecificOperator(const Init &N,
                                                 StringRef Name) {
  if (const DagInit *I = dyn_cast<DagInit>(&N))
    if (I->getNumArgs() > 0)
      if (const DefInit *OpI = dyn_cast<DefInit>(I->getOperator()))
        if (OpI->getDef()->getName() == Name)
          return I;
  return nullptr;
}

/// A convenience function to check that an Init refers to a dag whose operator
/// is a def that is a subclass of the given class and coerce it to a dag if it
/// is. This is primarily useful for testing for subclasses of GIMatchKind and
/// similar in DagInit's since DagInit's support any type inside them.
static const DagInit *getDagWithOperatorOfSubClass(const Init &N,
                                                   StringRef Cls) {
  if (const DagInit *I = dyn_cast<DagInit>(&N))
    if (I->getNumArgs() > 0)
      if (const DefInit *OpI = dyn_cast<DefInit>(I->getOperator()))
        if (OpI->getDef()->isSubClassOf(Cls))
          return I;
  return nullptr;
}

StringRef makeNameForAnonInstr(CombineRule &Rule) {
  return insertStrTab(to_string(
      format("__anon%" PRIu64 "_%u", Rule.getID(), Rule.allocUID())));
}

StringRef makeDebugName(CombineRule &Rule, StringRef Name) {
  return insertStrTab(Name.empty() ? makeNameForAnonInstr(Rule) : StringRef(Name));
}

StringRef makeNameForAnonPredicate(CombineRule &Rule) {
  return insertStrTab(to_string(
      format("__anonpred%" PRIu64 "_%u", Rule.getID(), Rule.allocUID())));
}

void CombineRule::declareMatchData(StringRef PatternSymbol, StringRef Type,
                                   StringRef VarName) {
  MatchDataDecls.emplace_back(PatternSymbol, Type, VarName);
}

bool CombineRule::parseDefs() {
  NamedRegionTimer T("parseDefs", "Time spent parsing the defs", "Rule Parsing",
                     "Time spent on rule parsing", TimeRegions);
  DagInit *Defs = TheDef.getValueAsDag("Defs");

  if (Defs->getOperatorAsDef(TheDef.getLoc())->getName() != "defs") {
    PrintError(TheDef.getLoc(), "Expected defs operator");
    return false;
  }

  for (unsigned I = 0, E = Defs->getNumArgs(); I < E; ++I) {
    // Roots should be collected into Roots
    if (isSpecificDef(*Defs->getArg(I), "root")) {
      Roots.emplace_back(Defs->getArgNameStr(I));
      continue;
    }

    // Subclasses of GIDefMatchData should declare that this rule needs to pass
    // data from the match stage to the apply stage, and ensure that the
    // generated matcher has a suitable variable for it to do so.
    if (Record *MatchDataRec =
            getDefOfSubClass(*Defs->getArg(I), "GIDefMatchData")) {
      declareMatchData(Defs->getArgNameStr(I),
                       MatchDataRec->getValueAsString("Type"),
                       llvm::to_string(llvm::format("MatchData%" PRIu64, ID)));
      continue;
    }

    // Otherwise emit an appropriate error message.
    if (getDefOfSubClass(*Defs->getArg(I), "GIDefKind"))
      PrintError(TheDef.getLoc(),
                 "This GIDefKind not implemented in tablegen");
    else if (getDefOfSubClass(*Defs->getArg(I), "GIDefKindWithArgs"))
      PrintError(TheDef.getLoc(),
                 "This GIDefKindWithArgs not implemented in tablegen");
    else
      PrintError(TheDef.getLoc(),
                 "Expected a subclass of GIDefKind or a sub-dag whose "
                 "operator is of type GIDefKindWithArgs");
    return false;
  }

  if (Roots.empty()) {
    PrintError(TheDef.getLoc(), "Combine rules must have at least one root");
    return false;
  }
  return true;
}

// Parse an (Instruction $a:Arg1, $b:Arg2, ...) matcher. Edges are formed
// between matching operand names between different matchers.
bool CombineRule::parseInstructionMatcher(
    const CodeGenTarget &Target, StringInit *ArgName, const Init &Arg,
    StringMap<std::vector<VarInfo>> &NamedEdgeDefs,
    StringMap<std::vector<VarInfo>> &NamedEdgeUses) {
  if (const DagInit *Matcher =
          getDagWithOperatorOfSubClass(Arg, "Instruction")) {
    auto &Instr =
        Target.getInstruction(Matcher->getOperatorAsDef(TheDef.getLoc()));

    StringRef Name = ArgName ? ArgName->getValue() : "";

    GIMatchDagInstr *N =
        MatchDag.addInstrNode(makeDebugName(*this, Name), insertStrTab(Name),
                              MatchDag.getContext().makeOperandList(Instr));

    N->setOpcodeAnnotation(&Instr);
    const auto &P = MatchDag.addPredicateNode<GIMatchDagOpcodePredicate>(
        makeNameForAnonPredicate(*this), Instr);
    MatchDag.addPredicateDependency(N, nullptr, P, &P->getOperandInfo()["mi"]);
    unsigned OpIdx = 0;
    for (const auto &NameInit : Matcher->getArgNames()) {
      StringRef Name = insertStrTab(NameInit->getAsUnquotedString());
      if (Name.empty())
        continue;
      N->assignNameToOperand(OpIdx, Name);

      // Record the endpoints of any named edges. We'll add the cartesian
      // product of edges later.
      const auto &InstrOperand = N->getOperandInfo()[OpIdx];
      if (InstrOperand.isDef()) {
        NamedEdgeDefs.try_emplace(Name);
        NamedEdgeDefs[Name].emplace_back(N, &InstrOperand, Matcher);
      } else {
        NamedEdgeUses.try_emplace(Name);
        NamedEdgeUses[Name].emplace_back(N, &InstrOperand, Matcher);
      }

      if (InstrOperand.isDef()) {
        if (find_if(Roots, [&](const RootInfo &X) {
              return X.getPatternSymbol() == Name;
            }) != Roots.end()) {
          N->setMatchRoot();
        }
      }

      OpIdx++;
    }

    return true;
  }
  return false;
}

// Parse the wip_match_opcode placeholder that's temporarily present in lieu of
// implementing macros or choices between two matchers.
bool CombineRule::parseWipMatchOpcodeMatcher(const CodeGenTarget &Target,
                                             StringInit *ArgName,
                                             const Init &Arg) {
  if (const DagInit *Matcher =
          getDagWithSpecificOperator(Arg, "wip_match_opcode")) {
    StringRef Name = ArgName ? ArgName->getValue() : "";

    GIMatchDagInstr *N =
        MatchDag.addInstrNode(makeDebugName(*this, Name), insertStrTab(Name),
                              MatchDag.getContext().makeEmptyOperandList());

    if (find_if(Roots, [&](const RootInfo &X) {
          return ArgName && X.getPatternSymbol() == ArgName->getValue();
        }) != Roots.end()) {
      N->setMatchRoot();
    }

    const auto &P = MatchDag.addPredicateNode<GIMatchDagOneOfOpcodesPredicate>(
        makeNameForAnonPredicate(*this));
    MatchDag.addPredicateDependency(N, nullptr, P, &P->getOperandInfo()["mi"]);
    // Each argument is an opcode that will pass this predicate. Add them all to
    // the predicate implementation
    for (const auto &Arg : Matcher->getArgs()) {
      Record *OpcodeDef = getDefOfSubClass(*Arg, "Instruction");
      if (OpcodeDef) {
        P->addOpcode(&Target.getInstruction(OpcodeDef));
        continue;
      }
      PrintError(TheDef.getLoc(),
                 "Arguments to wip_match_opcode must be instructions");
      return false;
    }
    return true;
  }
  return false;
}
bool CombineRule::parseMatcher(const CodeGenTarget &Target) {
  NamedRegionTimer T("parseMatcher", "Time spent parsing the matcher",
                     "Rule Parsing", "Time spent on rule parsing", TimeRegions);
  StringMap<std::vector<VarInfo>> NamedEdgeDefs;
  StringMap<std::vector<VarInfo>> NamedEdgeUses;
  DagInit *Matchers = TheDef.getValueAsDag("Match");

  if (Matchers->getOperatorAsDef(TheDef.getLoc())->getName() != "match") {
    PrintError(TheDef.getLoc(), "Expected match operator");
    return false;
  }

  if (Matchers->getNumArgs() == 0) {
    PrintError(TheDef.getLoc(), "Matcher is empty");
    return false;
  }

  // The match section consists of a list of matchers and predicates. Parse each
  // one and add the equivalent GIMatchDag nodes, predicates, and edges.
  for (unsigned I = 0; I < Matchers->getNumArgs(); ++I) {
    if (parseInstructionMatcher(Target, Matchers->getArgName(I),
                                *Matchers->getArg(I), NamedEdgeDefs,
                                NamedEdgeUses))
      continue;

    if (parseWipMatchOpcodeMatcher(Target, Matchers->getArgName(I),
                                   *Matchers->getArg(I)))
      continue;

    // Parse arbitrary C++ code we have in lieu of supporting MIR matching
    if (const CodeInit *CodeI = dyn_cast<CodeInit>(Matchers->getArg(I))) {
      assert(!MatchingFixupCode &&
             "Only one block of arbitrary code is currently permitted");
      MatchingFixupCode = CodeI;
      MatchDag.setHasPostMatchPredicate(true);
      continue;
    }

    PrintError(TheDef.getLoc(),
               "Expected a subclass of GIMatchKind or a sub-dag whose "
               "operator is either of a GIMatchKindWithArgs or Instruction");
    PrintNote("Pattern was `" + Matchers->getArg(I)->getAsString() + "'");
    return false;
  }

  // Add the cartesian product of use -> def edges.
  bool FailedToAddEdges = false;
  for (const auto &NameAndDefs : NamedEdgeDefs) {
    if (NameAndDefs.getValue().size() > 1) {
      PrintError(TheDef.getLoc(),
                 "Two different MachineInstrs cannot def the same vreg");
      for (const auto &NameAndDefOp : NameAndDefs.getValue())
        PrintNote("in " + to_string(*NameAndDefOp.N) + " created from " +
                  to_string(*NameAndDefOp.Matcher) + "");
      FailedToAddEdges = true;
    }
    const auto &Uses = NamedEdgeUses[NameAndDefs.getKey()];
    for (const VarInfo &DefVar : NameAndDefs.getValue()) {
      for (const VarInfo &UseVar : Uses) {
        MatchDag.addEdge(insertStrTab(NameAndDefs.getKey()), UseVar.N, UseVar.Op,
                         DefVar.N, DefVar.Op);
      }
    }
  }
  if (FailedToAddEdges)
    return false;

  // If a variable is referenced in multiple use contexts then we need a
  // predicate to confirm they are the same operand. We can elide this if it's
  // also referenced in a def context and we're traversing the def-use chain
  // from the def to the uses but we can't know which direction we're going
  // until after reorientToRoots().
  for (const auto &NameAndUses : NamedEdgeUses) {
    const auto &Uses = NameAndUses.getValue();
    if (Uses.size() > 1) {
      const auto &LeadingVar = Uses.front();
      for (const auto &Var : ArrayRef<VarInfo>(Uses).drop_front()) {
        // Add a predicate for each pair until we've covered the whole
        // equivalence set. We could test the whole set in a single predicate
        // but that means we can't test any equivalence until all the MO's are
        // available which can lead to wasted work matching the DAG when this
        // predicate can already be seen to have failed.
        //
        // We have a similar problem due to the need to wait for a particular MO
        // before being able to test any of them. However, that is mitigated by
        // the order in which we build the DAG. We build from the roots outwards
        // so by using the first recorded use in all the predicates, we are
        // making the dependency on one of the earliest visited references in
        // the DAG. It's not guaranteed once the generated matcher is optimized
        // (because the factoring the common portions of rules might change the
        // visit order) but this should mean that these predicates depend on the
        // first MO to become available.
        const auto &P = MatchDag.addPredicateNode<GIMatchDagSameMOPredicate>(
            makeNameForAnonPredicate(*this));
        MatchDag.addPredicateDependency(LeadingVar.N, LeadingVar.Op, P,
                                        &P->getOperandInfo()["mi0"]);
        MatchDag.addPredicateDependency(Var.N, Var.Op, P,
                                        &P->getOperandInfo()["mi1"]);
      }
    }
  }
  return true;
}

class GICombinerEmitter {
  StringRef Name;
  const CodeGenTarget &Target;
  Record *Combiner;
  std::vector<std::unique_ptr<CombineRule>> Rules;
  GIMatchDagContext MatchDagCtx;

  std::unique_ptr<CombineRule> makeCombineRule(const Record &R);

  void gatherRules(std::vector<std::unique_ptr<CombineRule>> &ActiveRules,
                   const std::vector<Record *> &&RulesAndGroups);

public:
  explicit GICombinerEmitter(RecordKeeper &RK, const CodeGenTarget &Target,
                             StringRef Name, Record *Combiner);
  ~GICombinerEmitter() {}

  StringRef getClassName() const {
    return Combiner->getValueAsString("Classname");
  }
  void run(raw_ostream &OS);

  /// Emit the name matcher (guarded by #ifndef NDEBUG) used to disable rules in
  /// response to the generated cl::opt.
  void emitNameMatcher(raw_ostream &OS) const;

  void generateDeclarationsCodeForTree(raw_ostream &OS, const GIMatchTree &Tree) const;
  void generateCodeForTree(raw_ostream &OS, const GIMatchTree &Tree,
                           StringRef Indent) const;
};

GICombinerEmitter::GICombinerEmitter(RecordKeeper &RK,
                                     const CodeGenTarget &Target,
                                     StringRef Name, Record *Combiner)
    : Name(Name), Target(Target), Combiner(Combiner) {}

void GICombinerEmitter::emitNameMatcher(raw_ostream &OS) const {
  std::vector<std::pair<std::string, std::string>> Cases;
  Cases.reserve(Rules.size());

  for (const CombineRule &EnumeratedRule : make_pointee_range(Rules)) {
    std::string Code;
    raw_string_ostream SS(Code);
    SS << "return " << EnumeratedRule.getID() << ";\n";
    Cases.push_back(std::make_pair(EnumeratedRule.getName(), SS.str()));
  }

  OS << "static Optional<uint64_t> getRuleIdxForIdentifier(StringRef "
        "RuleIdentifier) {\n"
     << "  uint64_t I;\n"
     << "  // getAtInteger(...) returns false on success\n"
     << "  bool Parsed = !RuleIdentifier.getAsInteger(0, I);\n"
     << "  if (Parsed)\n"
     << "    return I;\n\n"
     << "#ifndef NDEBUG\n";
  StringMatcher Matcher("RuleIdentifier", Cases, OS);
  Matcher.Emit();
  OS << "#endif // ifndef NDEBUG\n\n"
     << "  return None;\n"
     << "}\n";
}

std::unique_ptr<CombineRule>
GICombinerEmitter::makeCombineRule(const Record &TheDef) {
  std::unique_ptr<CombineRule> Rule =
      std::make_unique<CombineRule>(Target, MatchDagCtx, NumPatternTotal, TheDef);

  if (!Rule->parseDefs())
    return nullptr;
  if (!Rule->parseMatcher(Target))
    return nullptr;

  Rule->reorientToRoots();

  LLVM_DEBUG({
    dbgs() << "Parsed rule defs/match for '" << Rule->getName() << "'\n";
    Rule->getMatchDag().dump();
    Rule->getMatchDag().writeDOTGraph(dbgs(), Rule->getName());
  });
  if (StopAfterParse)
    return Rule;

  // For now, don't support traversing from def to use. We'll come back to
  // this later once we have the algorithm changes to support it.
  bool EmittedDefToUseError = false;
  for (const auto &E : Rule->getMatchDag().edges()) {
    if (E->isDefToUse()) {
      if (!EmittedDefToUseError) {
        PrintError(
            TheDef.getLoc(),
            "Generated state machine cannot lookup uses from a def (yet)");
        EmittedDefToUseError = true;
      }
      PrintNote("Node " + to_string(*E->getFromMI()));
      PrintNote("Node " + to_string(*E->getToMI()));
      PrintNote("Edge " + to_string(*E));
    }
  }
  if (EmittedDefToUseError)
    return nullptr;

  // For now, don't support multi-root rules. We'll come back to this later
  // once we have the algorithm changes to support it.
  if (Rule->getNumRoots() > 1) {
    PrintError(TheDef.getLoc(), "Multi-root matches are not supported (yet)");
    return nullptr;
  }
  return Rule;
}

/// Recurse into GICombineGroup's and flatten the ruleset into a simple list.
void GICombinerEmitter::gatherRules(
    std::vector<std::unique_ptr<CombineRule>> &ActiveRules,
    const std::vector<Record *> &&RulesAndGroups) {
  for (Record *R : RulesAndGroups) {
    if (R->isValueUnset("Rules")) {
      std::unique_ptr<CombineRule> Rule = makeCombineRule(*R);
      if (Rule == nullptr) {
        PrintError(R->getLoc(), "Failed to parse rule");
        continue;
      }
      ActiveRules.emplace_back(std::move(Rule));
      ++NumPatternTotal;
    } else
      gatherRules(ActiveRules, R->getValueAsListOfDefs("Rules"));
  }
}

void GICombinerEmitter::generateCodeForTree(raw_ostream &OS,
                                            const GIMatchTree &Tree,
                                            StringRef Indent) const {
  if (Tree.getPartitioner() != nullptr) {
    Tree.getPartitioner()->generatePartitionSelectorCode(OS, Indent);
    for (const auto &EnumChildren : enumerate(Tree.children())) {
      OS << Indent << "if (Partition == " << EnumChildren.index() << " /* "
         << format_partition_name(Tree, EnumChildren.index()) << " */) {\n";
      generateCodeForTree(OS, EnumChildren.value(), (Indent + "  ").str());
      OS << Indent << "}\n";
    }
    return;
  }

  bool AnyFullyTested = false;
  for (const auto &Leaf : Tree.possible_leaves()) {
    OS << Indent << "// Leaf name: " << Leaf.getName() << "\n";

    const CombineRule *Rule = Leaf.getTargetData<CombineRule>();
    const Record &RuleDef = Rule->getDef();

    OS << Indent << "// Rule: " << RuleDef.getName() << "\n"
       << Indent << "if (!isRuleDisabled(" << Rule->getID() << ")) {\n";

    CodeExpansions Expansions;
    for (const auto &VarBinding : Leaf.var_bindings()) {
      if (VarBinding.isInstr())
        Expansions.declare(VarBinding.getName(),
                           "MIs[" + to_string(VarBinding.getInstrID()) + "]");
      else
        Expansions.declare(VarBinding.getName(),
                           "MIs[" + to_string(VarBinding.getInstrID()) +
                               "]->getOperand(" +
                               to_string(VarBinding.getOpIdx()) + ")");
    }
    Rule->declareExpansions(Expansions);

    DagInit *Applyer = RuleDef.getValueAsDag("Apply");
    if (Applyer->getOperatorAsDef(RuleDef.getLoc())->getName() !=
        "apply") {
      PrintError(RuleDef.getLoc(), "Expected apply operator");
      return;
    }

    OS << Indent << "  if (1\n";

    // Attempt to emit code for any untested predicates left over. Note that
    // isFullyTested() will remain false even if we succeed here and therefore
    // combine rule elision will not be performed. This is because we do not
    // know if there's any connection between the predicates for each leaf and
    // therefore can't tell if one makes another unreachable. Ideally, the
    // partitioner(s) would be sufficiently complete to prevent us from having
    // untested predicates left over.
    for (const GIMatchDagPredicate *Predicate : Leaf.untested_predicates()) {
      if (Predicate->generateCheckCode(OS, (Indent + "      ").str(),
                                       Expansions))
        continue;
      PrintError(RuleDef.getLoc(),
                 "Unable to test predicate used in rule");
      PrintNote(SMLoc(),
                "This indicates an incomplete implementation in tablegen");
      Predicate->print(errs());
      errs() << "\n";
      OS << Indent
         << "llvm_unreachable(\"TableGen did not emit complete code for this "
            "path\");\n";
      break;
    }

    if (Rule->getMatchingFixupCode() &&
        !Rule->getMatchingFixupCode()->getValue().empty()) {
      // FIXME: Single-use lambda's like this are a serious compile-time
      // performance and memory issue. It's convenient for this early stage to
      // defer some work to successive patches but we need to eliminate this
      // before the ruleset grows to small-moderate size. Last time, it became
      // a big problem for low-mem systems around the 500 rule mark but by the
      // time we grow that large we should have merged the ISel match table
      // mechanism with the Combiner.
      OS << Indent << "      && [&]() {\n"
         << Indent << "      "
         << CodeExpander(Rule->getMatchingFixupCode()->getValue(), Expansions,
                         Rule->getMatchingFixupCode()->getLoc(), ShowExpansions)
         << "\n"
         << Indent << "      return true;\n"
         << Indent << "  }()";
    }
    OS << ") {\n" << Indent << "   ";

    if (const CodeInit *Code = dyn_cast<CodeInit>(Applyer->getArg(0))) {
      OS << CodeExpander(Code->getAsUnquotedString(), Expansions,
                         Code->getLoc(), ShowExpansions)
         << "\n"
         << Indent << "    return true;\n"
         << Indent << "  }\n";
    } else {
      PrintError(RuleDef.getLoc(), "Expected apply code block");
      return;
    }

    OS << Indent << "}\n";

    assert(Leaf.isFullyTraversed());

    // If we didn't have any predicates left over and we're not using the
    // trap-door we have to support arbitrary C++ code while we're migrating to
    // the declarative style then we know that subsequent leaves are
    // unreachable.
    if (Leaf.isFullyTested() &&
        (!Rule->getMatchingFixupCode() ||
         Rule->getMatchingFixupCode()->getValue().empty())) {
      AnyFullyTested = true;
      OS << Indent
         << "llvm_unreachable(\"Combine rule elision was incorrect\");\n"
         << Indent << "return false;\n";
    }
  }
  if (!AnyFullyTested)
    OS << Indent << "return false;\n";
}

void GICombinerEmitter::run(raw_ostream &OS) {
  gatherRules(Rules, Combiner->getValueAsListOfDefs("Rules"));
  if (StopAfterParse) {
    MatchDagCtx.print(errs());
    PrintNote(Combiner->getLoc(),
              "Terminating due to -gicombiner-stop-after-parse");
    return;
  }
  if (ErrorsPrinted)
    PrintFatalError(Combiner->getLoc(), "Failed to parse one or more rules");
  LLVM_DEBUG(dbgs() << "Optimizing tree for " << Rules.size() << " rules\n");
  std::unique_ptr<GIMatchTree> Tree;
  {
    NamedRegionTimer T("Optimize", "Time spent optimizing the combiner",
                       "Code Generation", "Time spent generating code",
                       TimeRegions);

    GIMatchTreeBuilder TreeBuilder(0);
    for (const auto &Rule : Rules) {
      bool HadARoot = false;
      for (const auto &Root : enumerate(Rule->getMatchDag().roots())) {
        TreeBuilder.addLeaf(Rule->getName(), Root.index(), Rule->getMatchDag(),
                            Rule.get());
        HadARoot = true;
      }
      if (!HadARoot)
        PrintFatalError(Rule->getDef().getLoc(), "All rules must have a root");
    }

    Tree = TreeBuilder.run();
  }
  if (StopAfterBuild) {
    Tree->writeDOTGraph(outs());
    PrintNote(Combiner->getLoc(),
              "Terminating due to -gicombiner-stop-after-build");
    return;
  }

  NamedRegionTimer T("Emit", "Time spent emitting the combiner",
                     "Code Generation", "Time spent generating code",
                     TimeRegions);
  OS << "#ifdef " << Name.upper() << "_GENCOMBINERHELPER_DEPS\n"
     << "#include \"llvm/ADT/SparseBitVector.h\"\n"
     << "namespace llvm {\n"
     << "extern cl::OptionCategory GICombinerOptionCategory;\n"
     << "} // end namespace llvm\n"
     << "#endif // ifdef " << Name.upper() << "_GENCOMBINERHELPER_DEPS\n\n";

  OS << "#ifdef " << Name.upper() << "_GENCOMBINERHELPER_H\n"
     << "class " << getClassName() << " {\n"
     << "  SparseBitVector<> DisabledRules;\n"
     << "\n"
     << "public:\n"
     << "  bool parseCommandLineOption();\n"
     << "  bool isRuleDisabled(unsigned ID) const;\n"
     << "  bool setRuleDisabled(StringRef RuleIdentifier);\n"
     << "\n"
     << "  bool tryCombineAll(\n"
     << "    GISelChangeObserver &Observer,\n"
     << "    MachineInstr &MI,\n"
     << "    MachineIRBuilder &B,\n"
     << "    CombinerHelper &Helper) const;\n"
     << "};\n\n";

  emitNameMatcher(OS);

  OS << "bool " << getClassName()
     << "::setRuleDisabled(StringRef RuleIdentifier) {\n"
     << "  std::pair<StringRef, StringRef> RangePair = "
        "RuleIdentifier.split('-');\n"
     << "  if (!RangePair.second.empty()) {\n"
     << "    const auto First = getRuleIdxForIdentifier(RangePair.first);\n"
     << "    const auto Last = getRuleIdxForIdentifier(RangePair.second);\n"
     << "    if (!First.hasValue() || !Last.hasValue())\n"
     << "      return false;\n"
     << "    if (First >= Last)\n"
     << "      report_fatal_error(\"Beginning of range should be before end of "
        "range\");\n"
     << "    for (auto I = First.getValue(); I < Last.getValue(); ++I)\n"
     << "      DisabledRules.set(I);\n"
     << "    return true;\n"
     << "  } else {\n"
     << "    const auto I = getRuleIdxForIdentifier(RangePair.first);\n"
     << "    if (!I.hasValue())\n"
     << "      return false;\n"
     << "    DisabledRules.set(I.getValue());\n"
     << "    return true;\n"
     << "  }\n"
     << "  return false;\n"
     << "}\n";

  OS << "bool " << getClassName()
     << "::isRuleDisabled(unsigned RuleID) const {\n"
     << "  return DisabledRules.test(RuleID);\n"
     << "}\n";
  OS << "#endif // ifdef " << Name.upper() << "_GENCOMBINERHELPER_H\n\n";

  OS << "#ifdef " << Name.upper() << "_GENCOMBINERHELPER_CPP\n"
     << "\n"
     << "cl::list<std::string> " << Name << "Option(\n"
     << "    \"" << Name.lower() << "-disable-rule\",\n"
     << "    cl::desc(\"Disable one or more combiner rules temporarily in "
     << "the " << Name << " pass\"),\n"
     << "    cl::CommaSeparated,\n"
     << "    cl::Hidden,\n"
     << "    cl::cat(GICombinerOptionCategory));\n"
     << "\n"
     << "bool " << getClassName() << "::parseCommandLineOption() {\n"
     << "  for (const auto &Identifier : " << Name << "Option)\n"
     << "    if (!setRuleDisabled(Identifier))\n"
     << "      return false;\n"
     << "  return true;\n"
     << "}\n\n";

  OS << "bool " << getClassName() << "::tryCombineAll(\n"
     << "    GISelChangeObserver &Observer,\n"
     << "    MachineInstr &MI,\n"
     << "    MachineIRBuilder &B,\n"
     << "    CombinerHelper &Helper) const {\n"
     << "  MachineBasicBlock *MBB = MI.getParent();\n"
     << "  MachineFunction *MF = MBB->getParent();\n"
     << "  MachineRegisterInfo &MRI = MF->getRegInfo();\n"
     << "  SmallVector<MachineInstr *, 8> MIs = { &MI };\n\n"
     << "  (void)MBB; (void)MF; (void)MRI;\n\n";

  OS << "  // Match data\n";
  for (const auto &Rule : Rules)
    for (const auto &I : Rule->matchdata_decls())
      OS << "  " << I.getType() << " " << I.getVariableName() << ";\n";
  OS << "\n";

  OS << "  int Partition = -1;\n";
  generateCodeForTree(OS, *Tree, "  ");
  OS << "\n  return false;\n"
     << "}\n"
     << "#endif // ifdef " << Name.upper() << "_GENCOMBINERHELPER_CPP\n";
}

} // end anonymous namespace

//===----------------------------------------------------------------------===//

namespace llvm {
void EmitGICombiner(RecordKeeper &RK, raw_ostream &OS) {
  CodeGenTarget Target(RK);
  emitSourceFileHeader("Global Combiner", OS);

  if (SelectedCombiners.empty())
    PrintFatalError("No combiners selected with -combiners");
  for (const auto &Combiner : SelectedCombiners) {
    Record *CombinerDef = RK.getDef(Combiner);
    if (!CombinerDef)
      PrintFatalError("Could not find " + Combiner);
    GICombinerEmitter(RK, Target, Combiner, CombinerDef).run(OS);
  }
  NumPatternTotalStatistic = NumPatternTotal;
}

} // namespace llvm


text:
The 0.2.2 release includes the following:

* SLF4J logging


text:
#include <QtScript>

#include <iostream>

static QString readFile(const QString &fileName)
{
    QFile file;
    file.setFileName(fileName);
    if (!file.open(QFile::ReadOnly)) {
        std::cerr << "Can't open" << qPrintable(fileName) << std::endl;
        return QString();
    }
    QString content = file.readAll();
    file.close();
    return content;
}

int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);

    if (argc < 2) {
        std::cout << "Usage:" << std::endl << std::endl;
        std::cout << "    jsbeautify source-file" << std::endl << std::endl;
        return 0;
    }

    QString script = readFile(":/beautify.js");
    QString source = readFile(QString::fromLocal8Bit(argv[1]));

    if (!script.isEmpty() && !source.isEmpty()) {
        QScriptEngine engine;
        engine.evaluate(script);
        engine.globalObject().setProperty("source", QScriptValue(source));
        QScriptValue result = engine.evaluate("js_beautify(source);");
        std::cout << qPrintable(result.toString()) << std::endl;
    }

    return 0;
}


text:
from neutron.api import extensions as neutron_extensions
from neutron.plugins.ml2 import driver_api as api

from baremetal_network_provisioning.ml2 import extensions

from oslo_log import log as logging

LOG = logging.getLogger(__name__)

class HPEIronicExtensionDriver(api.ExtensionDriver):
    _supported_extension_aliases = 'bnp-switch'

    def initialize(self):
        neutron_extensions.append_api_extensions_path(extensions.__path__)
        LOG.info(_("HPEIronicExtensionDriver initialization complete"))

    @property
    def extension_alias(self):
        """Supported extension alias.

        identifying the core API extension supported
                  by this BNP driver
        """
        return self._supported_extension_aliases


text:
You are seeing the relations page of the API Builder. You can add, edit or
remove relations between your APIs.

## What is a relation?

A relation is such as a join/link between two APIs. For example, if
you have a `Article` API and a `Comment` API, your article can have many
comments. So, you need to link your API `Article` with your API `Comment`.
We called this a "relation".

## How to fill out the fields?

### Relations

@@ This is the list of your relations for your API.

This is the list of your relations for your API. For example, if you add a
`comments` key, this will create a new relation with the selected API in the
settings part.

For developers: The name of your relation will be a new key in your model's
API, and the relation key will be a new key in the other model's API.

### Settings

#### Type

@@ Please read the sentence beside

There are different kind of relations. Take time to read the sentence beside
this input..

#### API

@@ Select the API which must be linked with your current API

This input targets the API which must be linked.

#### Relation key

@@ This input value will be the name of the key created in the API selected above.

This input value will be the name of the key created in the API selected above.


text:
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Diagnostics;
using ALinq.Mapping;
using ALinq.SqlClient;

namespace ALinq.Access
{
    class AccessParameterizer //: SqlParameterizerBase
        : ISqlParameterizer
    {
        // Fields
        private readonly SqlNodeAnnotations annotations;
        private int index;
        internal readonly ITypeSystemProvider typeProvider;

        // Methods
        internal AccessParameterizer(ITypeSystemProvider typeProvider, SqlNodeAnnotations annotations)
        {
            this.typeProvider = typeProvider;
            this.annotations = annotations;
        }

        ReadOnlyCollection<SqlParameterInfo> ISqlParameterizer.Parameterize(SqlNode node)
        {
            return ParameterizeInternal(node).AsReadOnly();
        }

        ReadOnlyCollection<ReadOnlyCollection<SqlParameterInfo>> ISqlParameterizer.ParameterizeBlock(SqlBlock block)
        {
            //var item = new SqlParameterInfo(new SqlParameter(typeof(int), typeProvider.From(typeof(int)),
            //                                                 "@ROWCOUNT", block.SourceExpression));
            var list = new List<ReadOnlyCollection<SqlParameterInfo>>();
            int num = 0;
            int count = block.Statements.Count;
            while (num < count)
            {
                SqlNode node = block.Statements[num];
                List<SqlParameterInfo> list2 = this.ParameterizeInternal(node);
                if (num > 0)
                {
                    //list2.Add(item);
                }
                list.Add(list2.AsReadOnly());
                num++;
            }
            return list.AsReadOnly();
        }

        ITypeSystemProvider ISqlParameterizer.TypeProvider
        {
            get { return typeProvider; }
        }

        SqlNodeAnnotations ISqlParameterizer.Annotations
        {
            get { return annotations; }
        }

        private List<SqlParameterInfo> ParameterizeInternal(SqlNode node)
        {
            var visitor = new Visitor(this);
            visitor.Visit(node);
            return new List<SqlParameterInfo>(visitor.currentParams);
        }

        class Visitor : SqlParameterizer.Visitor
        {
            internal Visitor(ISqlParameterizer parameterizer)
                : base(parameterizer)
            {
            }

            internal override SqlStoredProcedureCall VisitStoredProcedureCall(SqlStoredProcedureCall spc)
            {
                this.VisitUserQuery(spc);
                int num = 0;
                int count = spc.Function.Parameters.Count;
                while (num < count)
                {
                    MetaParameter p = spc.Function.Parameters[num];
                    var node = spc.Arguments[num] as SqlParameter;
                    if (node != null)
                    {
                        node.Direction = GetParameterDirection(p);
                        Debug.Assert(!string.IsNullOrEmpty(p.MappedName));
                        node.Name = p.MappedName;
                        if ((node.Direction == ParameterDirection.InputOutput) ||
                            (node.Direction == ParameterDirection.Output))
                        {
                            RetypeOutParameter(node);
                        }
                    }
                    num++;
                }
                //var parameter3 = new SqlParameter(typeof(int?),
                //                                  parameterizer.TypeProvider.From(typeof(int)),
                //                                  "@RETURN_VALUE", spc.SourceExpression) { Direction = ParameterDirection.Input };
                //this.currentParams.Add(new SqlParameterInfo(parameter3));
                return spc;
            }

            internal override SqlStatement VisitUpdate(SqlUpdate sup)
            {
                bool topLevel = this.topLevel;
                this.topLevel = false;

                int num = 0;
                int count = sup.Assignments.Count;
                while (num < count)
                {
                    sup.Assignments[num] = (SqlAssign)Visit(sup.Assignments[num]);
                    num++;
                }
                sup.Select = VisitSequence(sup.Select);

                this.topLevel = topLevel;
                return sup;
            }

            internal override SqlSelect VisitSelect(SqlSelect select)
            {
                bool topLevel = this.topLevel;
                this.topLevel = false;

                select.Top = this.VisitExpression(select.Top);
                select.Row = (SqlRow)this.Visit(select.Row);

                select.From = (SqlSource)this.Visit(select.From);
                select.Where = this.VisitExpression(select.Where);
                int num = 0;
                int count = select.GroupBy.Count;
                while (num < count)
                {
                    select.GroupBy[num] = this.VisitExpression(select.GroupBy[num]);
                    num++;
                }
                select.Having = this.VisitExpression(select.Having);
                int num3 = 0;
                int num4 = select.OrderBy.Count;
                while (num3 < num4)
                {
                    select.OrderBy[num3].Expression = this.VisitExpression(select.OrderBy[num3].Expression);
                    num3++;
                }

                this.topLevel = topLevel;
                select.Selection = this.VisitExpression(select.Selection);
                return select;
            }
        }
    }
}


text:
import {CompileDirectiveMetadata, CompileDirectiveSummary, CompileNgModuleMetadata, CompileNgModuleSummary, CompilePipeMetadata, CompileProviderMetadata, CompileSummaryKind, CompileTypeMetadata, CompileTypeSummary} from '../compile_metadata';
import * as o from '../output/output_ast';
import {Summary, SummaryResolver} from '../summary_resolver';
import {OutputContext, ValueTransformer, ValueVisitor, visitValue} from '../util';

import {StaticSymbol, StaticSymbolCache} from './static_symbol';
import {ResolvedStaticSymbol, StaticSymbolResolver} from './static_symbol_resolver';
import {summaryForJitFileName, summaryForJitName} from './util';

export function serializeSummaries(
    srcFileName: string, forJitCtx: OutputContext | null,
    summaryResolver: SummaryResolver<StaticSymbol>, symbolResolver: StaticSymbolResolver,
    symbols: ResolvedStaticSymbol[], types: {
      summary: CompileTypeSummary,
      metadata: CompileNgModuleMetadata | CompileDirectiveMetadata | CompilePipeMetadata |
          CompileTypeMetadata
    }[]): {json: string, exportAs: {symbol: StaticSymbol, exportAs: string}[]} {
  const toJsonSerializer = new ToJsonSerializer(symbolResolver, summaryResolver, srcFileName);

  // for symbols, we use everything except for the class metadata itself
  // (we keep the statics though), as the class metadata is contained in the
  // CompileTypeSummary.
  symbols.forEach(
      (resolvedSymbol) => toJsonSerializer.addSummary(
          {symbol: resolvedSymbol.symbol, metadata: resolvedSymbol.metadata}));

  // Add type summaries.
  types.forEach(({summary, metadata}) => {
    toJsonSerializer.addSummary(
        {symbol: summary.type.reference, metadata: undefined, type: summary});
  });
  const {json, exportAs} = toJsonSerializer.serialize();
  if (forJitCtx) {
    const forJitSerializer = new ForJitSerializer(forJitCtx, symbolResolver);
    types.forEach(({summary, metadata}) => { forJitSerializer.addSourceType(summary, metadata); });
    toJsonSerializer.unprocessedSymbolSummariesBySymbol.forEach((summary) => {
      if (summaryResolver.isLibraryFile(summary.symbol.filePath) && summary.type) {
        forJitSerializer.addLibType(summary.type);
      }
    });
    forJitSerializer.serialize(exportAs);
  }
  return {json, exportAs};
}

export function deserializeSummaries(
    symbolCache: StaticSymbolCache, summaryResolver: SummaryResolver<StaticSymbol>,
    libraryFileName: string, json: string): {
  moduleName: string | null,
  summaries: Summary<StaticSymbol>[],
  importAs: {symbol: StaticSymbol, importAs: string}[]
} {
  const deserializer = new FromJsonDeserializer(symbolCache, summaryResolver);
  return deserializer.deserialize(libraryFileName, json);
}

export function createForJitStub(outputCtx: OutputContext, reference: StaticSymbol) {
  return createSummaryForJitFunction(outputCtx, reference, o.NULL_EXPR);
}

function createSummaryForJitFunction(
    outputCtx: OutputContext, reference: StaticSymbol, value: o.Expression) {
  const fnName = summaryForJitName(reference.name);
  outputCtx.statements.push(
      o.fn([], [new o.ReturnStatement(value)], new o.ArrayType(o.DYNAMIC_TYPE)).toDeclStmt(fnName, [
        o.StmtModifier.Final, o.StmtModifier.Exported
      ]));
}

const enum SerializationFlags {
  None = 0,
  ResolveValue = 1,
}

class ToJsonSerializer extends ValueTransformer {
  // Note: This only contains symbols without members.
  private symbols: StaticSymbol[] = [];
  private indexBySymbol = new Map<StaticSymbol, number>();
  // This now contains a `__symbol: number` in the place of
  // StaticSymbols, but otherwise has the same shape as the original objects.
  private processedSummaryBySymbol = new Map<StaticSymbol, any>();
  private processedSummaries: any[] = [];
  private moduleName: string|null;

  unprocessedSymbolSummariesBySymbol = new Map<StaticSymbol, Summary<StaticSymbol>>();

  constructor(
      private symbolResolver: StaticSymbolResolver,
      private summaryResolver: SummaryResolver<StaticSymbol>, private srcFileName: string) {
    super();
    this.moduleName = symbolResolver.getKnownModuleName(srcFileName);
  }

  addSummary(summary: Summary<StaticSymbol>) {
    let unprocessedSummary = this.unprocessedSymbolSummariesBySymbol.get(summary.symbol);
    let processedSummary = this.processedSummaryBySymbol.get(summary.symbol);
    if (!unprocessedSummary) {
      unprocessedSummary = {symbol: summary.symbol, metadata: undefined};
      this.unprocessedSymbolSummariesBySymbol.set(summary.symbol, unprocessedSummary);
      processedSummary = {symbol: this.processValue(summary.symbol, SerializationFlags.None)};
      this.processedSummaries.push(processedSummary);
      this.processedSummaryBySymbol.set(summary.symbol, processedSummary);
    }
    if (!unprocessedSummary.metadata && summary.metadata) {
      let metadata = summary.metadata || {};
      if (metadata.__symbolic === 'class') {
        // For classes, we keep everything except their class decorators.
        // We need to keep e.g. the ctor args, method names, method decorators
        // so that the class can be extended in another compilation unit.
        // We don't keep the class decorators as
        // 1) they refer to data
        //   that should not cause a rebuild of downstream compilation units
        //   (e.g. inline templates of @Component, or @NgModule.declarations)
        // 2) their data is already captured in TypeSummaries, e.g. DirectiveSummary.
        const clone: {[key: string]: any} = {};
        Object.keys(metadata).forEach((propName) => {
          if (propName !== 'decorators') {
            clone[propName] = metadata[propName];
          }
        });
        metadata = clone;
      }
      unprocessedSummary.metadata = metadata;
      processedSummary.metadata = this.processValue(metadata, SerializationFlags.ResolveValue);
    }
    if (!unprocessedSummary.type && summary.type) {
      unprocessedSummary.type = summary.type;
      // Note: We don't add the summaries of all referenced symbols as for the ResolvedSymbols,
      // as the type summaries already contain the transitive data that they require
      // (in a minimal way).
      processedSummary.type = this.processValue(summary.type, SerializationFlags.None);
      // except for reexported directives / pipes, so we need to store
      // their summaries explicitly.
      if (summary.type.summaryKind === CompileSummaryKind.NgModule) {
        const ngModuleSummary = <CompileNgModuleSummary>summary.type;
        ngModuleSummary.exportedDirectives.concat(ngModuleSummary.exportedPipes).forEach((id) => {
          const symbol: StaticSymbol = id.reference;
          if (this.summaryResolver.isLibraryFile(symbol.filePath) &&
              !this.unprocessedSymbolSummariesBySymbol.has(symbol)) {
            const summary = this.summaryResolver.resolveSummary(symbol);
            if (summary) {
              this.addSummary(summary);
            }
          }
        });
      }
    }
  }

  serialize(): {json: string, exportAs: {symbol: StaticSymbol, exportAs: string}[]} {
    const exportAs: {symbol: StaticSymbol, exportAs: string}[] = [];
    const json = JSON.stringify({
      moduleName: this.moduleName,
      summaries: this.processedSummaries,
      symbols: this.symbols.map((symbol, index) => {
        symbol.assertNoMembers();
        let importAs: string = undefined !;
        if (this.summaryResolver.isLibraryFile(symbol.filePath)) {
          const summary = this.unprocessedSymbolSummariesBySymbol.get(symbol);
          if (!summary || !summary.metadata || summary.metadata.__symbolic !== 'interface') {
            importAs = `${symbol.name}_${index}`;
            exportAs.push({symbol, exportAs: importAs});
          }
        }
        return {
          __symbol: index,
          name: symbol.name,
          filePath: this.summaryResolver.toSummaryFileName(symbol.filePath, this.srcFileName),
          importAs: importAs
        };
      })
    });
    return {json, exportAs};
  }

  private processValue(value: any, flags: SerializationFlags): any {
    return visitValue(value, this, flags);
  }

  visitOther(value: any, context: any): any {
    if (value instanceof StaticSymbol) {
      let baseSymbol = this.symbolResolver.getStaticSymbol(value.filePath, value.name);
      const index = this.visitStaticSymbol(baseSymbol, context);
      return {__symbol: index, members: value.members};
    }
  }

  /**
   * Returns null if the options.resolveValue is true, and the summary for the symbol
   * resolved to a type or could not be resolved.
   */
  private visitStaticSymbol(baseSymbol: StaticSymbol, flags: SerializationFlags): number {
    let index: number|undefined|null = this.indexBySymbol.get(baseSymbol);
    let summary: Summary<StaticSymbol>|null = null;
    if (flags & SerializationFlags.ResolveValue &&
        this.summaryResolver.isLibraryFile(baseSymbol.filePath)) {
      if (this.unprocessedSymbolSummariesBySymbol.has(baseSymbol)) {
        // the summary for this symbol was already added
        // -> nothing to do.
        return index !;
      }
      summary = this.loadSummary(baseSymbol);
      if (summary && summary.metadata instanceof StaticSymbol) {
        // The summary is a reexport
        index = this.visitStaticSymbol(summary.metadata, flags);
        // reset the summary as it is just a reexport, so we don't want to store it.
        summary = null;
      }
    } else if (index != null) {
      // Note: == on purpose to compare with undefined!
      // No summary and the symbol is already added -> nothing to do.
      return index;
    }
    // Note: == on purpose to compare with undefined!
    if (index == null) {
      index = this.symbols.length;
      this.symbols.push(baseSymbol);
    }
    this.indexBySymbol.set(baseSymbol, index);
    if (summary) {
      this.addSummary(summary);
    }
    return index;
  }

  private loadSummary(symbol: StaticSymbol): Summary<StaticSymbol>|null {
    let summary = this.summaryResolver.resolveSummary(symbol);
    if (!summary) {
      // some symbols might originate from a plain typescript library
      // that just exported .d.ts and .metadata.json files, i.e. where no summary
      // files were created.
      const resolvedSymbol = this.symbolResolver.resolveSymbol(symbol);
      if (resolvedSymbol) {
        summary = {symbol: resolvedSymbol.symbol, metadata: resolvedSymbol.metadata};
      }
    }
    return summary;
  }
}

class ForJitSerializer {
  private data = new Map<StaticSymbol, {
    summary: CompileTypeSummary,
    metadata: CompileNgModuleMetadata|CompileDirectiveMetadata|CompilePipeMetadata|
    CompileTypeMetadata|null,
    isLibrary: boolean
  }>();

  constructor(private outputCtx: OutputContext, private symbolResolver: StaticSymbolResolver) {}

  addSourceType(
      summary: CompileTypeSummary, metadata: CompileNgModuleMetadata|CompileDirectiveMetadata|
      CompilePipeMetadata|CompileTypeMetadata) {
    this.data.set(summary.type.reference, {summary, metadata, isLibrary: false});
  }

  addLibType(summary: CompileTypeSummary) {
    this.data.set(summary.type.reference, {summary, metadata: null, isLibrary: true});
  }

  serialize(exportAs: {symbol: StaticSymbol, exportAs: string}[]): void {
    const ngModuleSymbols = new Set<StaticSymbol>();

    Array.from(this.data.values()).forEach(({summary, metadata, isLibrary}) => {
      if (summary.summaryKind === CompileSummaryKind.NgModule) {
        // collect the symbols that refer to NgModule classes.
        // Note: we can't just rely on `summary.type.summaryKind` to determine this as
        // we don't add the summaries of all referenced symbols when we serialize type summaries.
        // See serializeSummaries for details.
        ngModuleSymbols.add(summary.type.reference);
        const modSummary = <CompileNgModuleSummary>summary;
        modSummary.modules.forEach((mod) => { ngModuleSymbols.add(mod.reference); });
      }
      if (!isLibrary) {
        const fnName = summaryForJitName(summary.type.reference.name);
        createSummaryForJitFunction(
            this.outputCtx, summary.type.reference,
            this.serializeSummaryWithDeps(summary, metadata !));
      }
    });

    exportAs.forEach((entry) => {
      const symbol = entry.symbol;
      if (ngModuleSymbols.has(symbol)) {
        const jitExportAsName = summaryForJitName(entry.exportAs);
        this.outputCtx.statements.push(
            o.variable(jitExportAsName).set(this.serializeSummaryRef(symbol)).toDeclStmt(null, [
              o.StmtModifier.Exported
            ]));
      }
    });
  }

  private serializeSummaryWithDeps(
      summary: CompileTypeSummary, metadata: CompileNgModuleMetadata|CompileDirectiveMetadata|
      CompilePipeMetadata|CompileTypeMetadata): o.Expression {
    const expressions: o.Expression[] = [this.serializeSummary(summary)];
    let providers: CompileProviderMetadata[] = [];
    if (metadata instanceof CompileNgModuleMetadata) {
      expressions.push(...
                       // For directives / pipes, we only add the declared ones,
                       // and rely on transitively importing NgModules to get the transitive
                       // summaries.
                       metadata.declaredDirectives.concat(metadata.declaredPipes)
                           .map(type => type.reference)
                           // For modules,
                           // we also add the summaries for modules
                           // from libraries.
                           // This is ok as we produce reexports for all transitive modules.
                           .concat(metadata.transitiveModule.modules.map(type => type.reference)
                                       .filter(ref => ref !== metadata.type.reference))
                           .map((ref) => this.serializeSummaryRef(ref)));
      // Note: We don't use `NgModuleSummary.providers`, as that one is transitive,
      // and we already have transitive modules.
      providers = metadata.providers;
    } else if (summary.summaryKind === CompileSummaryKind.Directive) {
      const dirSummary = <CompileDirectiveSummary>summary;
      providers = dirSummary.providers.concat(dirSummary.viewProviders);
    }
    // Note: We can't just refer to the `ngsummary.ts` files for `useClass` providers (as we do for
    // declaredDirectives / declaredPipes), as we allow
    // providers without ctor arguments to skip the `@Injectable` decorator,
    // i.e. we didn't generate .ngsummary.ts files for these.
    expressions.push(
        ...providers.filter(provider => !!provider.useClass).map(provider => this.serializeSummary({
          summaryKind: CompileSummaryKind.Injectable, type: provider.useClass
        } as CompileTypeSummary)));
    return o.literalArr(expressions);
  }

  private serializeSummaryRef(typeSymbol: StaticSymbol): o.Expression {
    const jitImportedSymbol = this.symbolResolver.getStaticSymbol(
        summaryForJitFileName(typeSymbol.filePath), summaryForJitName(typeSymbol.name));
    return this.outputCtx.importExpr(jitImportedSymbol);
  }

  private serializeSummary(data: {[key: string]: any}): o.Expression {
    const outputCtx = this.outputCtx;

    class Transformer implements ValueVisitor {
      visitArray(arr: any[], context: any): any {
        return o.literalArr(arr.map(entry => visitValue(entry, this, context)));
      }
      visitStringMap(map: {[key: string]: any}, context: any): any {
        return new o.LiteralMapExpr(Object.keys(map).map(
            (key) => new o.LiteralMapEntry(key, visitValue(map[key], this, context), false)));
      }
      visitPrimitive(value: any, context: any): any { return o.literal(value); }
      visitOther(value: any, context: any): any {
        if (value instanceof StaticSymbol) {
          return outputCtx.importExpr(value);
        } else {
          throw new Error(`Illegal State: Encountered value ${value}`);
        }
      }
    }

    return visitValue(data, new Transformer(), null);
  }
}

class FromJsonDeserializer extends ValueTransformer {
  private symbols: StaticSymbol[];

  constructor(
      private symbolCache: StaticSymbolCache,
      private summaryResolver: SummaryResolver<StaticSymbol>) {
    super();
  }

  deserialize(libraryFileName: string, json: string): {
    moduleName: string | null,
    summaries: Summary<StaticSymbol>[],
    importAs: {symbol: StaticSymbol, importAs: string}[]
  } {
    const data: {moduleName: string | null, summaries: any[], symbols: any[]} = JSON.parse(json);
    const importAs: {symbol: StaticSymbol, importAs: string}[] = [];
    this.symbols = [];
    data.symbols.forEach((serializedSymbol) => {
      const symbol = this.symbolCache.get(
          this.summaryResolver.fromSummaryFileName(serializedSymbol.filePath, libraryFileName),
          serializedSymbol.name);
      this.symbols.push(symbol);
      if (serializedSymbol.importAs) {
        importAs.push({symbol: symbol, importAs: serializedSymbol.importAs});
      }
    });
    const summaries = visitValue(data.summaries, this, null);
    return {moduleName: data.moduleName, summaries, importAs};
  }

  visitStringMap(map: {[key: string]: any}, context: any): any {
    if ('__symbol' in map) {
      const baseSymbol = this.symbols[map['__symbol']];
      const members = map['members'];
      return members.length ? this.symbolCache.get(baseSymbol.filePath, baseSymbol.name, members) :
                              baseSymbol;
    } else {
      return super.visitStringMap(map, context);
    }
  }
}


text:
<?php
namespace Sayenko\Twig;

use Twig_Extension;

/**
 * Class ACF
 * @package App\Twig
 *
 * Twig extension with commands for advanced custom fields
 */
class ACF extends Twig_Extension
{

    /**
     * {@inheritdoc}
     *
     * @return array
     */
    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('get_field', function ($selector, $postID = false, $formatValue = true) {
                return get_field($selector, $postID, $formatValue);
            }),
        );
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return __CLASS__;
    }
}


text:
package com.cloudera.flume.master;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudera.flume.master.commands.CreateLogicalNodeForm;
import com.cloudera.flume.master.commands.DecommissionLogicalNodeForm;
import com.cloudera.flume.master.commands.RefreshAllCommand;
import com.cloudera.flume.master.commands.RefreshCommand;
import com.cloudera.flume.master.commands.SetChokeLimitForm;
import com.cloudera.flume.master.commands.UnconfigCommand;
import com.cloudera.flume.master.commands.UnmapLogicalNodeForm;
import com.cloudera.flume.master.commands.UpdateAllCommand;
import com.cloudera.flume.reporter.ReportEvent;
import com.cloudera.flume.reporter.Reportable;
import com.google.common.base.Preconditions;

/**
 * We want to serialize the order of configuration commands sent to the flume
 * configuration server. To do this we break up actions into Commands, and
 * submit a command to the command manager. The commands are queued into an
 * order and eventually they are exec'ed by the main execution thread.
 *
 * This must be thread safe.
 *
 * TODO (jon) this stores data in memory and will eventually exhaust memory.
 * need to add some cleanup persist old values after some threshold
 * (time/space).
 */
public class CommandManager implements Reportable {
  static final Logger LOG = LoggerFactory.getLogger(CommandManager.class);

  // queue of commands pending execution.
  final LinkedBlockingQueue<CommandStatus> queue = new LinkedBlockingQueue<CommandStatus>();

  // map from command string to executable command. Since we don no provide a
  // mechanism to add more commands, this is essentially
  // constant, and doesn't need guarding.
  final Map<String, Execable> cmds = new HashMap<String, Execable>();

  // This must be accessed in a thread safe way.
  final SortedMap<Long, CommandStatus> statuses = new TreeMap<Long, CommandStatus>();

  final AtomicLong curCommandId = new AtomicLong();

  static Execable noopExec = new Execable() {
    /**
     * Optional argument is a time to sleep in millis
     */
    public void exec(String[] args) throws MasterExecException {
      if (args.length == 1) {
        long delay = Long.parseLong(args[0]);
        try {
          Thread.sleep(delay);
        } catch (InterruptedException e) {
          LOG.debug("Delay noop interrupted", e);
          throw new MasterExecException("Delay Noop Interrupted!", e);
        }
      }
    }
  };

  ExecThread execThread;
  final static Object[][] cmdArrays = { { "noop", noopExec },
      { "config", ConfigCommand.buildExecable() },
      { "multiconfig", MultiConfigCommand.buildExecable() },
      { "unconfig", UnconfigCommand.buildExecable() },
      { "refresh", RefreshCommand.buildExecable() },
      { "refreshAll", RefreshAllCommand.buildExecable() },
      { "updateAll", UpdateAllCommand.buildExecable() },
      { "save", SaveConfigCommand.buildExecable() },
      { "load", LoadConfigCommand.buildExecable() },
      { "spawn", CreateLogicalNodeForm.buildExecable() },
      { "map", CreateLogicalNodeForm.buildExecable() },
      { "decommission", DecommissionLogicalNodeForm.buildExecable() },
      { "unmap", UnmapLogicalNodeForm.buildExecable() },
      { "unmapAll", UnmapLogicalNodeForm.buildUnmapAllExecable() },
      { "setChokeLimit", SetChokeLimitForm.buildExecable() }

  };

  public CommandManager() {
    this(cmdArrays);
  }

  /*
   * This is for testing
   */
  CommandManager(Object[][] cmdArray) {
    for (Object[] c : cmdArray) {
      cmds.put((String) c[0], (Execable) c[1]);
    }
  }

  /**
   * This adds a new command to the set commands that can be executed by the
   * CommandManager
   */
  public void addCommand(String cmd, Execable ex) {
    Preconditions.checkNotNull(cmd, "Command must not be null");
    Preconditions.checkNotNull(ex, "Execable must not be null");
    if (cmds.containsKey(cmd)) {
      LOG.warn("Command '" + cmd
          + "' previously existed and is being overwritten");
    }
    cmds.put(cmd, ex);
  }

  /**
   * Starts the exec thread (don't do this in a constructor)
   */
  synchronized public void start() {
    if (execThread != null) {
      LOG.error("Command Manager already started, not spawning another");
      return;
    }

    execThread = new ExecThread();
    execThread.start();
  }

  /**
   * Cleanly stops the command manager. This blocks until the execThreads are
   * complete.
   */
  synchronized public void stop() {
    execThread.shutdown();
    execThread = null;
  }

  public long submit(Command cmd) {
    Preconditions.checkNotNull(cmd, "No null commands allowed, use \"noop\"");
    LOG.info("Submitting command: " + cmd);
    long cmdId = curCommandId.getAndIncrement();
    CommandStatus cmdStat = CommandStatus.createCommandStatus(cmdId, cmd);
    synchronized (this) {
      // want this to be atomic
      statuses.put(cmdId, cmdStat);
      queue.add(cmdStat);
    }
    return cmdId;
  }

  public boolean isSuccess(long cmdid) {
    CommandStatus stat = null;
    synchronized (this) {
      stat = statuses.get(cmdid);
    }
    return stat != null && stat.isSuccess();
  }

  public boolean isFailure(long cmdid) {
    CommandStatus stat = null;
    synchronized (this) {
      stat = statuses.get(cmdid);
    }
    return stat != null && stat.isFailure();
  }

  /**
   * This layer should eat all exceptions, including runtime exceptions.
   */
  void handleCommand(CommandStatus cmd) {
    try {
      if (cmd == null) {
        return; // do nothing
      }

      cmd.toExecing("");
      exec(cmd.cmd); // if no exception, assumed to be successful
      cmd.toSucceeded("");
    } catch (MasterExecException e) {
      // Log and leave info about expected exceptions
      LOG.warn("During " + cmd + " : " + e.getMessage());
      cmd.toFailed(e.getMessage());
    } catch (Exception e) {
      // catches runtime and unexpected validation / illegal / preconditions
      // exceptions.
      LOG.error("Unexpected exception during " + cmd + " : " + e.getMessage(),
          e);
      cmd.toFailed(e.getMessage());
    }

  }

  class ExecThread extends Thread {
    volatile boolean done = false;

    CountDownLatch stopped = new CountDownLatch(1);

    ExecThread() {
      super("exec-thread");
    }

    @Override
    public void run() {
      try {
        while (!done) {
          // only have to worry about interrupted exns here.
          CommandStatus cmd = queue.poll(1000, TimeUnit.MILLISECONDS);
          handleCommand(cmd);
        }
      } catch (InterruptedException e) {
        LOG.error("Master exec thread interrupted!", e);
      } finally {
        stopped.countDown();
      }
    }

    public void shutdown() {
      done = true;
      try {
        stopped.await();
      } catch (InterruptedException e) {
        LOG.error("Shutdown of command manager was interrupted");
      }
    }

  }

  // package visible for testing.
  void exec(Command cmd) throws MasterExecException {
    Execable ex = cmds.get(cmd.getCommand());
    if (ex == null) {
      throw new MasterExecException("Don't know how to handle Command: '" + cmd
          + "'", null);
    }

    LOG.info("Executing command: " + cmd);
    try {
      ex.exec(cmd.getArgs());
    } catch (MasterExecException e) {
      throw e; // just rethrow
    } catch (IOException e) {
      throw new MasterExecException(e.getMessage(), e);
    }
    // other exceptions get handled at next layer.
  }

  @Override
  public String getName() {
    return "command manager";
  }

  /*
   * Return the Command status for the given submission id. If the id is not
   * present, it returns null.
   */
  public CommandStatus getStatus(long id) {
    return statuses.get(id);
  }

  // TODO (jon) convert to a regular report
  @Override
  public ReportEvent getReport() {

    StringBuilder html = new StringBuilder();
    html.append("
");
    html
        .append("
Command history
\n

id	State	command line	message
\n");

    List<CommandStatus> values = null;

    synchronized (this) {
      values = new ArrayList<CommandStatus>(statuses.values());
    }

    for (CommandStatus stat : values) {
      html.append("
");

      html.append("  ");
      html.append(stat.getCmdID());
      html.append("	\n");

      html.append("  ");
      html.append(stat.getState());
      html.append("	\n");

      html.append("  ");
      html.append(stat.getCommand());
      html.append("	\n");

      html.append("  ");
      html.append(stat.getMessage());
      html.append("	\n");

      html.append("
\n");
    }

    html.append("
\n\n");
    html.append("
");

    return ReportEvent.createLegacyHtmlReport("", html.toString());
  }

}