<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE ScopeReader
#define BOOST_TEST_LOG_LEVEL message
#include <cstddef>
#include <functional>
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include "../JPetManager/JPetManager.h"

#include "JPetScopeReaderFixtures.h"
#include "../JPetScopeReader/JPetScopeReader.h"

char* convertStringToCharP(const std::string& s)
{
  char* pc = new char[s.size() + 1];
  std::strcpy(pc, s.c_str());
  return pc;
}

std::vector<char*> createArgs(const std::string& commandLine)
{
  std::istringstream iss(commandLine);
  std::vector<std::string> args {std::istream_iterator<std::string>{iss},
                                 std::istream_iterator<std::string>{}
                                };
  std::vector<char*> args_char;
  std::transform(args.begin(), args.end(), std::back_inserter(args_char), convertStringToCharP);
  return args_char;
}

BOOST_AUTO_TEST_SUITE (JPetScopeReaderTestSuite)
BOOST_AUTO_TEST_CASE (generate_root_file) {

  auto commandLine = "main.exe  -t scope -f unitTestData/JPetScopeReaderTest/test_file.json";
  auto args_char = createArgs(commandLine);
  auto argc = args_char.size();
  auto argv = args_char.data();

  JPetManager& manager = JPetManager::getManager();
  manager.parseCmdLine(argc, argv);
  manager.run();
  BOOST_REQUIRE_MESSAGE(boost::filesystem::exists(gTest_root_filename), "File " << gTest_root_filename << " does not exist.");
}
BOOST_FIXTURE_TEST_CASE (signal_generation_test, signal_generation_fixture) {

  check_header(
    [] (int osc_file_size, int reco_signal_size) -> void {
      BOOST_REQUIRE_EQUAL(osc_file_size, reco_signal_size);
    }
  );

  check_data(
    [] (float osc_file_time, float reco_signal_time, float osc_file_ampl, float reco_signal_ampl) -> void {
      BOOST_CHECK_CLOSE_FRACTION(osc_file_time, reco_signal_time, 1.f / 131072.f);
      BOOST_CHECK_CLOSE_FRACTION(osc_file_ampl, reco_signal_ampl, 1.f / 131072.f);
    }
  );
}
BOOST_FIXTURE_TEST_CASE (tref_correctness_test, tref_correctness_fixture) {

  check_tref_simple(
    [] (const void* tref_pointer) -> void {
      BOOST_CHECK_PREDICATE(std::not_equal_to <size_t> (), ((size_t) tref_pointer)((size_t) nullptr));
    }
  );
  //check_tref_simple(nullptr);
}

BOOST_AUTO_TEST_CASE (getFilePrefix)
{
  JPetScopeReader reader(0);
  BOOST_REQUIRE(reader.getFilePrefix("").empty());
  BOOST_REQUIRE(reader.getFilePrefix("abkabd").empty());
  BOOST_REQUIRE(reader.getFilePrefix("jfsd808").empty());
  BOOST_REQUIRE_EQUAL(reader.getFilePrefix("c1_0554.txt"), "c1");
  BOOST_REQUIRE_EQUAL(reader.getFilePrefix("c098_0554.txt"), "c098");
  BOOST_REQUIRE_EQUAL(reader.getFilePrefix("cq_"), "cq");
  BOOST_REQUIRE_EQUAL(reader.getFilePrefix("a_ss_q"), "a");
}

BOOST_AUTO_TEST_CASE (createInputScopeFileNames)
{
  JPetScopeReader reader(0);
  BOOST_REQUIRE(reader.createInputScopeFileNames("", {}).empty());
  BOOST_REQUIRE(reader.createInputScopeFileNames("non_existing", {}).empty());
  BOOST_REQUIRE(!reader.createInputScopeFileNames("unitTestData/JPetScopeReaderTest/scope_files/0", {{"c1",0}, {"c2",1}, {"c3", 2}, {"c4",3}}).empty());
  std::map<int, std::vector<string>>  expectedRes {
    {0, {"C1_00003.txt","C1_00004.txt"}}, {1, {"C2_00003.txt","C2_00004.txt"}},
    {2, {"C3_00003.txt","C3_00004.txt"}}, {3, {"C4_00003.txt","C4_00004.txt"}}
  };
  std::string pathToFiles = "unitTestData/JPetScopeReaderTest/scope_files/0";
  std::for_each(expectedRes.begin(), expectedRes.end(),
                [&](std::pair<const int, std::vector<std::string> >&  el) {
                      for_each(el.second.begin(), el.second.end(),
                      [&](std::string& name) {
                        name = pathToFiles + "/" + name;
                      });
                      std::sort(el.second.begin(), el.second.end());
                });
  std::map<int, std::vector<std::string> > obtainedRes = reader.createInputScopeFileNames(pathToFiles, {{"C1",0}, {"C2",1}, {"C3", 2}, {"C4",3}});
  /// to assure the same order of elements for comparison
  std::for_each(obtainedRes.begin(), obtainedRes.end(),
                [&](std::pair<const int, std::vector<std::string> >&  el) {
                      std::sort(el.second.begin(), el.second.end());
                });
  BOOST_REQUIRE(!obtainedRes.empty());
  BOOST_REQUIRE_EQUAL_COLLECTIONS(obtainedRes[0].begin(), obtainedRes[0].end(), expectedRes[0].begin(), expectedRes[0].end());
  BOOST_REQUIRE_EQUAL_COLLECTIONS(obtainedRes[1].begin(), obtainedRes[1].end(), expectedRes[1].begin(), expectedRes[1].end());
  BOOST_REQUIRE_EQUAL_COLLECTIONS(obtainedRes[2].begin(), obtainedRes[2].end(), expectedRes[2].begin(), expectedRes[2].end());
  BOOST_REQUIRE_EQUAL_COLLECTIONS(obtainedRes[3].begin(), obtainedRes[3].end(), expectedRes[3].begin(), expectedRes[3].end());
}

BOOST_AUTO_TEST_CASE (isCorrectScopeFileName)
{
  JPetScopeReader reader(0);
  BOOST_REQUIRE(!reader.isCorrectScopeFileName(""));
  BOOST_REQUIRE(!reader.isCorrectScopeFileName("C1_004.gif"));
  BOOST_REQUIRE(!reader.isCorrectScopeFileName("C1004.txt"));
  BOOST_REQUIRE(!reader.isCorrectScopeFileName("004.txt"));
  BOOST_REQUIRE(!reader.isCorrectScopeFileName("C5_abc.txt"));
  BOOST_REQUIRE(reader.isCorrectScopeFileName("C1_023.txt"));
  BOOST_REQUIRE(reader.isCorrectScopeFileName("C5_000.txt"));
  BOOST_REQUIRE(reader.isCorrectScopeFileName("AA_004.txt"));
  BOOST_REQUIRE(reader.isCorrectScopeFileName("AA_004.txt"));
}

BOOST_AUTO_TEST_CASE (FullTest)
{
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Remove empty test and change the order of JPetScopeReaderTests<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE ScopeReader
#define BOOST_TEST_LOG_LEVEL message
#include <cstddef>
#include <functional>
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include "../JPetManager/JPetManager.h"

#include "JPetScopeReaderFixtures.h"
#include "../JPetScopeReader/JPetScopeReader.h"

char* convertStringToCharP(const std::string& s)
{
  char* pc = new char[s.size() + 1];
  std::strcpy(pc, s.c_str());
  return pc;
}

std::vector<char*> createArgs(const std::string& commandLine)
{
  std::istringstream iss(commandLine);
  std::vector<std::string> args {std::istream_iterator<std::string>{iss},
                                 std::istream_iterator<std::string>{}
                                };
  std::vector<char*> args_char;
  std::transform(args.begin(), args.end(), std::back_inserter(args_char), convertStringToCharP);
  return args_char;
}

BOOST_AUTO_TEST_SUITE (JPetScopeReaderTestSuite)

BOOST_AUTO_TEST_CASE (getFilePrefix)
{
  JPetScopeReader reader(0);
  BOOST_REQUIRE(reader.getFilePrefix("").empty());
  BOOST_REQUIRE(reader.getFilePrefix("abkabd").empty());
  BOOST_REQUIRE(reader.getFilePrefix("jfsd808").empty());
  BOOST_REQUIRE_EQUAL(reader.getFilePrefix("c1_0554.txt"), "c1");
  BOOST_REQUIRE_EQUAL(reader.getFilePrefix("c098_0554.txt"), "c098");
  BOOST_REQUIRE_EQUAL(reader.getFilePrefix("cq_"), "cq");
  BOOST_REQUIRE_EQUAL(reader.getFilePrefix("a_ss_q"), "a");
}

BOOST_AUTO_TEST_CASE (createInputScopeFileNames)
{
  JPetScopeReader reader(0);
  BOOST_REQUIRE(reader.createInputScopeFileNames("", {}).empty());
  BOOST_REQUIRE(reader.createInputScopeFileNames("non_existing", {}).empty());
  BOOST_REQUIRE(!reader.createInputScopeFileNames("unitTestData/JPetScopeReaderTest/scope_files/0", {{"c1",0}, {"c2",1}, {"c3", 2}, {"c4",3}}).empty());
  std::map<int, std::vector<string>>  expectedRes {
    {0, {"C1_00003.txt","C1_00004.txt"}}, {1, {"C2_00003.txt","C2_00004.txt"}},
    {2, {"C3_00003.txt","C3_00004.txt"}}, {3, {"C4_00003.txt","C4_00004.txt"}}
  };
  std::string pathToFiles = "unitTestData/JPetScopeReaderTest/scope_files/0";
  std::for_each(expectedRes.begin(), expectedRes.end(),
                [&](std::pair<const int, std::vector<std::string> >&  el) {
                      for_each(el.second.begin(), el.second.end(),
                      [&](std::string& name) {
                        name = pathToFiles + "/" + name;
                      });
                      std::sort(el.second.begin(), el.second.end());
                });
  std::map<int, std::vector<std::string> > obtainedRes = reader.createInputScopeFileNames(pathToFiles, {{"C1",0}, {"C2",1}, {"C3", 2}, {"C4",3}});
  /// to assure the same order of elements for comparison
  std::for_each(obtainedRes.begin(), obtainedRes.end(),
                [&](std::pair<const int, std::vector<std::string> >&  el) {
                      std::sort(el.second.begin(), el.second.end());
                });
  BOOST_REQUIRE(!obtainedRes.empty());
  BOOST_REQUIRE_EQUAL_COLLECTIONS(obtainedRes[0].begin(), obtainedRes[0].end(), expectedRes[0].begin(), expectedRes[0].end());
  BOOST_REQUIRE_EQUAL_COLLECTIONS(obtainedRes[1].begin(), obtainedRes[1].end(), expectedRes[1].begin(), expectedRes[1].end());
  BOOST_REQUIRE_EQUAL_COLLECTIONS(obtainedRes[2].begin(), obtainedRes[2].end(), expectedRes[2].begin(), expectedRes[2].end());
  BOOST_REQUIRE_EQUAL_COLLECTIONS(obtainedRes[3].begin(), obtainedRes[3].end(), expectedRes[3].begin(), expectedRes[3].end());
}

BOOST_AUTO_TEST_CASE (isCorrectScopeFileName)
{
  JPetScopeReader reader(0);
  BOOST_REQUIRE(!reader.isCorrectScopeFileName(""));
  BOOST_REQUIRE(!reader.isCorrectScopeFileName("C1_004.gif"));
  BOOST_REQUIRE(!reader.isCorrectScopeFileName("C1004.txt"));
  BOOST_REQUIRE(!reader.isCorrectScopeFileName("004.txt"));
  BOOST_REQUIRE(!reader.isCorrectScopeFileName("C5_abc.txt"));
  BOOST_REQUIRE(reader.isCorrectScopeFileName("C1_023.txt"));
  BOOST_REQUIRE(reader.isCorrectScopeFileName("C5_000.txt"));
  BOOST_REQUIRE(reader.isCorrectScopeFileName("AA_004.txt"));
  BOOST_REQUIRE(reader.isCorrectScopeFileName("AA_004.txt"));
}

BOOST_AUTO_TEST_CASE (generate_root_file) {

  auto commandLine = "main.exe  -t scope -f unitTestData/JPetScopeReaderTest/test_file.json";
  auto args_char = createArgs(commandLine);
  auto argc = args_char.size();
  auto argv = args_char.data();

  JPetManager& manager = JPetManager::getManager();
  manager.parseCmdLine(argc, argv);
  manager.run();
  BOOST_REQUIRE_MESSAGE(boost::filesystem::exists(gTest_root_filename), "File " << gTest_root_filename << " does not exist.");
}

BOOST_FIXTURE_TEST_CASE (signal_generation_test, signal_generation_fixture) {

  check_header(
    [] (int osc_file_size, int reco_signal_size) -> void {
      BOOST_REQUIRE_EQUAL(osc_file_size, reco_signal_size);
    }
  );

  check_data(
    [] (float osc_file_time, float reco_signal_time, float osc_file_ampl, float reco_signal_ampl) -> void {
      BOOST_CHECK_CLOSE_FRACTION(osc_file_time, reco_signal_time, 1.f / 131072.f);
      BOOST_CHECK_CLOSE_FRACTION(osc_file_ampl, reco_signal_ampl, 1.f / 131072.f);
    }
  );
}
BOOST_FIXTURE_TEST_CASE (tref_correctness_test, tref_correctness_fixture) {

  check_tref_simple(
    [] (const void* tref_pointer) -> void {
      BOOST_CHECK_PREDICATE(std::not_equal_to <size_t> (), ((size_t) tref_pointer)((size_t) nullptr));
    }
  );
  //check_tref_simple(nullptr);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>//===- ReadConst.cpp - Code to constants and constant pools ---------------===//
//
// This file implements functionality to deserialize constants and entire
// constant pools.
//
// Note that this library should be as fast as possible, reentrant, and
// threadsafe!!
//
//===----------------------------------------------------------------------===//

#include "ReaderInternals.h"
#include "llvm/Module.h"
#include "llvm/Constants.h"
#include "llvm/GlobalVariable.h"
#include <algorithm>
#include <iostream>

using std::make_pair;

const Type *BytecodeParser::parseTypeConstant(const uchar *&Buf,
					      const uchar *EndBuf) {
  unsigned PrimType;
  if (read_vbr(Buf, EndBuf, PrimType)) return failure<const Type*>(0);

  const Type *Val = 0;
  if ((Val = Type::getPrimitiveType((Type::PrimitiveID)PrimType)))
    return Val;

  switch (PrimType) {
  case Type::FunctionTyID: {
    unsigned Typ;
    if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
    const Type *RetType = getType(Typ);
    if (RetType == 0) return failure(Val);

    unsigned NumParams;
    if (read_vbr(Buf, EndBuf, NumParams)) return failure(Val);

    std::vector<const Type*> Params;
    while (NumParams--) {
      if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
      const Type *Ty = getType(Typ);
      if (Ty == 0) return failure(Val);
      Params.push_back(Ty);
    }

    bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
    if (isVarArg) Params.pop_back();

    return FunctionType::get(RetType, Params, isVarArg);
  }
  case Type::ArrayTyID: {
    unsigned ElTyp;
    if (read_vbr(Buf, EndBuf, ElTyp)) return failure(Val);
    const Type *ElementType = getType(ElTyp);
    if (ElementType == 0) return failure(Val);

    unsigned NumElements;
    if (read_vbr(Buf, EndBuf, NumElements)) return failure(Val);

    BCR_TRACE(5, "Array Type Constant #" << ElTyp << " size="
              << NumElements << "\n");
    return ArrayType::get(ElementType, NumElements);
  }
  case Type::StructTyID: {
    unsigned Typ;
    std::vector<const Type*> Elements;

    if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
    while (Typ) {         // List is terminated by void/0 typeid
      const Type *Ty = getType(Typ);
      if (Ty == 0) return failure(Val);
      Elements.push_back(Ty);

      if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
    }

    return StructType::get(Elements);
  }
  case Type::PointerTyID: {
    unsigned ElTyp;
    if (read_vbr(Buf, EndBuf, ElTyp)) return failure(Val);
    BCR_TRACE(5, "Pointer Type Constant #" << (ElTyp-14) << "\n");
    const Type *ElementType = getType(ElTyp);
    if (ElementType == 0) return failure(Val);
    return PointerType::get(ElementType);
  }

  case Type::OpaqueTyID: {
    return OpaqueType::get();
  }

  default:
    std::cerr << __FILE__ << ":" << __LINE__
              << ": Don't know how to deserialize"
              << " primitive Type " << PrimType << "\n";
    return failure(Val);
  }
}

// refineAbstractType - The callback method is invoked when one of the
// elements of TypeValues becomes more concrete...
//
void BytecodeParser::refineAbstractType(const DerivedType *OldType,
					const Type *NewType) {
  if (OldType == NewType &&
      OldType->isAbstract()) return;  // Type is modified, but same

  TypeValuesListTy::iterator I = find(MethodTypeValues.begin(),
				      MethodTypeValues.end(), OldType);
  if (I == MethodTypeValues.end()) {
    I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), OldType);
    assert(I != ModuleTypeValues.end() &&
	   "Can't refine a type I don't know about!");
  }

  if (OldType == NewType) {
    assert(!OldType->isAbstract());
    I->removeUserFromConcrete();
  } else {
    *I = NewType;  // Update to point to new, more refined type.
  }
}

// parseTypeConstants - We have to use this wierd code to handle recursive
// types.  We know that recursive types will only reference the current slab of
// values in the type plane, but they can forward reference types before they
// have been read.  For example, Type #0 might be '{ Ty#1 }' and Type #1 might
// be 'Ty#0*'.  When reading Type #0, type number one doesn't exist.  To fix
// this ugly problem, we pesimistically insert an opaque type for each type we
// are about to read.  This means that forward references will resolve to
// something and when we reread the type later, we can replace the opaque type
// with a new resolved concrete type.
//
void debug_type_tables();
bool BytecodeParser::parseTypeConstants(const uchar *&Buf, const uchar *EndBuf,
					TypeValuesListTy &Tab,
					unsigned NumEntries) {
  assert(Tab.size() == 0 && "should not have read type constants in before!");

  // Insert a bunch of opaque types to be resolved later...
  for (unsigned i = 0; i < NumEntries; ++i)
    Tab.push_back(PATypeHandle<Type>(OpaqueType::get(), this));

  // Loop through reading all of the types.  Forward types will make use of the
  // opaque types just inserted.
  //
  for (unsigned i = 0; i < NumEntries; ++i) {
    const Type *NewTy = parseTypeConstant(Buf, EndBuf), *OldTy = Tab[i].get();
    if (NewTy == 0) return failure(true);
    BCR_TRACE(4, "#" << i << ": Read Type Constant: '" << NewTy <<
              "' Replacing: " << OldTy << "\n");

    // Don't insertValue the new type... instead we want to replace the opaque
    // type with the new concrete value...
    //

    // Refine the abstract type to the new type.  This causes all uses of the
    // abstract type to use the newty.  This also will cause the opaque type
    // to be deleted...
    //
    ((DerivedType*)Tab[i].get())->refineAbstractTypeTo(NewTy);

    // This should have replace the old opaque type with the new type in the
    // value table... or with a preexisting type that was already in the system
    assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
  }

  BCR_TRACE(5, "Resulting types:\n");
  for (unsigned i = 0; i < NumEntries; ++i) {
    BCR_TRACE(5, (void*)Tab[i].get() << " - " << Tab[i].get() << "\n");
  }
  debug_type_tables();
  return false;
}

bool BytecodeParser::parseConstantValue(const uchar *&Buf, const uchar *EndBuf,
                                        const Type *Ty, Constant *&V) {

  // We must check for a ConstantExpr before switching by type because
  // a ConstantExpr can be of any type, and has no explicit value.
  //
  unsigned isExprNumArgs;               // 0 if not expr; numArgs if is expr
  if (read_vbr(Buf, EndBuf, isExprNumArgs)) return failure(true);
  if (isExprNumArgs) {
    unsigned opCode;
    std::vector<Constant*> argVec;
    argVec.reserve(isExprNumArgs);

    if (read_vbr(Buf, EndBuf, opCode)) return failure(true);

    // Read the slot number and types of each of the arguments
    for (unsigned i=0; i < isExprNumArgs; ++i) {
      unsigned argValSlot, argTypeSlot;
      if (read_vbr(Buf, EndBuf, argValSlot)) return failure(true);
      if (read_vbr(Buf, EndBuf, argTypeSlot)) return failure(true);
      const Type *argTy = getType(argTypeSlot);
      if (argTy == 0) return failure(true);

      BCR_TRACE(4, "CE Arg " << i << ": Type: '" << argTy << "'  slot: " << argValSlot << "\n");

      // Get the arg value from its slot if it exists, otherwise a placeholder
      Value *Val = getValue(argTy, argValSlot, false);
      Constant *C;
      if (Val) {
        if (!(C = dyn_cast<Constant>(Val))) return failure(true);
        BCR_TRACE(5, "Constant Found in ValueTable!\n");
      } else {         // Nope... find or create a forward ref. for it
        C = fwdRefs.GetFwdRefToConstant(argTy, argValSlot);
      }
      argVec.push_back(C);
    }

    // Construct a ConstantExpr of the appropriate kind
    if (isExprNumArgs == 1) {           // All one-operand expressions
      V = ConstantExpr::get(opCode, argVec[0], Ty);
    } else if (opCode == Instruction::GetElementPtr) { // GetElementPtr
      std::vector<Constant*> IdxList(argVec.begin()+1, argVec.end());
      V = ConstantExpr::get(opCode, argVec[0], IdxList, Ty);
    } else {                            // All other 2-operand expressions
      V = ConstantExpr::get(opCode, argVec[0], argVec[1], Ty);
    }
    return false;
  }

  // Ok, not an ConstantExpr.  We now know how to read the given type...
  switch (Ty->getPrimitiveID()) {
  case Type::BoolTyID: {
    unsigned Val;
    if (read_vbr(Buf, EndBuf, Val)) return failure(true);
    if (Val != 0 && Val != 1) return failure(true);
    V = ConstantBool::get(Val == 1);
    break;
  }

  case Type::UByteTyID:   // Unsigned integer types...
  case Type::UShortTyID:
  case Type::UIntTyID: {
    unsigned Val;
    if (read_vbr(Buf, EndBuf, Val)) return failure(true);
    if (!ConstantUInt::isValueValidForType(Ty, Val)) return failure(true);
    V = ConstantUInt::get(Ty, Val);
    break;
  }

  case Type::ULongTyID: {
    uint64_t Val;
    if (read_vbr(Buf, EndBuf, Val)) return failure(true);
    V = ConstantUInt::get(Ty, Val);
    break;
  }

  case Type::SByteTyID:   // Unsigned integer types...
  case Type::ShortTyID:
  case Type::IntTyID: {
    int Val;
    if (read_vbr(Buf, EndBuf, Val)) return failure(true);
    if (!ConstantSInt::isValueValidForType(Ty, Val)) return failure(true);
    V = ConstantSInt::get(Ty, Val);
    break;
  }

  case Type::LongTyID: {
    int64_t Val;
    if (read_vbr(Buf, EndBuf, Val)) return failure(true);
    V = ConstantSInt::get(Ty, Val);
    break;
  }

  case Type::FloatTyID: {
    float F;
    if (input_data(Buf, EndBuf, &F, &F+1)) return failure(true);
    V = ConstantFP::get(Ty, F);
    break;
  }

  case Type::DoubleTyID: {
    double Val;
    if (input_data(Buf, EndBuf, &Val, &Val+1)) return failure(true);
    V = ConstantFP::get(Ty, Val);
    break;
  }

  case Type::TypeTyID:
    assert(0 && "Type constants should be handled seperately!!!");
    abort();

  case Type::ArrayTyID: {
    const ArrayType *AT = cast<const ArrayType>(Ty);
    unsigned NumElements = AT->getNumElements();

    std::vector<Constant*> Elements;
    while (NumElements--) {   // Read all of the elements of the constant.
      unsigned Slot;
      if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
      Value *V = getValue(AT->getElementType(), Slot, false);
      if (!V || !isa<Constant>(V)) return failure(true);
      Elements.push_back(cast<Constant>(V));
    }
    V = ConstantArray::get(AT, Elements);
    break;
  }

  case Type::StructTyID: {
    const StructType *ST = cast<StructType>(Ty);
    const StructType::ElementTypes &ET = ST->getElementTypes();

    std::vector<Constant *> Elements;
    for (unsigned i = 0; i < ET.size(); ++i) {
      unsigned Slot;
      if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
      Value *V = getValue(ET[i], Slot, false);
      if (!V || !isa<Constant>(V))
	return failure(true);
      Elements.push_back(cast<Constant>(V));
    }

    V = ConstantStruct::get(ST, Elements);
    break;
  }

  case Type::PointerTyID: {
    const PointerType *PT = cast<const PointerType>(Ty);
    unsigned SubClass;
    if (read_vbr(Buf, EndBuf, SubClass)) return failure(true);
    switch (SubClass) {
    case 0:    // ConstantPointerNull value...
      V = ConstantPointerNull::get(PT);
      break;

    case 1: {  // ConstantPointerRef value...
      unsigned Slot;
      if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
      BCR_TRACE(4, "CPR: Type: '" << Ty << "'  slot: " << Slot << "\n");

      // Check to see if we have already read this global variable yet...
      Value *Val = getValue(PT, Slot, false);
      GlobalValue* GV;
      if (Val) {
        if (!(GV = dyn_cast<GlobalValue>(Val))) return failure(true);
        BCR_TRACE(5, "Value Found in ValueTable!\n");
      } else {         // Nope... find or create a forward ref. for it
        GV = fwdRefs.GetFwdRefToGlobal(PT, Slot);
      }
      V = ConstantPointerRef::get(GV);
      break;
    }

    default:
      BCR_TRACE(5, "UNKNOWN Pointer Constant Type!\n");
      return failure(true);
    }
    break;
  }

  default:
    std::cerr << __FILE__ << ":" << __LINE__
              << ": Don't know how to deserialize constant value of type '"
              << Ty->getName() << "'\n";
    return failure(true);
  }

  return false;
}

bool BytecodeParser::ParseConstantPool(const uchar *&Buf, const uchar *EndBuf,
				       ValueTable &Tab,
				       TypeValuesListTy &TypeTab) {
  while (Buf < EndBuf) {
    unsigned NumEntries, Typ;

    if (read_vbr(Buf, EndBuf, NumEntries) ||
        read_vbr(Buf, EndBuf, Typ)) return failure(true);
    const Type *Ty = getType(Typ);
    if (Ty == 0) return failure(true);
    BCR_TRACE(3, "Type: '" << Ty << "'  NumEntries: " << NumEntries << "\n");

    if (Typ == Type::TypeTyID) {
      if (parseTypeConstants(Buf, EndBuf, TypeTab, NumEntries)) return true;
    } else {
      for (unsigned i = 0; i < NumEntries; ++i) {
	Constant *I;
        int Slot;
	if (parseConstantValue(Buf, EndBuf, Ty, I)) return failure(true);
        assert(I && "parseConstantValue returned `!failure' and NULL result");
	BCR_TRACE(4, "Read Constant: '" << I << "'\n");
	if ((Slot = insertValue(I, Tab)) < 0) return failure(true);
        resolveRefsToConstant(I, (unsigned) Slot);
      }
    }
  }

  if (Buf > EndBuf) return failure(true);
  return false;
}
<commit_msg>Break line to fit 80 columns<commit_after>//===- ReadConst.cpp - Code to constants and constant pools ---------------===//
//
// This file implements functionality to deserialize constants and entire
// constant pools.
//
// Note that this library should be as fast as possible, reentrant, and
// threadsafe!!
//
//===----------------------------------------------------------------------===//

#include "ReaderInternals.h"
#include "llvm/Module.h"
#include "llvm/Constants.h"
#include "llvm/GlobalVariable.h"
#include <algorithm>
#include <iostream>

using std::make_pair;

const Type *BytecodeParser::parseTypeConstant(const uchar *&Buf,
					      const uchar *EndBuf) {
  unsigned PrimType;
  if (read_vbr(Buf, EndBuf, PrimType)) return failure<const Type*>(0);

  const Type *Val = 0;
  if ((Val = Type::getPrimitiveType((Type::PrimitiveID)PrimType)))
    return Val;

  switch (PrimType) {
  case Type::FunctionTyID: {
    unsigned Typ;
    if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
    const Type *RetType = getType(Typ);
    if (RetType == 0) return failure(Val);

    unsigned NumParams;
    if (read_vbr(Buf, EndBuf, NumParams)) return failure(Val);

    std::vector<const Type*> Params;
    while (NumParams--) {
      if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
      const Type *Ty = getType(Typ);
      if (Ty == 0) return failure(Val);
      Params.push_back(Ty);
    }

    bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
    if (isVarArg) Params.pop_back();

    return FunctionType::get(RetType, Params, isVarArg);
  }
  case Type::ArrayTyID: {
    unsigned ElTyp;
    if (read_vbr(Buf, EndBuf, ElTyp)) return failure(Val);
    const Type *ElementType = getType(ElTyp);
    if (ElementType == 0) return failure(Val);

    unsigned NumElements;
    if (read_vbr(Buf, EndBuf, NumElements)) return failure(Val);

    BCR_TRACE(5, "Array Type Constant #" << ElTyp << " size="
              << NumElements << "\n");
    return ArrayType::get(ElementType, NumElements);
  }
  case Type::StructTyID: {
    unsigned Typ;
    std::vector<const Type*> Elements;

    if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
    while (Typ) {         // List is terminated by void/0 typeid
      const Type *Ty = getType(Typ);
      if (Ty == 0) return failure(Val);
      Elements.push_back(Ty);

      if (read_vbr(Buf, EndBuf, Typ)) return failure(Val);
    }

    return StructType::get(Elements);
  }
  case Type::PointerTyID: {
    unsigned ElTyp;
    if (read_vbr(Buf, EndBuf, ElTyp)) return failure(Val);
    BCR_TRACE(5, "Pointer Type Constant #" << (ElTyp-14) << "\n");
    const Type *ElementType = getType(ElTyp);
    if (ElementType == 0) return failure(Val);
    return PointerType::get(ElementType);
  }

  case Type::OpaqueTyID: {
    return OpaqueType::get();
  }

  default:
    std::cerr << __FILE__ << ":" << __LINE__
              << ": Don't know how to deserialize"
              << " primitive Type " << PrimType << "\n";
    return failure(Val);
  }
}

// refineAbstractType - The callback method is invoked when one of the
// elements of TypeValues becomes more concrete...
//
void BytecodeParser::refineAbstractType(const DerivedType *OldType,
					const Type *NewType) {
  if (OldType == NewType &&
      OldType->isAbstract()) return;  // Type is modified, but same

  TypeValuesListTy::iterator I = find(MethodTypeValues.begin(),
				      MethodTypeValues.end(), OldType);
  if (I == MethodTypeValues.end()) {
    I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), OldType);
    assert(I != ModuleTypeValues.end() &&
	   "Can't refine a type I don't know about!");
  }

  if (OldType == NewType) {
    assert(!OldType->isAbstract());
    I->removeUserFromConcrete();
  } else {
    *I = NewType;  // Update to point to new, more refined type.
  }
}

// parseTypeConstants - We have to use this wierd code to handle recursive
// types.  We know that recursive types will only reference the current slab of
// values in the type plane, but they can forward reference types before they
// have been read.  For example, Type #0 might be '{ Ty#1 }' and Type #1 might
// be 'Ty#0*'.  When reading Type #0, type number one doesn't exist.  To fix
// this ugly problem, we pesimistically insert an opaque type for each type we
// are about to read.  This means that forward references will resolve to
// something and when we reread the type later, we can replace the opaque type
// with a new resolved concrete type.
//
void debug_type_tables();
bool BytecodeParser::parseTypeConstants(const uchar *&Buf, const uchar *EndBuf,
					TypeValuesListTy &Tab,
					unsigned NumEntries) {
  assert(Tab.size() == 0 && "should not have read type constants in before!");

  // Insert a bunch of opaque types to be resolved later...
  for (unsigned i = 0; i < NumEntries; ++i)
    Tab.push_back(PATypeHandle<Type>(OpaqueType::get(), this));

  // Loop through reading all of the types.  Forward types will make use of the
  // opaque types just inserted.
  //
  for (unsigned i = 0; i < NumEntries; ++i) {
    const Type *NewTy = parseTypeConstant(Buf, EndBuf), *OldTy = Tab[i].get();
    if (NewTy == 0) return failure(true);
    BCR_TRACE(4, "#" << i << ": Read Type Constant: '" << NewTy <<
              "' Replacing: " << OldTy << "\n");

    // Don't insertValue the new type... instead we want to replace the opaque
    // type with the new concrete value...
    //

    // Refine the abstract type to the new type.  This causes all uses of the
    // abstract type to use the newty.  This also will cause the opaque type
    // to be deleted...
    //
    ((DerivedType*)Tab[i].get())->refineAbstractTypeTo(NewTy);

    // This should have replace the old opaque type with the new type in the
    // value table... or with a preexisting type that was already in the system
    assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
  }

  BCR_TRACE(5, "Resulting types:\n");
  for (unsigned i = 0; i < NumEntries; ++i) {
    BCR_TRACE(5, (void*)Tab[i].get() << " - " << Tab[i].get() << "\n");
  }
  debug_type_tables();
  return false;
}

bool BytecodeParser::parseConstantValue(const uchar *&Buf, const uchar *EndBuf,
                                        const Type *Ty, Constant *&V) {

  // We must check for a ConstantExpr before switching by type because
  // a ConstantExpr can be of any type, and has no explicit value.
  //
  unsigned isExprNumArgs;               // 0 if not expr; numArgs if is expr
  if (read_vbr(Buf, EndBuf, isExprNumArgs)) return failure(true);
  if (isExprNumArgs) {
    unsigned opCode;
    std::vector<Constant*> argVec;
    argVec.reserve(isExprNumArgs);

    if (read_vbr(Buf, EndBuf, opCode)) return failure(true);

    // Read the slot number and types of each of the arguments
    for (unsigned i=0; i < isExprNumArgs; ++i) {
      unsigned argValSlot, argTypeSlot;
      if (read_vbr(Buf, EndBuf, argValSlot)) return failure(true);
      if (read_vbr(Buf, EndBuf, argTypeSlot)) return failure(true);
      const Type *argTy = getType(argTypeSlot);
      if (argTy == 0) return failure(true);

      BCR_TRACE(4, "CE Arg " << i << ": Type: '" << argTy << "'  slot: "
                << argValSlot << "\n");

      // Get the arg value from its slot if it exists, otherwise a placeholder
      Value *Val = getValue(argTy, argValSlot, false);
      Constant *C;
      if (Val) {
        if (!(C = dyn_cast<Constant>(Val))) return failure(true);
        BCR_TRACE(5, "Constant Found in ValueTable!\n");
      } else {         // Nope... find or create a forward ref. for it
        C = fwdRefs.GetFwdRefToConstant(argTy, argValSlot);
      }
      argVec.push_back(C);
    }

    // Construct a ConstantExpr of the appropriate kind
    if (isExprNumArgs == 1) {           // All one-operand expressions
      V = ConstantExpr::get(opCode, argVec[0], Ty);
    } else if (opCode == Instruction::GetElementPtr) { // GetElementPtr
      std::vector<Constant*> IdxList(argVec.begin()+1, argVec.end());
      V = ConstantExpr::get(opCode, argVec[0], IdxList, Ty);
    } else {                            // All other 2-operand expressions
      V = ConstantExpr::get(opCode, argVec[0], argVec[1], Ty);
    }
    return false;
  }

  // Ok, not an ConstantExpr.  We now know how to read the given type...
  switch (Ty->getPrimitiveID()) {
  case Type::BoolTyID: {
    unsigned Val;
    if (read_vbr(Buf, EndBuf, Val)) return failure(true);
    if (Val != 0 && Val != 1) return failure(true);
    V = ConstantBool::get(Val == 1);
    break;
  }

  case Type::UByteTyID:   // Unsigned integer types...
  case Type::UShortTyID:
  case Type::UIntTyID: {
    unsigned Val;
    if (read_vbr(Buf, EndBuf, Val)) return failure(true);
    if (!ConstantUInt::isValueValidForType(Ty, Val)) return failure(true);
    V = ConstantUInt::get(Ty, Val);
    break;
  }

  case Type::ULongTyID: {
    uint64_t Val;
    if (read_vbr(Buf, EndBuf, Val)) return failure(true);
    V = ConstantUInt::get(Ty, Val);
    break;
  }

  case Type::SByteTyID:   // Unsigned integer types...
  case Type::ShortTyID:
  case Type::IntTyID: {
    int Val;
    if (read_vbr(Buf, EndBuf, Val)) return failure(true);
    if (!ConstantSInt::isValueValidForType(Ty, Val)) return failure(true);
    V = ConstantSInt::get(Ty, Val);
    break;
  }

  case Type::LongTyID: {
    int64_t Val;
    if (read_vbr(Buf, EndBuf, Val)) return failure(true);
    V = ConstantSInt::get(Ty, Val);
    break;
  }

  case Type::FloatTyID: {
    float F;
    if (input_data(Buf, EndBuf, &F, &F+1)) return failure(true);
    V = ConstantFP::get(Ty, F);
    break;
  }

  case Type::DoubleTyID: {
    double Val;
    if (input_data(Buf, EndBuf, &Val, &Val+1)) return failure(true);
    V = ConstantFP::get(Ty, Val);
    break;
  }

  case Type::TypeTyID:
    assert(0 && "Type constants should be handled seperately!!!");
    abort();

  case Type::ArrayTyID: {
    const ArrayType *AT = cast<const ArrayType>(Ty);
    unsigned NumElements = AT->getNumElements();

    std::vector<Constant*> Elements;
    while (NumElements--) {   // Read all of the elements of the constant.
      unsigned Slot;
      if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
      Value *V = getValue(AT->getElementType(), Slot, false);
      if (!V || !isa<Constant>(V)) return failure(true);
      Elements.push_back(cast<Constant>(V));
    }
    V = ConstantArray::get(AT, Elements);
    break;
  }

  case Type::StructTyID: {
    const StructType *ST = cast<StructType>(Ty);
    const StructType::ElementTypes &ET = ST->getElementTypes();

    std::vector<Constant *> Elements;
    for (unsigned i = 0; i < ET.size(); ++i) {
      unsigned Slot;
      if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
      Value *V = getValue(ET[i], Slot, false);
      if (!V || !isa<Constant>(V))
	return failure(true);
      Elements.push_back(cast<Constant>(V));
    }

    V = ConstantStruct::get(ST, Elements);
    break;
  }

  case Type::PointerTyID: {
    const PointerType *PT = cast<const PointerType>(Ty);
    unsigned SubClass;
    if (read_vbr(Buf, EndBuf, SubClass)) return failure(true);
    switch (SubClass) {
    case 0:    // ConstantPointerNull value...
      V = ConstantPointerNull::get(PT);
      break;

    case 1: {  // ConstantPointerRef value...
      unsigned Slot;
      if (read_vbr(Buf, EndBuf, Slot)) return failure(true);
      BCR_TRACE(4, "CPR: Type: '" << Ty << "'  slot: " << Slot << "\n");

      // Check to see if we have already read this global variable yet...
      Value *Val = getValue(PT, Slot, false);
      GlobalValue* GV;
      if (Val) {
        if (!(GV = dyn_cast<GlobalValue>(Val))) return failure(true);
        BCR_TRACE(5, "Value Found in ValueTable!\n");
      } else {         // Nope... find or create a forward ref. for it
        GV = fwdRefs.GetFwdRefToGlobal(PT, Slot);
      }
      V = ConstantPointerRef::get(GV);
      break;
    }

    default:
      BCR_TRACE(5, "UNKNOWN Pointer Constant Type!\n");
      return failure(true);
    }
    break;
  }

  default:
    std::cerr << __FILE__ << ":" << __LINE__
              << ": Don't know how to deserialize constant value of type '"
              << Ty->getName() << "'\n";
    return failure(true);
  }

  return false;
}

bool BytecodeParser::ParseConstantPool(const uchar *&Buf, const uchar *EndBuf,
				       ValueTable &Tab,
				       TypeValuesListTy &TypeTab) {
  while (Buf < EndBuf) {
    unsigned NumEntries, Typ;

    if (read_vbr(Buf, EndBuf, NumEntries) ||
        read_vbr(Buf, EndBuf, Typ)) return failure(true);
    const Type *Ty = getType(Typ);
    if (Ty == 0) return failure(true);
    BCR_TRACE(3, "Type: '" << Ty << "'  NumEntries: " << NumEntries << "\n");

    if (Typ == Type::TypeTyID) {
      if (parseTypeConstants(Buf, EndBuf, TypeTab, NumEntries)) return true;
    } else {
      for (unsigned i = 0; i < NumEntries; ++i) {
	Constant *I;
        int Slot;
	if (parseConstantValue(Buf, EndBuf, Ty, I)) return failure(true);
        assert(I && "parseConstantValue returned `!failure' and NULL result");
	BCR_TRACE(4, "Read Constant: '" << I << "'\n");
	if ((Slot = insertValue(I, Tab)) < 0) return failure(true);
        resolveRefsToConstant(I, (unsigned) Slot);
      }
    }
  }

  if (Buf > EndBuf) return failure(true);
  return false;
}
<|endoftext|>


<commit_before>#include "jakmuse_common.h"
#include <cstdint>
#include <vector>
#include <cstdio>

static void wav_write_header(FILE* f, unsigned samplPerSec, unsigned numSamples)
{
    struct wav_header_s {
        uint32_t ckId;
        uint32_t cksize;
        uint32_t WAVEID;
        uint32_t fmt_ckId;
        uint32_t fmt_cksize;
        uint16_t wFormatTag;
        uint16_t nChannels;
        uint32_t nSamplesPerSec;
        uint32_t nAvgBytesPerSec;
        uint16_t nBlockAlign;
        uint16_t wBitsPerSample;
        uint32_t data_ckId;
        uint32_t data_cksize;
    } header = {
        'RIFF',
        4 + 24 + (8 + 2 /*B per sample*/ * 1 /*N channels*/ * numSamples + 0),
        'WAVE',
        'fmt ',
        16,
        0x0001,
        2,
        samplPerSec,
        samplPerSec * 2 * 1,
        2 * 1,
        16,
        'data',
        2 * 1 * numSamples,
    };

    fwrite(&header, sizeof(wav_header_s), 1, f);
}

static void wav_write_samples(FILE* f, std::vector<short> const& samples)
{
    fwrite(samples.data(), sizeof(short), samples.size(), f);
}

bool wav_write_file(std::string const& filename, std::vector<short> const& samples, unsigned samples_per_second)
{
    FILE* f = fopen(filename.c_str(), "wb");
    if(!f) {
        fprintf(stderr, "failed to open %s for writing\n", filename.c_str());
        return false;
    }

    wav_write_header(f, samples_per_second, samples.size());
    wav_write_samples(f, samples);

    fclose(f);

    return true;
}
<commit_msg>...only one channel<commit_after>#include "jakmuse_common.h"
#include <cstdint>
#include <vector>
#include <cstdio>

static void wav_write_header(FILE* f, unsigned samplPerSec, unsigned numSamples)
{
    struct wav_header_s {
        uint32_t ckId;
        uint32_t cksize;
        uint32_t WAVEID;
        uint32_t fmt_ckId;
        uint32_t fmt_cksize;
        uint16_t wFormatTag;
        uint16_t nChannels;
        uint32_t nSamplesPerSec;
        uint32_t nAvgBytesPerSec;
        uint16_t nBlockAlign;
        uint16_t wBitsPerSample;
        uint32_t data_ckId;
        uint32_t data_cksize;
    } header = {
        'RIFF',
        4 + 24 + (8 + 2 /*B per sample*/ * 1 /*N channels*/ * numSamples + 0),
        'WAVE',
        'fmt ',
        16,
        0x0001,
        1,
        samplPerSec,
        samplPerSec * 2 * 1,
        2 * 1,
        16,
        'data',
        2 * 1 * numSamples,
    };

    fwrite(&header, sizeof(wav_header_s), 1, f);
}

static void wav_write_samples(FILE* f, std::vector<short> const& samples)
{
    fwrite(samples.data(), sizeof(short), samples.size(), f);
}

bool wav_write_file(std::string const& filename, std::vector<short> const& samples, unsigned samples_per_second)
{
    FILE* f = fopen(filename.c_str(), "wb");
    if(!f) {
        fprintf(stderr, "failed to open %s for writing\n", filename.c_str());
        return false;
    }

    wav_write_header(f, samples_per_second, samples.size());
    wav_write_samples(f, samples);

    fclose(f);

    return true;
}
<|endoftext|>


<commit_before>/** @file
 *
 * @ingroup modularLibrary
 *
 * @brief A Preset Object
 *
 * @details
 *
 * @authors Théo de la Hogue
 *
 * @copyright © 2010, Théo de la Hogue @n
 * This code is licensed under the terms of the "New BSD License" @n
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTPreset.h"

#define thisTTClass			TTPreset
#define thisTTClassName		"Preset"
#define thisTTClassTags		"preset"

TT_MODULAR_CONSTRUCTOR,
mName(kTTSymEmpty),
mDescription("something about this preset"),
mAddress(kTTAdrsEmpty),
mDirectory(NULL),
mScript(NULL)
{
	TT_ASSERT("Correct number of args to create TTPreset", arguments.size() == 0 || arguments.size() == 1);

	addAttribute(Name, kTypeSymbol);
    addAttribute(Description, kTypeSymbol);
	addAttributeWithSetter(Address, kTypeSymbol);

	addMessage(Clear);
	addMessage(Store);
    addMessage(Update);
	addMessageWithArguments(Recall);
    addMessageWithArguments(Output);

	// needed to be handled by a TTXmlHandler
	addMessageWithArguments(WriteAsXml);
	addMessageProperty(WriteAsXml, hidden, YES);
	addMessageWithArguments(ReadFromXml);
	addMessageProperty(ReadFromXml, hidden, YES);

	// needed to be handled by a TTTextHandler
	addMessageWithArguments(WriteAsText);
	addMessageProperty(WriteAsText, hidden, YES);
	addMessageWithArguments(ReadFromText);
	addMessageProperty(ReadFromText, hidden, YES);

	TTObjectBaseInstantiate(kTTSym_Script, TTObjectBaseHandle(&mScript), arguments);
}

TTPreset::~TTPreset()
{
    if (mScript) {
        TTObjectBaseRelease(TTObjectBaseHandle(&mScript));
        mScript = NULL;
    }
}

TTErr TTPreset::setAddress(const TTValue& value)
{
	Clear();
	mAddress = value[0];

	mDirectory = getDirectoryFrom(mAddress);

	if (mDirectory) {

		mScript->setAttributeValue(kTTSym_address, mAddress);
		return kTTErrNone;
	}
	else
		return kTTErrGeneric; // else wait for directory or not ?
}

TTErr TTPreset::Store()
{
	TTNodePtr		aNode;
	TTObjectBasePtr	anObject;
	TTList			aNodeList, allObjectNodes;
	TTAddress       aRelativeAddress;
	TTValue			v, parsedLine;

	Clear();

	if (mDirectory) {

		// 1. Append a preset flag with the name
		v = TTValue(TTSymbol("preset"));
		v.append(mName);
		mScript->sendMessage(TTSymbol("AppendFlag"), v, parsedLine);

        // 2. Append a description flag with the description
		v = TTValue(TTSymbol("description"));
		v.append(mDescription);
		mScript->sendMessage(TTSymbol("AppendFlag"), v, parsedLine);

		// 3. Append a comment line at the beginning
		v = TTValue(TTSymbol("###########################################"));
		mScript->sendMessage(TTSymbol("AppendComment"), v, parsedLine);

        // 4. Append an empty comment line
        v.clear();
		mScript->sendMessage(TTSymbol("AppendComment"), v, parsedLine);

		// 5. Look for all Objects under the address into the directory
		mDirectory->Lookup(mAddress, aNodeList, &aNode);
		mDirectory->LookFor(&aNodeList, &TTPresetTestObject, NULL, allObjectNodes, &aNode);

		// 6. Sort the NodeList using object priority order
		allObjectNodes.sort(&compareNodePriorityThenNameThenInstance);

		// 7. Append a script line for each object found
		for (allObjectNodes.begin(); allObjectNodes.end(); allObjectNodes.next()) {

			aNode = TTNodePtr((TTPtr)allObjectNodes.current()[0]);

			// get relative address
			aNode->getAddress(aRelativeAddress, mAddress);

			// get object
			anObject = aNode->getObject();

			// append command line
			if (anObject) {

				// DATA case
				if (anObject->getName() == kTTSym_Data) {

					v.clear();
					anObject->getAttributeValue(kTTSym_value, v);

					if (v.empty())
						continue;

					v.prepend(aRelativeAddress);
					mScript->sendMessage(TTSymbol("AppendCommand"), v, parsedLine);
				}
			}
		}

        // 8. Append an empty comment line
        v.clear();
		mScript->sendMessage(TTSymbol("AppendComment"), v, parsedLine);

        // 9. Append a comment line at the end
		v = TTValue(TTSymbol("###########################################"));
		mScript->sendMessage(TTSymbol("AppendComment"), v, parsedLine);

		return kTTErrNone;
	}
	else
		return kTTErrGeneric;
}

TTErr TTPreset::Update()
{
    TTValue     v, none;
    TTBoolean   flattened;

    // is the preset already flattened ?
    mScript->getAttributeValue(kTTSym_flattened, v);
    flattened = v[0];

    if (!flattened)
        mScript->sendMessage(kTTSym_Flatten, mAddress, none);

	return processUpdate(mScript);
}

TTErr TTPreset::processUpdate(TTObjectBasePtr aScript)
{
	TTListPtr		lines;
	TTDictionaryBasePtr	aLine;
    TTAddress       anAddress;
    TTNodePtr       aNode;
	TTObjectBasePtr	anObject;
    TTSymbol        service;
	TTValue			v;
    TTErr           err;

	aScript->getAttributeValue(TTSymbol("flattenedLines"), v);
	lines = TTListPtr((TTPtr)v[0]);

	// lookat each line of the script
	for (lines->begin(); lines->end(); lines->next()) {

		aLine = TTDictionaryBasePtr((TTPtr)lines->current()[0]);

        // if it is a Data object
        if (!aLine->lookup(kTTSym_target, v)) {

            anAddress = v[0];
            err = getDirectoryFrom(anAddress)->getTTNode(anAddress, &aNode);

            if (!err) {

                anObject = aNode->getObject();

                if (anObject) {

                    if (anObject->getName() == kTTSym_Data) {

                        // get his service attribute value
                        anObject->getAttributeValue(kTTSym_service, v);
                        service = v[0];

                        // update only parameters
                        if (service == kTTSym_parameter) {

                            // get his current value
                            err = anObject->getAttributeValue(kTTSym_value, v);

                            if (!err) {

                                // replace the former value
                                aLine->remove(kTTSym_value);
                                aLine->append(kTTSym_value, v);
                            }
                        }
                    }
                }
            }
        }
	}

	return kTTErrNone;
}

TTErr TTPreset::Clear()
{
	return mScript->sendMessage(TTSymbol("Clear"));
}

TTErr TTPreset::Recall(const TTValue& inputValue, TTValue& outputValue)
{
    TTAddress       anAddress = kTTAdrsRoot;
    TTBoolean       flattened;
    TTValue         v, none;

    if (inputValue.size() == 1)
        if (inputValue[0].type() == kTypeSymbol)
            anAddress = inputValue[0];

    // is the cue already flattened ?
    mScript->getAttributeValue(kTTSym_flattened, v);
    flattened = v[0];

    if (!flattened)
        mScript->sendMessage(kTTSym_Flatten, mAddress, none);

    // if an address is passed, run the line at address
    if (anAddress != kTTAdrsRoot)
        return mScript->sendMessage(TTSymbol("RunCommand"), inputValue, none);

    // else run all the script
    else
        return mScript->sendMessage(kTTSym_Run, mAddress, none);
}

TTErr TTPreset::Output(const TTValue& inputValue, TTValue& outputValue)
{
    TTAddress   anAddress = kTTAdrsRoot;
    TTBoolean   flattened;
    TTValue     v, none;

    if (inputValue.size() == 1)
        if (inputValue[0].type() == kTypeSymbol)
            anAddress = inputValue[0];

    // is the preset already flattened ?
    mScript->getAttributeValue(kTTSym_flattened, v);
    flattened = v[0];

    if (!flattened)
        mScript->sendMessage(kTTSym_Flatten, kTTAdrsRoot, none);

    // if an address is passed, dump the line at address
    if (anAddress != kTTAdrsRoot)
        return mScript->sendMessage(TTSymbol("DumpLine"), inputValue, none);

    // else dump all the script
    else
        return mScript->sendMessage(kTTSym_Dump, inputValue, none);
}

TTErr TTPreset::WriteAsXml(const TTValue& inputValue, TTValue& outputValue)
{
	TTXmlHandlerPtr		aXmlHandler = NULL;
	TTValue				v;

	aXmlHandler = TTXmlHandlerPtr((TTObjectBasePtr)inputValue[0]);

	// use WriteAsXml of the script
	v = TTValue(mScript);
	aXmlHandler->setAttributeValue(kTTSym_object, v);
	aXmlHandler->sendMessage(TTSymbol("Write"));

	return kTTErrNone;
}

TTErr TTPreset::ReadFromXml(const TTValue& inputValue, TTValue& outputValue)
{
	TTXmlHandlerPtr		aXmlHandler = NULL;
	TTValue				v, parsedLine;

	aXmlHandler = TTXmlHandlerPtr((TTObjectBasePtr)inputValue[0]);

	// Preset node : append a preset flag with the name
	if (aXmlHandler->mXmlNodeName == TTSymbol("preset")) {

		if (!aXmlHandler->mXmlNodeStart)
			return kTTErrNone;

		v = TTValue(TTSymbol("preset"));
		v.append(mName);
		mScript->sendMessage(TTSymbol("AppendFlag"), v, parsedLine);

		return kTTErrNone;
	}

	// use ReadFromXml of the script
	v = TTValue(mScript);
	aXmlHandler->setAttributeValue(kTTSym_object, v);
	aXmlHandler->sendMessage(TTSymbol("Read"));

	return kTTErrNone;
}

TTErr TTPreset::WriteAsText(const TTValue& inputValue, TTValue& outputValue)
{
	TTTextHandlerPtr aTextHandler;
    TTBoolean flattened;
	TTValue	v;

	aTextHandler = TTTextHandlerPtr((TTObjectBasePtr)inputValue[0]);

    // théo - since the workshop in june 2014 in Albi we decide to force the script to be flattened
    // but we should review all the #TTCue and #TTScript architecture to improve this
    // so here we need to unflatten the script before to write it ...

    // is the preset already flattened ?
    mScript->getAttributeValue(kTTSym_flattened, v);
    flattened = v[0];

    if (flattened)
        mScript->sendMessage("Unflatten");

	// use WriteAsBuffer of the script
	v = TTValue(mScript);
	aTextHandler->setAttributeValue(kTTSym_object, v);
	aTextHandler->sendMessage(TTSymbol("Write"));

	return kTTErrNone;
}

TTErr TTPreset::ReadFromText(const TTValue& inputValue, TTValue& outputValue)
{
	TTTextHandlerPtr aTextHandler;
    TTDictionaryBasePtr line;
	TTValue	v;

	aTextHandler = TTTextHandlerPtr((TTObjectBasePtr)inputValue[0]);

	// if it is the first line :
	if (aTextHandler->mFirstLine)
		Clear();

    if (inputValue.size() == 0)
        return kTTErrGeneric;

    // if needed : parse the buffer line into TTDictionary
    if ((*(aTextHandler->mLine))[0].type() != kTypePointer) {

        line = TTScriptParseLine(*(aTextHandler->mLine));

        if (line)

            // replace the buffer line value by the parsed line dictionary
            aTextHandler->mLine = new TTValue((TTPtr)line);
    }
    else
        line = TTDictionaryBasePtr((TTPtr)aTextHandler->mLine[0]);

    // match description or tag flag lines :
    if (line->getSchema() == kTTSym_flag) {

        line->lookup(kTTSym_name, v);
        TTSymbol flagName = v[0];

        if (flagName == TTSymbol("description")) {

            // get description
            if (!line->getValue(v)) {

                mDescription = v[0];
            }
        }
    }

	// use ReadFromText of the script
	v = TTValue(mScript);
	aTextHandler->setAttributeValue(kTTSym_object, v);
	aTextHandler->sendMessage(TTSymbol("Read"));

	return kTTErrNone;
}

#if 0
#pragma mark -
#pragma mark Some Methods
#endif

TTBoolean TTPresetTestObject(TTNodePtr node, TTPtr args)
{
	TTObjectBasePtr o;
	TTValue		v;
	TTSymbol    s;

	// Here we decide to keep nodes which binds on :
	//		- Data with @service == parameter
	o = node->getObject();
	if (o) {

		if (o->getName() == kTTSym_Data) {
			o->getAttributeValue(kTTSym_service, v);
			s = v[0];
			return s == kTTSym_parameter;
		}
	}

	return NO;
}

TTErr TTPresetInterpolate(TTPreset* preset1, TTPreset* preset2, TTFloat64 position)
{
    TTBoolean   flattened1, flattened2;
    TTValue     v, none;

    // is the preset1 already flattened ?
    preset1->mScript->getAttributeValue(kTTSym_flattened, v);
    flattened1 = v[0];

    if (!flattened1)
        preset1->mScript->sendMessage(kTTSym_Flatten, preset1->mAddress, none);

    // is the preset2 already flattened ?
    preset2->mScript->getAttributeValue(kTTSym_flattened, v);
    flattened2 = v[0];

    if (!flattened2)
        preset2->mScript->sendMessage(kTTSym_Flatten, preset2->mAddress, none);

	return TTScriptInterpolate(preset1->mScript, preset2->mScript, position);
}

TTErr TTPresetMix(const TTValue& presets, const TTValue& factors)
{
	TTPresetPtr aPreset;
	TTValue		scripts;
    TTBoolean   flattened;
    TTValue     v, none;
	TTUInt32	i;

	for (i = 0; i < presets.size(); i++) {

		aPreset = TTPresetPtr((TTObjectBasePtr)presets[i]);

        // is the preset1 already flattened ?
        aPreset->mScript->getAttributeValue(kTTSym_flattened, v);
        flattened = v[0];

        if (!flattened)
            aPreset->mScript->sendMessage(kTTSym_Flatten, aPreset->mAddress, none);

		scripts.append(aPreset->mScript);
	}

	return TTScriptMix(scripts, factors);
}

TTErr TTPresetCopy(TTPreset* aPresetToCopy, TTPreset* aPresetCopy)
{
	TTValue v, args;

	aPresetCopy->mName = aPresetToCopy->mName;
	aPresetCopy->mAddress = aPresetToCopy->mAddress;
	aPresetCopy->mDirectory = aPresetToCopy->mDirectory;
	return TTScriptCopy(aPresetToCopy->mScript, aPresetCopy->mScript);
}
<commit_msg>Fixing JamomaMax #724 issue<commit_after>/** @file
 *
 * @ingroup modularLibrary
 *
 * @brief A Preset Object
 *
 * @details
 *
 * @authors Théo de la Hogue
 *
 * @copyright © 2010, Théo de la Hogue @n
 * This code is licensed under the terms of the "New BSD License" @n
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTPreset.h"

#define thisTTClass			TTPreset
#define thisTTClassName		"Preset"
#define thisTTClassTags		"preset"

TT_MODULAR_CONSTRUCTOR,
mName(kTTSymEmpty),
mDescription("something about this preset"),
mAddress(kTTAdrsEmpty),
mDirectory(NULL),
mScript(NULL)
{
	TT_ASSERT("Correct number of args to create TTPreset", arguments.size() == 0 || arguments.size() == 1);

	addAttribute(Name, kTypeSymbol);
    addAttribute(Description, kTypeSymbol);
	addAttributeWithSetter(Address, kTypeSymbol);

	addMessage(Clear);
	addMessage(Store);
    addMessage(Update);
	addMessageWithArguments(Recall);
    addMessageWithArguments(Output);

	// needed to be handled by a TTXmlHandler
	addMessageWithArguments(WriteAsXml);
	addMessageProperty(WriteAsXml, hidden, YES);
	addMessageWithArguments(ReadFromXml);
	addMessageProperty(ReadFromXml, hidden, YES);

	// needed to be handled by a TTTextHandler
	addMessageWithArguments(WriteAsText);
	addMessageProperty(WriteAsText, hidden, YES);
	addMessageWithArguments(ReadFromText);
	addMessageProperty(ReadFromText, hidden, YES);

	TTObjectBaseInstantiate(kTTSym_Script, TTObjectBaseHandle(&mScript), arguments);
}

TTPreset::~TTPreset()
{
    if (mScript) {
        TTObjectBaseRelease(TTObjectBaseHandle(&mScript));
        mScript = NULL;
    }
}

TTErr TTPreset::setAddress(const TTValue& value)
{
	Clear();
	mAddress = value[0];

	mDirectory = getDirectoryFrom(mAddress);

	if (mDirectory) {

		mScript->setAttributeValue(kTTSym_address, mAddress);
		return kTTErrNone;
	}
	else
		return kTTErrGeneric; // else wait for directory or not ?
}

TTErr TTPreset::Store()
{
	TTNodePtr		aNode;
	TTObjectBasePtr	anObject;
	TTList			aNodeList, allObjectNodes;
	TTAddress       aRelativeAddress;
	TTValue			v, parsedLine;

	Clear();

	if (mDirectory) {

		// 1. Append a preset flag with the name
		v = TTValue(TTSymbol("preset"));
		v.append(mName);
		mScript->sendMessage(TTSymbol("AppendFlag"), v, parsedLine);

        // 2. Append a description flag with the description
		v = TTValue(TTSymbol("description"));
		v.append(mDescription);
		mScript->sendMessage(TTSymbol("AppendFlag"), v, parsedLine);

		// 3. Append a comment line at the beginning
		v = TTValue(TTSymbol("###########################################"));
		mScript->sendMessage(TTSymbol("AppendComment"), v, parsedLine);

        // 4. Append an empty comment line
        v.clear();
		mScript->sendMessage(TTSymbol("AppendComment"), v, parsedLine);

		// 5. Look for all Objects under the address into the directory
		mDirectory->Lookup(mAddress, aNodeList, &aNode);
		mDirectory->LookFor(&aNodeList, &TTPresetTestObject, NULL, allObjectNodes, &aNode);

		// 6. Sort the NodeList using object priority order
		allObjectNodes.sort(&compareNodePriorityThenNameThenInstance);

		// 7. Append a script line for each object found
		for (allObjectNodes.begin(); allObjectNodes.end(); allObjectNodes.next()) {

			aNode = TTNodePtr((TTPtr)allObjectNodes.current()[0]);

			// get relative address
			aNode->getAddress(aRelativeAddress, mAddress);

			// get object
			anObject = aNode->getObject();

			// append command line
			if (anObject) {

				// DATA case
				if (anObject->getName() == kTTSym_Data) {

					v.clear();
					anObject->getAttributeValue(kTTSym_value, v);

					if (v.empty())
						continue;

					v.prepend(aRelativeAddress);
					mScript->sendMessage(TTSymbol("AppendCommand"), v, parsedLine);
				}
			}
		}

        // 8. Append an empty comment line
        v.clear();
		mScript->sendMessage(TTSymbol("AppendComment"), v, parsedLine);

        // 9. Append a comment line at the end
		v = TTValue(TTSymbol("###########################################"));
		mScript->sendMessage(TTSymbol("AppendComment"), v, parsedLine);

		return kTTErrNone;
	}
	else
		return kTTErrGeneric;
}

TTErr TTPreset::Update()
{
    TTValue     v, none;
    TTBoolean   flattened;

    // is the preset already flattened ?
    mScript->getAttributeValue(kTTSym_flattened, v);
    flattened = v[0];

    if (!flattened)
        mScript->sendMessage(kTTSym_Flatten, mAddress, none);

	return processUpdate(mScript);
}

TTErr TTPreset::processUpdate(TTObjectBasePtr aScript)
{
	TTListPtr		lines;
	TTDictionaryBasePtr	aLine;
    TTAddress       anAddress;
    TTNodePtr       aNode;
	TTObjectBasePtr	anObject;
    TTSymbol        service;
	TTValue			v;
    TTErr           err;

	aScript->getAttributeValue(TTSymbol("flattenedLines"), v);
	lines = TTListPtr((TTPtr)v[0]);

	// lookat each line of the script
	for (lines->begin(); lines->end(); lines->next()) {

		aLine = TTDictionaryBasePtr((TTPtr)lines->current()[0]);

        // if it is a Data object
        if (!aLine->lookup(kTTSym_target, v)) {

            anAddress = v[0];
            err = getDirectoryFrom(anAddress)->getTTNode(anAddress, &aNode);

            if (!err) {

                anObject = aNode->getObject();

                if (anObject) {

                    if (anObject->getName() == kTTSym_Data) {

                        // get his service attribute value
                        anObject->getAttributeValue(kTTSym_service, v);
                        service = v[0];

                        // update only parameters
                        if (service == kTTSym_parameter) {

                            // get his current value
                            err = anObject->getAttributeValue(kTTSym_value, v);

                            if (!err) {

                                // replace the former value
                                aLine->remove(kTTSym_value);
                                aLine->append(kTTSym_value, v);
                            }
                        }
                    }
                }
            }
        }
	}

	return kTTErrNone;
}

TTErr TTPreset::Clear()
{
	return mScript->sendMessage(TTSymbol("Clear"));
}

TTErr TTPreset::Recall(const TTValue& inputValue, TTValue& outputValue)
{
    TTAddress       anAddress = kTTAdrsRoot;
    TTBoolean       flattened;
    TTValue         v, none;

    if (inputValue.size() == 1)
        if (inputValue[0].type() == kTypeSymbol)
            anAddress = inputValue[0];

    // is the cue already flattened ?
    mScript->getAttributeValue(kTTSym_flattened, v);
    flattened = v[0];

    if (!flattened)
        mScript->sendMessage(kTTSym_Flatten, mAddress, none);

    // if an address is passed, run the line at address
    if (anAddress != kTTAdrsRoot)
        return mScript->sendMessage(TTSymbol("RunCommand"), inputValue, none);

    // else run all the script
    else
        return mScript->sendMessage(kTTSym_Run, mAddress, none);
}

TTErr TTPreset::Output(const TTValue& inputValue, TTValue& outputValue)
{
    TTAddress   anAddress = kTTAdrsRoot;
    TTBoolean   flattened;
    TTValue     v, none;

    if (inputValue.size() == 1)
        if (inputValue[0].type() == kTypeSymbol)
            anAddress = inputValue[0];

    // is the preset already flattened ?
    mScript->getAttributeValue(kTTSym_flattened, v);
    flattened = v[0];

    if (!flattened)
        mScript->sendMessage(kTTSym_Flatten, kTTAdrsRoot, none);

    // if an address is passed, dump the line at address
    if (anAddress != kTTAdrsRoot)
        return mScript->sendMessage(TTSymbol("DumpLine"), inputValue, none);

    // else dump all the script
    else
        return mScript->sendMessage(kTTSym_Dump, inputValue, none);
}

TTErr TTPreset::WriteAsXml(const TTValue& inputValue, TTValue& outputValue)
{
	TTXmlHandlerPtr		aXmlHandler = NULL;
	TTValue				v;

	aXmlHandler = TTXmlHandlerPtr((TTObjectBasePtr)inputValue[0]);

	// use WriteAsXml of the script
	v = TTValue(mScript);
	aXmlHandler->setAttributeValue(kTTSym_object, v);
	aXmlHandler->sendMessage(TTSymbol("Write"));

	return kTTErrNone;
}

TTErr TTPreset::ReadFromXml(const TTValue& inputValue, TTValue& outputValue)
{
	TTXmlHandlerPtr		aXmlHandler = NULL;
	TTValue				v, parsedLine;

	aXmlHandler = TTXmlHandlerPtr((TTObjectBasePtr)inputValue[0]);

	// Preset node : append a preset flag with the name
	if (aXmlHandler->mXmlNodeName == TTSymbol("preset")) {

		if (!aXmlHandler->mXmlNodeStart)
			return kTTErrNone;

		v = TTValue(TTSymbol("preset"));
		v.append(mName);
		mScript->sendMessage(TTSymbol("AppendFlag"), v, parsedLine);

		return kTTErrNone;
	}

	// use ReadFromXml of the script
	v = TTValue(mScript);
	aXmlHandler->setAttributeValue(kTTSym_object, v);
	aXmlHandler->sendMessage(TTSymbol("Read"));

	return kTTErrNone;
}

TTErr TTPreset::WriteAsText(const TTValue& inputValue, TTValue& outputValue)
{
	TTTextHandlerPtr aTextHandler;
    TTBoolean flattened;
	TTValue	v;

	aTextHandler = TTTextHandlerPtr((TTObjectBasePtr)inputValue[0]);

    // théo - since the workshop in june 2014 in Albi we decide to force the script to be flattened
    // but we should review all the #TTCue and #TTScript architecture to improve this
    // so here we need to unflatten the script before to write it ...

    // is the preset already flattened ?
    mScript->getAttributeValue(kTTSym_flattened, v);
    flattened = v[0];

    if (flattened)
        mScript->sendMessage("Unflatten");

	// use WriteAsBuffer of the script
	v = TTValue(mScript);
	aTextHandler->setAttributeValue(kTTSym_object, v);
	aTextHandler->sendMessage(TTSymbol("Write"));

	return kTTErrNone;
}

TTErr TTPreset::ReadFromText(const TTValue& inputValue, TTValue& outputValue)
{
	TTTextHandlerPtr aTextHandler;
    TTDictionaryBasePtr line;
	TTValue	v;

	aTextHandler = TTTextHandlerPtr((TTObjectBasePtr)inputValue[0]);

	// if it is the first line :
	if (aTextHandler->mFirstLine)
		Clear();

    if (inputValue.size() == 0)
        return kTTErrGeneric;

    // if needed : parse the buffer line into TTDictionary
    if ((*(aTextHandler->mLine))[0].type() != kTypePointer) {

        line = TTScriptParseLine(*(aTextHandler->mLine));

        if (line)

            // replace the buffer line value by the parsed line dictionary
            aTextHandler->mLine = new TTValue((TTPtr)line);
    }
    else
        line = TTDictionaryBasePtr((TTPtr)aTextHandler->mLine[0]);

    // match description or tag flag lines :
    if (line) {

        if (line->getSchema() == kTTSym_flag) {

            line->lookup(kTTSym_name, v);
            TTSymbol flagName = v[0];

            if (flagName == TTSymbol("description")) {

                // get description
                if (!line->getValue(v)) {

                    mDescription = v[0];
                }
            }
        }
    }

	// use ReadFromText of the script
	v = TTValue(mScript);
	aTextHandler->setAttributeValue(kTTSym_object, v);
	aTextHandler->sendMessage(TTSymbol("Read"));

	return kTTErrNone;
}

#if 0
#pragma mark -
#pragma mark Some Methods
#endif

TTBoolean TTPresetTestObject(TTNodePtr node, TTPtr args)
{
	TTObjectBasePtr o;
	TTValue		v;
	TTSymbol    s;

	// Here we decide to keep nodes which binds on :
	//		- Data with @service == parameter
	o = node->getObject();
	if (o) {

		if (o->getName() == kTTSym_Data) {
			o->getAttributeValue(kTTSym_service, v);
			s = v[0];
			return s == kTTSym_parameter;
		}
	}

	return NO;
}

TTErr TTPresetInterpolate(TTPreset* preset1, TTPreset* preset2, TTFloat64 position)
{
    TTBoolean   flattened1, flattened2;
    TTValue     v, none;

    // is the preset1 already flattened ?
    preset1->mScript->getAttributeValue(kTTSym_flattened, v);
    flattened1 = v[0];

    if (!flattened1)
        preset1->mScript->sendMessage(kTTSym_Flatten, preset1->mAddress, none);

    // is the preset2 already flattened ?
    preset2->mScript->getAttributeValue(kTTSym_flattened, v);
    flattened2 = v[0];

    if (!flattened2)
        preset2->mScript->sendMessage(kTTSym_Flatten, preset2->mAddress, none);

	return TTScriptInterpolate(preset1->mScript, preset2->mScript, position);
}

TTErr TTPresetMix(const TTValue& presets, const TTValue& factors)
{
	TTPresetPtr aPreset;
	TTValue		scripts;
    TTBoolean   flattened;
    TTValue     v, none;
	TTUInt32	i;

	for (i = 0; i < presets.size(); i++) {

		aPreset = TTPresetPtr((TTObjectBasePtr)presets[i]);

        // is the preset1 already flattened ?
        aPreset->mScript->getAttributeValue(kTTSym_flattened, v);
        flattened = v[0];

        if (!flattened)
            aPreset->mScript->sendMessage(kTTSym_Flatten, aPreset->mAddress, none);

		scripts.append(aPreset->mScript);
	}

	return TTScriptMix(scripts, factors);
}

TTErr TTPresetCopy(TTPreset* aPresetToCopy, TTPreset* aPresetCopy)
{
	TTValue v, args;

	aPresetCopy->mName = aPresetToCopy->mName;
	aPresetCopy->mAddress = aPresetToCopy->mAddress;
	aPresetCopy->mDirectory = aPresetToCopy->mDirectory;
	return TTScriptCopy(aPresetToCopy->mScript, aPresetCopy->mScript);
}
<|endoftext|>


<commit_before>//===- ReaderWrappers.cpp - Parse bytecode from file or buffer  -----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements loading and parsing a bytecode file and parsing a
// bytecode module from a given buffer.
//
//===----------------------------------------------------------------------===//

#include "llvm/Bytecode/Analyzer.h"
#include "llvm/Bytecode/Reader.h"
#include "Reader.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Config/unistd.h"
#include <cerrno>
using namespace llvm;

//===----------------------------------------------------------------------===//
// BytecodeFileReader - Read from an mmap'able file descriptor.
//

namespace {
  /// BytecodeFileReader - parses a bytecode file from a file
  ///
  class BytecodeFileReader : public BytecodeReader {
  private:
    unsigned char *Buffer;
    unsigned Length;

    BytecodeFileReader(const BytecodeFileReader&); // Do not implement
    void operator=(const BytecodeFileReader &BFR); // Do not implement

  public:
    BytecodeFileReader(const std::string &Filename, llvm::BytecodeHandler* H=0);
    ~BytecodeFileReader();
  };
}

static std::string ErrnoMessage (int savedErrNum, std::string descr) {
   return ::strerror(savedErrNum) + std::string(", while trying to ") + descr;
}

BytecodeFileReader::BytecodeFileReader(const std::string &Filename,
                                       llvm::BytecodeHandler* H )
  : BytecodeReader(H)
{
  Buffer = (unsigned char*)ReadFileIntoAddressSpace(Filename, Length);
  if (Buffer == 0)
    throw "Error reading file '" + Filename + "'.";

  try {
    // Parse the bytecode we mmapped in
    ParseBytecode(Buffer, Length, Filename);
  } catch (...) {
    UnmapFileFromAddressSpace(Buffer, Length);
    throw;
  }
}

BytecodeFileReader::~BytecodeFileReader() {
  // Unmmap the bytecode...
  UnmapFileFromAddressSpace(Buffer, Length);
}

//===----------------------------------------------------------------------===//
// BytecodeBufferReader - Read from a memory buffer
//

namespace {
  /// BytecodeBufferReader - parses a bytecode file from a buffer
  ///
  class BytecodeBufferReader : public BytecodeReader {
  private:
    const unsigned char *Buffer;
    bool MustDelete;

    BytecodeBufferReader(const BytecodeBufferReader&); // Do not implement
    void operator=(const BytecodeBufferReader &BFR);   // Do not implement

  public:
    BytecodeBufferReader(const unsigned char *Buf, unsigned Length,
                         const std::string &ModuleID,
                         llvm::BytecodeHandler* Handler = 0);
    ~BytecodeBufferReader();

  };
}

BytecodeBufferReader::BytecodeBufferReader(const unsigned char *Buf,
                                           unsigned Length,
                                           const std::string &ModuleID,
                                           llvm::BytecodeHandler* H )
  : BytecodeReader(H)
{
  // If not aligned, allocate a new buffer to hold the bytecode...
  const unsigned char *ParseBegin = 0;
  if (reinterpret_cast<uint64_t>(Buf) & 3) {
    Buffer = new unsigned char[Length+4];
    unsigned Offset = 4 - ((intptr_t)Buffer & 3);   // Make sure it's aligned
    ParseBegin = Buffer + Offset;
    memcpy((unsigned char*)ParseBegin, Buf, Length);    // Copy it over
    MustDelete = true;
  } else {
    // If we don't need to copy it over, just use the caller's copy
    ParseBegin = Buffer = Buf;
    MustDelete = false;
  }
  try {
    ParseBytecode(ParseBegin, Length, ModuleID);
  } catch (...) {
    if (MustDelete) delete [] Buffer;
    throw;
  }
}

BytecodeBufferReader::~BytecodeBufferReader() {
  if (MustDelete) delete [] Buffer;
}

//===----------------------------------------------------------------------===//
//  BytecodeStdinReader - Read bytecode from Standard Input
//

namespace {
  /// BytecodeStdinReader - parses a bytecode file from stdin
  ///
  class BytecodeStdinReader : public BytecodeReader {
  private:
    std::vector<unsigned char> FileData;
    unsigned char *FileBuf;

    BytecodeStdinReader(const BytecodeStdinReader&); // Do not implement
    void operator=(const BytecodeStdinReader &BFR);  // Do not implement

  public:
    BytecodeStdinReader( llvm::BytecodeHandler* H = 0 );
  };
}

BytecodeStdinReader::BytecodeStdinReader( BytecodeHandler* H )
  : BytecodeReader(H)
{
  int BlockSize;
  unsigned char Buffer[4096*4];

  // Read in all of the data from stdin, we cannot mmap stdin...
  while ((BlockSize = ::read(0 /*stdin*/, Buffer, 4096*4))) {
    if (BlockSize == -1)
      throw ErrnoMessage(errno, "read from standard input");

    FileData.insert(FileData.end(), Buffer, Buffer+BlockSize);
  }

  if (FileData.empty())
    throw std::string("Standard Input empty!");

  FileBuf = &FileData[0];
  ParseBytecode(FileBuf, FileData.size(), "<stdin>");
}

//===----------------------------------------------------------------------===//
//  Varargs transmogrification code...
//

// CheckVarargs - This is used to automatically translate old-style varargs to
// new style varargs for backwards compatibility.
static ModuleProvider *CheckVarargs(ModuleProvider *MP) {
  Module *M = MP->getModule();

  // Check to see if va_start takes arguments...
  Function *F = M->getNamedFunction("llvm.va_start");
  if (F == 0) return MP;  // No varargs use, just return.

  if (F->getFunctionType()->getNumParams() == 0)
    return MP;  // Modern varargs processing, just return.

  // If we get to this point, we know that we have an old-style module.
  // Materialize the whole thing to perform the rewriting.
  MP->materializeModule();

  // If the user is making use of obsolete varargs intrinsics, adjust them for
  // the user.
  if (Function *F = M->getNamedFunction("llvm.va_start")) {
    assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");

    const Type *RetTy = F->getFunctionType()->getParamType(0);
    RetTy = cast<PointerType>(RetTy)->getElementType();
    Function *NF = M->getOrInsertFunction("llvm.va_start", RetTy, 0);

    for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
      if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
        Value *V = new CallInst(NF, "", CI);
        new StoreInst(V, CI->getOperand(1), CI);
        CI->getParent()->getInstList().erase(CI);
      }
    F->setName("");
  }

  if (Function *F = M->getNamedFunction("llvm.va_end")) {
    assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
    const Type *ArgTy = F->getFunctionType()->getParamType(0);
    ArgTy = cast<PointerType>(ArgTy)->getElementType();
    Function *NF = M->getOrInsertFunction("llvm.va_end", Type::VoidTy,
                                                  ArgTy, 0);

    for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
      if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
        Value *V = new LoadInst(CI->getOperand(1), "", CI);
        new CallInst(NF, V, "", CI);
        CI->getParent()->getInstList().erase(CI);
      }
    F->setName("");
  }

  if (Function *F = M->getNamedFunction("llvm.va_copy")) {
    assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
    const Type *ArgTy = F->getFunctionType()->getParamType(0);
    ArgTy = cast<PointerType>(ArgTy)->getElementType();
    Function *NF = M->getOrInsertFunction("llvm.va_copy", ArgTy,
                                                  ArgTy, 0);

    for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
      if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
        Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
        new StoreInst(V, CI->getOperand(1), CI);
        CI->getParent()->getInstList().erase(CI);
      }
    F->setName("");
  }
  return MP;
}

//===----------------------------------------------------------------------===//
// Wrapper functions
//===----------------------------------------------------------------------===//

/// getBytecodeBufferModuleProvider - lazy function-at-a-time loading from a
/// buffer
ModuleProvider*
llvm::getBytecodeBufferModuleProvider(const unsigned char *Buffer,
                                      unsigned Length,
                                      const std::string &ModuleID,
                                      BytecodeHandler* H ) {
  return CheckVarargs(
      new BytecodeBufferReader(Buffer, Length, ModuleID, H));
}

/// ParseBytecodeBuffer - Parse a given bytecode buffer
///
Module *llvm::ParseBytecodeBuffer(const unsigned char *Buffer, unsigned Length,
                                  const std::string &ModuleID,
                                  std::string *ErrorStr){
  try {
    std::auto_ptr<ModuleProvider>
      AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID));
    return AMP->releaseModule();
  } catch (std::string &err) {
    if (ErrorStr) *ErrorStr = err;
    return 0;
  }
}

/// getBytecodeModuleProvider - lazy function-at-a-time loading from a file
///
ModuleProvider *llvm::getBytecodeModuleProvider(const std::string &Filename,
                                                BytecodeHandler* H) {
  if (Filename != std::string("-"))        // Read from a file...
    return CheckVarargs(new BytecodeFileReader(Filename,H));
  else                                     // Read from stdin
    return CheckVarargs(new BytecodeStdinReader(H));
}

/// ParseBytecodeFile - Parse the given bytecode file
///
Module *llvm::ParseBytecodeFile(const std::string &Filename,
                                std::string *ErrorStr) {
  try {
    std::auto_ptr<ModuleProvider> AMP(getBytecodeModuleProvider(Filename));
    return AMP->releaseModule();
  } catch (std::string &err) {
    if (ErrorStr) *ErrorStr = err;
    return 0;
  }
}

// AnalyzeBytecodeFile - analyze one file
Module* llvm::AnalyzeBytecodeFile(
  const std::string &Filename,  ///< File to analyze
  BytecodeAnalysis& bca,        ///< Statistical output
  std::string *ErrorStr,        ///< Error output
  std::ostream* output          ///< Dump output
)
{
  try {
    BytecodeHandler* analyzerHandler = createBytecodeAnalyzerHandler(bca,output);
    std::auto_ptr<ModuleProvider> AMP(
      getBytecodeModuleProvider(Filename,analyzerHandler));
    return AMP->releaseModule();
  } catch (std::string &err) {
    if (ErrorStr) *ErrorStr = err;
    return 0;
  }
}

// AnalyzeBytecodeBuffer - analyze a buffer
Module* llvm::AnalyzeBytecodeBuffer(
  const unsigned char* Buffer, ///< Pointer to start of bytecode buffer
  unsigned Length,             ///< Size of the bytecode buffer
  const std::string& ModuleID, ///< Identifier for the module
  BytecodeAnalysis& bca,       ///< The results of the analysis
  std::string* ErrorStr,       ///< Errors, if any.
  std::ostream* output         ///< Dump output, if any
)
{
  try {
    BytecodeHandler* hdlr = createBytecodeAnalyzerHandler(bca, output);
    std::auto_ptr<ModuleProvider>
      AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID, hdlr));
    return AMP->releaseModule();
  } catch (std::string &err) {
    if (ErrorStr) *ErrorStr = err;
    return 0;
  }
}

bool llvm::GetBytecodeDependentLibraries(const std::string &fname,
                                         std::vector<std::string>& deplibs) {
  try {
    std::auto_ptr<ModuleProvider> AMP( getBytecodeModuleProvider(fname));
    Module* M = AMP->releaseModule();
    deplibs = M->getLibraries();
    delete M;
    return true;
  } catch (...) {
    deplibs.clear();
    return false;
  }
}

// vim: sw=2 ai
<commit_msg>Change interface to use correct typedef so it will always compile.<commit_after>//===- ReaderWrappers.cpp - Parse bytecode from file or buffer  -----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements loading and parsing a bytecode file and parsing a
// bytecode module from a given buffer.
//
//===----------------------------------------------------------------------===//

#include "llvm/Bytecode/Analyzer.h"
#include "llvm/Bytecode/Reader.h"
#include "Reader.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Config/unistd.h"
#include <cerrno>
using namespace llvm;

//===----------------------------------------------------------------------===//
// BytecodeFileReader - Read from an mmap'able file descriptor.
//

namespace {
  /// BytecodeFileReader - parses a bytecode file from a file
  ///
  class BytecodeFileReader : public BytecodeReader {
  private:
    unsigned char *Buffer;
    unsigned Length;

    BytecodeFileReader(const BytecodeFileReader&); // Do not implement
    void operator=(const BytecodeFileReader &BFR); // Do not implement

  public:
    BytecodeFileReader(const std::string &Filename, llvm::BytecodeHandler* H=0);
    ~BytecodeFileReader();
  };
}

static std::string ErrnoMessage (int savedErrNum, std::string descr) {
   return ::strerror(savedErrNum) + std::string(", while trying to ") + descr;
}

BytecodeFileReader::BytecodeFileReader(const std::string &Filename,
                                       llvm::BytecodeHandler* H )
  : BytecodeReader(H)
{
  Buffer = (unsigned char*)ReadFileIntoAddressSpace(Filename, Length);
  if (Buffer == 0)
    throw "Error reading file '" + Filename + "'.";

  try {
    // Parse the bytecode we mmapped in
    ParseBytecode(Buffer, Length, Filename);
  } catch (...) {
    UnmapFileFromAddressSpace(Buffer, Length);
    throw;
  }
}

BytecodeFileReader::~BytecodeFileReader() {
  // Unmmap the bytecode...
  UnmapFileFromAddressSpace(Buffer, Length);
}

//===----------------------------------------------------------------------===//
// BytecodeBufferReader - Read from a memory buffer
//

namespace {
  /// BytecodeBufferReader - parses a bytecode file from a buffer
  ///
  class BytecodeBufferReader : public BytecodeReader {
  private:
    const unsigned char *Buffer;
    bool MustDelete;

    BytecodeBufferReader(const BytecodeBufferReader&); // Do not implement
    void operator=(const BytecodeBufferReader &BFR);   // Do not implement

  public:
    BytecodeBufferReader(const unsigned char *Buf, unsigned Length,
                         const std::string &ModuleID,
                         llvm::BytecodeHandler* Handler = 0);
    ~BytecodeBufferReader();

  };
}

BytecodeBufferReader::BytecodeBufferReader(const unsigned char *Buf,
                                           unsigned Length,
                                           const std::string &ModuleID,
                                           llvm::BytecodeHandler* H )
  : BytecodeReader(H)
{
  // If not aligned, allocate a new buffer to hold the bytecode...
  const unsigned char *ParseBegin = 0;
  if (reinterpret_cast<uint64_t>(Buf) & 3) {
    Buffer = new unsigned char[Length+4];
    unsigned Offset = 4 - ((intptr_t)Buffer & 3);   // Make sure it's aligned
    ParseBegin = Buffer + Offset;
    memcpy((unsigned char*)ParseBegin, Buf, Length);    // Copy it over
    MustDelete = true;
  } else {
    // If we don't need to copy it over, just use the caller's copy
    ParseBegin = Buffer = Buf;
    MustDelete = false;
  }
  try {
    ParseBytecode(ParseBegin, Length, ModuleID);
  } catch (...) {
    if (MustDelete) delete [] Buffer;
    throw;
  }
}

BytecodeBufferReader::~BytecodeBufferReader() {
  if (MustDelete) delete [] Buffer;
}

//===----------------------------------------------------------------------===//
//  BytecodeStdinReader - Read bytecode from Standard Input
//

namespace {
  /// BytecodeStdinReader - parses a bytecode file from stdin
  ///
  class BytecodeStdinReader : public BytecodeReader {
  private:
    std::vector<unsigned char> FileData;
    unsigned char *FileBuf;

    BytecodeStdinReader(const BytecodeStdinReader&); // Do not implement
    void operator=(const BytecodeStdinReader &BFR);  // Do not implement

  public:
    BytecodeStdinReader( llvm::BytecodeHandler* H = 0 );
  };
}

BytecodeStdinReader::BytecodeStdinReader( BytecodeHandler* H )
  : BytecodeReader(H)
{
  int BlockSize;
  unsigned char Buffer[4096*4];

  // Read in all of the data from stdin, we cannot mmap stdin...
  while ((BlockSize = ::read(0 /*stdin*/, Buffer, 4096*4))) {
    if (BlockSize == -1)
      throw ErrnoMessage(errno, "read from standard input");

    FileData.insert(FileData.end(), Buffer, Buffer+BlockSize);
  }

  if (FileData.empty())
    throw std::string("Standard Input empty!");

  FileBuf = &FileData[0];
  ParseBytecode(FileBuf, FileData.size(), "<stdin>");
}

//===----------------------------------------------------------------------===//
//  Varargs transmogrification code...
//

// CheckVarargs - This is used to automatically translate old-style varargs to
// new style varargs for backwards compatibility.
static ModuleProvider *CheckVarargs(ModuleProvider *MP) {
  Module *M = MP->getModule();

  // Check to see if va_start takes arguments...
  Function *F = M->getNamedFunction("llvm.va_start");
  if (F == 0) return MP;  // No varargs use, just return.

  if (F->getFunctionType()->getNumParams() == 0)
    return MP;  // Modern varargs processing, just return.

  // If we get to this point, we know that we have an old-style module.
  // Materialize the whole thing to perform the rewriting.
  MP->materializeModule();

  // If the user is making use of obsolete varargs intrinsics, adjust them for
  // the user.
  if (Function *F = M->getNamedFunction("llvm.va_start")) {
    assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");

    const Type *RetTy = F->getFunctionType()->getParamType(0);
    RetTy = cast<PointerType>(RetTy)->getElementType();
    Function *NF = M->getOrInsertFunction("llvm.va_start", RetTy, 0);

    for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
      if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
        Value *V = new CallInst(NF, "", CI);
        new StoreInst(V, CI->getOperand(1), CI);
        CI->getParent()->getInstList().erase(CI);
      }
    F->setName("");
  }

  if (Function *F = M->getNamedFunction("llvm.va_end")) {
    assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
    const Type *ArgTy = F->getFunctionType()->getParamType(0);
    ArgTy = cast<PointerType>(ArgTy)->getElementType();
    Function *NF = M->getOrInsertFunction("llvm.va_end", Type::VoidTy,
                                                  ArgTy, 0);

    for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
      if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
        Value *V = new LoadInst(CI->getOperand(1), "", CI);
        new CallInst(NF, V, "", CI);
        CI->getParent()->getInstList().erase(CI);
      }
    F->setName("");
  }

  if (Function *F = M->getNamedFunction("llvm.va_copy")) {
    assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
    const Type *ArgTy = F->getFunctionType()->getParamType(0);
    ArgTy = cast<PointerType>(ArgTy)->getElementType();
    Function *NF = M->getOrInsertFunction("llvm.va_copy", ArgTy,
                                                  ArgTy, 0);

    for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
      if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
        Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
        new StoreInst(V, CI->getOperand(1), CI);
        CI->getParent()->getInstList().erase(CI);
      }
    F->setName("");
  }
  return MP;
}

//===----------------------------------------------------------------------===//
// Wrapper functions
//===----------------------------------------------------------------------===//

/// getBytecodeBufferModuleProvider - lazy function-at-a-time loading from a
/// buffer
ModuleProvider*
llvm::getBytecodeBufferModuleProvider(const unsigned char *Buffer,
                                      unsigned Length,
                                      const std::string &ModuleID,
                                      BytecodeHandler* H ) {
  return CheckVarargs(
      new BytecodeBufferReader(Buffer, Length, ModuleID, H));
}

/// ParseBytecodeBuffer - Parse a given bytecode buffer
///
Module *llvm::ParseBytecodeBuffer(const unsigned char *Buffer, unsigned Length,
                                  const std::string &ModuleID,
                                  std::string *ErrorStr){
  try {
    std::auto_ptr<ModuleProvider>
      AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID));
    return AMP->releaseModule();
  } catch (std::string &err) {
    if (ErrorStr) *ErrorStr = err;
    return 0;
  }
}

/// getBytecodeModuleProvider - lazy function-at-a-time loading from a file
///
ModuleProvider *llvm::getBytecodeModuleProvider(const std::string &Filename,
                                                BytecodeHandler* H) {
  if (Filename != std::string("-"))        // Read from a file...
    return CheckVarargs(new BytecodeFileReader(Filename,H));
  else                                     // Read from stdin
    return CheckVarargs(new BytecodeStdinReader(H));
}

/// ParseBytecodeFile - Parse the given bytecode file
///
Module *llvm::ParseBytecodeFile(const std::string &Filename,
                                std::string *ErrorStr) {
  try {
    std::auto_ptr<ModuleProvider> AMP(getBytecodeModuleProvider(Filename));
    return AMP->releaseModule();
  } catch (std::string &err) {
    if (ErrorStr) *ErrorStr = err;
    return 0;
  }
}

// AnalyzeBytecodeFile - analyze one file
Module* llvm::AnalyzeBytecodeFile(
  const std::string &Filename,  ///< File to analyze
  BytecodeAnalysis& bca,        ///< Statistical output
  std::string *ErrorStr,        ///< Error output
  std::ostream* output          ///< Dump output
)
{
  try {
    BytecodeHandler* analyzerHandler = createBytecodeAnalyzerHandler(bca,output);
    std::auto_ptr<ModuleProvider> AMP(
      getBytecodeModuleProvider(Filename,analyzerHandler));
    return AMP->releaseModule();
  } catch (std::string &err) {
    if (ErrorStr) *ErrorStr = err;
    return 0;
  }
}

// AnalyzeBytecodeBuffer - analyze a buffer
Module* llvm::AnalyzeBytecodeBuffer(
  const unsigned char* Buffer, ///< Pointer to start of bytecode buffer
  unsigned Length,             ///< Size of the bytecode buffer
  const std::string& ModuleID, ///< Identifier for the module
  BytecodeAnalysis& bca,       ///< The results of the analysis
  std::string* ErrorStr,       ///< Errors, if any.
  std::ostream* output         ///< Dump output, if any
)
{
  try {
    BytecodeHandler* hdlr = createBytecodeAnalyzerHandler(bca, output);
    std::auto_ptr<ModuleProvider>
      AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID, hdlr));
    return AMP->releaseModule();
  } catch (std::string &err) {
    if (ErrorStr) *ErrorStr = err;
    return 0;
  }
}

bool llvm::GetBytecodeDependentLibraries(const std::string &fname,
    Module::LibraryListType& deplibs) {
  try {
    std::auto_ptr<ModuleProvider> AMP( getBytecodeModuleProvider(fname));
    Module* M = AMP->releaseModule();
    deplibs = M->getLibraries();
    delete M;
    return true;
  } catch (...) {
    deplibs.clear();
    return false;
  }
}

// vim: sw=2 ai
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: udlnitem.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 14:33:13 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SVX_UDLNITEM_HXX
#define _SVX_UDLNITEM_HXX

// include ---------------------------------------------------------------

#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _VCL_VCLENUM_HXX
#include <vcl/vclenum.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

class SvXMLUnitConverter;
namespace rtl
{
    class OUString;
}

// class SvxUnderlineItem ------------------------------------------------

/*  [Beschreibung]

    Dieses Item beschreibt, ob und wie unterstrichen ist.
*/

class SVX_DLLPUBLIC SvxUnderlineItem : public SfxEnumItem
{
    Color mColor;
public:
    TYPEINFO();

    SvxUnderlineItem( const FontUnderline eSt /*= UNDERLINE_NONE*/,
                      const USHORT nId  );

    // "pure virtual Methoden" vom SfxPoolItem
    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
                            SfxMapUnit eCoreMetric,
                            SfxMapUnit ePresMetric,
                            String &rText, const IntlWrapper * = 0 ) const;

    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;
    virtual SfxPoolItem*    Create(SvStream &, USHORT) const;
    virtual SvStream&       Store(SvStream &, USHORT nItemVersion) const;
    virtual String          GetValueTextByPos( USHORT nPos ) const;
    virtual USHORT          GetValueCount() const;

    virtual sal_Bool        QueryValue( com::sun::star::uno::Any& rVal,
                                        BYTE nMemberId = 0 ) const;
    virtual sal_Bool        PutValue( const com::sun::star::uno::Any& rVal,
                                        BYTE nMemberId = 0 );

    // MS VC4.0 kommt durcheinander
    void                    SetValue( USHORT nNewVal )
                                {SfxEnumItem::SetValue(nNewVal); }
    virtual int             HasBoolValue() const;
    virtual BOOL            GetBoolValue() const;
    virtual void            SetBoolValue( BOOL bVal );

    virtual int              operator==( const SfxPoolItem& ) const;

    inline SvxUnderlineItem& operator=(const SvxUnderlineItem& rUnderline)
        {
            SetValue( rUnderline.GetValue() );
            SetColor( rUnderline.GetColor() );
            return *this;
        }

    // enum cast
    FontUnderline           GetUnderline() const
                                { return (FontUnderline)GetValue(); }
    void                    SetUnderline ( FontUnderline eNew )
                                { SetValue((USHORT) eNew); }

    const Color&            GetColor() const                { return mColor; }
    void                    SetColor( const Color& rCol )   { mColor = rCol; }
};

#endif // #ifndef _SVX_UDLNITEM_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.3.446); FILE MERGED 2008/04/01 15:49:41 thb 1.3.446.3: #i85898# Stripping all external header guards 2008/04/01 12:47:01 thb 1.3.446.2: #i85898# Stripping all external header guards 2008/03/31 14:18:21 rt 1.3.446.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: udlnitem.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SVX_UDLNITEM_HXX
#define _SVX_UDLNITEM_HXX

// include ---------------------------------------------------------------

#include <svtools/eitem.hxx>
#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#include <vcl/vclenum.hxx>
#include <tools/color.hxx>
#include "svx/svxdllapi.h"

class SvXMLUnitConverter;
namespace rtl
{
    class OUString;
}

// class SvxUnderlineItem ------------------------------------------------

/*  [Beschreibung]

    Dieses Item beschreibt, ob und wie unterstrichen ist.
*/

class SVX_DLLPUBLIC SvxUnderlineItem : public SfxEnumItem
{
    Color mColor;
public:
    TYPEINFO();

    SvxUnderlineItem( const FontUnderline eSt /*= UNDERLINE_NONE*/,
                      const USHORT nId  );

    // "pure virtual Methoden" vom SfxPoolItem
    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
                            SfxMapUnit eCoreMetric,
                            SfxMapUnit ePresMetric,
                            String &rText, const IntlWrapper * = 0 ) const;

    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;
    virtual SfxPoolItem*    Create(SvStream &, USHORT) const;
    virtual SvStream&       Store(SvStream &, USHORT nItemVersion) const;
    virtual String          GetValueTextByPos( USHORT nPos ) const;
    virtual USHORT          GetValueCount() const;

    virtual sal_Bool        QueryValue( com::sun::star::uno::Any& rVal,
                                        BYTE nMemberId = 0 ) const;
    virtual sal_Bool        PutValue( const com::sun::star::uno::Any& rVal,
                                        BYTE nMemberId = 0 );

    // MS VC4.0 kommt durcheinander
    void                    SetValue( USHORT nNewVal )
                                {SfxEnumItem::SetValue(nNewVal); }
    virtual int             HasBoolValue() const;
    virtual BOOL            GetBoolValue() const;
    virtual void            SetBoolValue( BOOL bVal );

    virtual int              operator==( const SfxPoolItem& ) const;

    inline SvxUnderlineItem& operator=(const SvxUnderlineItem& rUnderline)
        {
            SetValue( rUnderline.GetValue() );
            SetColor( rUnderline.GetColor() );
            return *this;
        }

    // enum cast
    FontUnderline           GetUnderline() const
                                { return (FontUnderline)GetValue(); }
    void                    SetUnderline ( FontUnderline eNew )
                                { SetValue((USHORT) eNew); }

    const Color&            GetColor() const                { return mColor; }
    void                    SetColor( const Color& rCol )   { mColor = rCol; }
};

#endif // #ifndef _SVX_UDLNITEM_HXX

<|endoftext|>