<commit_before>//===-------------- AliasAnalysis.cpp - SIL Alias Analysis ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "sil-aa"
#include "swift/SILAnalysis/AliasAnalysis.h"
#include "swift/SILPasses/Utils/Local.h"
#include "swift/SIL/SILValue.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILFunction.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"

using namespace swift;

static llvm::cl::opt<bool>
DisableAliasAnalysis("disable-aa", llvm::cl::init(false),
                     llvm::cl::Hidden,
                     llvm::cl::desc("Always return most conservative AA "
                                    "result."));

//===----------------------------------------------------------------------===//
//                             Utility Functions
//===----------------------------------------------------------------------===//

/// Strip off casts/indexing insts/address projections from V until there is
/// nothing left to strip.
static SILValue getUnderlyingObject(SILValue V) {
  while (true) {
    SILValue V2 = V.stripCasts().stripAddressProjections().stripIndexingInsts();
    if (V2 == V)
      return V2;
    V = V2;
  }
}

/// Return true if the given SILArgument is an argument to the first BB of a
/// function.
static bool isFunctionArgument(SILValue V) {
  auto *Arg = dyn_cast<SILArgument>(V.getDef());
  if (!Arg)
    return false;
  return Arg->getParent() == &*Arg->getFunction()->begin();
}

/// A no alias argument is an argument that is an address type of the entry
/// basic block of a function.
static bool isNoAliasArgument(SILValue V) {
  return isFunctionArgument(V) && V.getType().isAddress();
}

/// Return true if V is an object that at compile time can be uniquely
/// identified.
static bool isIdentifiableObject(SILValue V) {
  return isa<AllocationInst>(*V) || isNoAliasArgument(V) ||
    isa<LiteralInst>(*V);
}

static bool isLocalLiteral(SILValue V) {
  switch (V->getKind()) {
  case ValueKind::IntegerLiteralInst:
  case ValueKind::FloatLiteralInst:
  case ValueKind::StringLiteralInst:
    return true;
  default:
    return false;
  }
}

static bool isIdentifiedFunctionLocal(SILValue V) {
  return isa<AllocationInst>(*V) || isNoAliasArgument(V) || isLocalLiteral(V);
}

/// Returns true if we can prove that the two input SILValues which do not equal
/// can not alias.
static bool aliasUnequalObjects(SILValue O1, SILValue O2) {
  assert(O1 != O2 && "This function should only be called on unequal values.");

  // If O1 and O2 do not equal and they are both values that can be statically
  // and uniquely identified, they can not alias.
  if (isIdentifiableObject(O1) && isIdentifiableObject(O2))
    return true;

  // Function arguments can't alias with things that are known to be
  // unambigously identified at the function level.
  if ((isFunctionArgument(O1.getDef()) && isIdentifiedFunctionLocal(O2)) ||
      (isFunctionArgument(O2.getDef()) && isIdentifiedFunctionLocal(O1)))
    return true;

  // We failed to prove that the two objects are different.
  return false;
}

//===----------------------------------------------------------------------===//
//                                Entry Points
//===----------------------------------------------------------------------===//

AliasAnalysis::AliasResult AliasAnalysis::alias(SILValue V1, SILValue V2) {
  // If alias analysis is disabled, always return may alias.
  if (DisableAliasAnalysis)
    return AliasResult::MayAlias;

  // If the two values equal, quickly return must alias.
  if (V1 == V2)
    return AliasResult::MustAlias;

  DEBUG(llvm::dbgs() << "ALIAS ANALYSIS:\n    V1: " << *V1.getDef()
        << "    V2: " << *V2.getDef());
  // Strip off any casts on V1, V2.
  V1 = V1.stripCasts();
  V2 = V2.stripCasts();
  DEBUG(llvm::dbgs() << "        After Cast Stripping V1:" << *V1.getDef());
  DEBUG(llvm::dbgs() << "        After Cast Stripping V2:" << *V2.getDef());

  // Create a key to lookup if we have already computed an alias result for V1,
  // V2. Canonicalize our cache keys so that the pointer with the lower address
  // is always the first element of the pair. This ensures we do not pollute our
  // cache with two entries with the same key, albeit with the key's fields
  // swapped.
  auto Key = V1 < V2? std::make_pair(V1, V2) : std::make_pair(V2, V1);

  // If we find our key in the cache, just return the alias result.
  auto Pair = AliasCache.find(Key);
  if (Pair != AliasCache.end()) {
    DEBUG(llvm::dbgs() << "      Found value in the cache: "
          << unsigned(Pair->second));

    return Pair->second;
  }

  // Ok, we need to actually compute an Alias Analysis result for V1, V2. Begin
  // by finding the "base" of V1, V2 by stripping off all casts and GEPs.
  SILValue O1 = getUnderlyingObject(V1);
  SILValue O2 = getUnderlyingObject(V2);
  DEBUG(llvm::dbgs() << "        Underlying V1:" << *O1.getDef());
  DEBUG(llvm::dbgs() << "        Underlying V2:" << *O2.getDef());

  // If O1 and O2 do not equal, see if we can prove that they can not be the
  // same object. If we can, return No Alias.
  if (O1 != O2 && aliasUnequalObjects(O1, O2))
    return AliasCache[Key] = AliasResult::NoAlias;

  // We could not prove anything. Be conservative and return that V1, V2 may
  // alias.
  return AliasResult::MayAlias;
}

SILInstruction::MemoryBehavior
AliasAnalysis::getMemoryBehavior(SILInstruction *Inst, SILValue V) {
  DEBUG(llvm::dbgs() << "GET MEMORY BEHAVIOR FOR:\n    " << *Inst << "    "
        << *V.getDef());

  // If we already know that we do not read or write memory, just return None.
  if (!Inst->mayReadOrWriteMemory()) {
    DEBUG(llvm::dbgs() << "  Inst does not write memory. Returning None.\n");
    return MemoryBehavior::None;
  }

  switch (Inst->getKind()) {
  case ValueKind::LoadInst:
    // If the load address doesn't alias the given address, it doesn't read or
    // write the specified memory.
    if (alias(Inst->getOperand(0), V) == AliasResult::NoAlias) {
      DEBUG(llvm::dbgs() << "  Load does not alias inst. Returning None.\n");
      return MemoryBehavior::None;
    }

    // Otherwise be conservative and just return reads since loads can only
    // read.
    DEBUG(llvm::dbgs() << "  Could not prove load does not alias inst. "
          "Returning MayRead.\n");
    return MemoryBehavior::MayRead;
  case ValueKind::StoreInst:
    // If the store dest cannot alias the pointer in question, then the
    // specified value can not be modified by the store.
    if (alias(cast<StoreInst>(Inst)->getDest(), V) == AliasResult::NoAlias) {
      DEBUG(llvm::dbgs() << "  Store Dst does not alias inst. Returning "
            "None.\n");
      return MemoryBehavior::None;
    }

    // Otherwise, a store just writes.
    DEBUG(llvm::dbgs() << "  Could not prove store does not alias inst. "
          "Returning MayWrite.\n");
    return MemoryBehavior::MayWrite;
  case ValueKind::ApplyInst: {
    // If the ApplyInst is from a no-read builtin it can not read or write and
    // if it comes from a no-side effect builtin, it can only read.
    auto *AI = cast<ApplyInst>(Inst);
    auto *BFR = dyn_cast<BuiltinFunctionRefInst>(AI->getCallee().getDef());

    // If our callee is not a builtin, be conservative and return may have side
    // effects.
    if (!BFR) {
      DEBUG(llvm::dbgs() << "  Found apply we don't understand returning "
            "MHSF.\n");
      return MemoryBehavior::MayHaveSideEffects;
    }

    // If the builtin is read none, it does not read or write memory.
    if (isReadNone(BFR)) {
      DEBUG(llvm::dbgs() << "  Found apply of read none builtin. Returning"
            " None.\n");
      return MemoryBehavior::None;
    }
    // If the builtin is side effect free, then it can only read memory.
    if (isSideEffectFree(BFR)) {
      DEBUG(llvm::dbgs() << "  Found apply of side effect free builtin. "
            "Returning MayRead.\n");
      return MemoryBehavior::MayRead;
    }

    // Otherwise be conservative and return that we may have side effects.
    DEBUG(llvm::dbgs() << "  Found apply of side effect builtin. "
          "Returning MayHaveSideEffects.\n");
    return MemoryBehavior::MayHaveSideEffects;
  }
  default:
    // If we do not have a special case, just return the generic memory
    // behavior of Inst.
    return Inst->getMemoryBehavior();
  }
}

SILAnalysis *swift::createAliasAnalysis(SILModule *M) {
  return new AliasAnalysis(M);
}

llvm::raw_ostream &swift::operator<<(llvm::raw_ostream &OS,
                                     AliasAnalysis::AliasResult R) {
  switch (R) {
  case AliasAnalysis::AliasResult::NoAlias:
    return OS << "NoAlias";
  case AliasAnalysis::AliasResult::MayAlias:
    return OS << "MayAlias";
  case AliasAnalysis::AliasResult::MustAlias:
    return OS << "MustAlias";
  }
}
<commit_msg>[sil-aa] Compile out DisableAliasAnalysis flag when not building Debug. Put in a comment making it clear that it should be removed once AA bringup is complete.<commit_after>//===-------------- AliasAnalysis.cpp - SIL Alias Analysis ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "sil-aa"
#include "swift/SILAnalysis/AliasAnalysis.h"
#include "swift/SILPasses/Utils/Local.h"
#include "swift/SIL/SILValue.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILFunction.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"

using namespace swift;

#ifndef NDEBUG
/// This is meant to be used during AA bring up. If AA has been brought up, feel
/// free to remove this.
static llvm::cl::opt<bool>
DisableAliasAnalysis("disable-aa", llvm::cl::init(false),
                     llvm::cl::Hidden,
                     llvm::cl::desc("Always return most conservative AA "
                                    "result."));
#endif

//===----------------------------------------------------------------------===//
//                             Utility Functions
//===----------------------------------------------------------------------===//

/// Strip off casts/indexing insts/address projections from V until there is
/// nothing left to strip.
static SILValue getUnderlyingObject(SILValue V) {
  while (true) {
    SILValue V2 = V.stripCasts().stripAddressProjections().stripIndexingInsts();
    if (V2 == V)
      return V2;
    V = V2;
  }
}

/// Return true if the given SILArgument is an argument to the first BB of a
/// function.
static bool isFunctionArgument(SILValue V) {
  auto *Arg = dyn_cast<SILArgument>(V.getDef());
  if (!Arg)
    return false;
  return Arg->getParent() == &*Arg->getFunction()->begin();
}

/// A no alias argument is an argument that is an address type of the entry
/// basic block of a function.
static bool isNoAliasArgument(SILValue V) {
  return isFunctionArgument(V) && V.getType().isAddress();
}

/// Return true if V is an object that at compile time can be uniquely
/// identified.
static bool isIdentifiableObject(SILValue V) {
  return isa<AllocationInst>(*V) || isNoAliasArgument(V) ||
    isa<LiteralInst>(*V);
}

static bool isLocalLiteral(SILValue V) {
  switch (V->getKind()) {
  case ValueKind::IntegerLiteralInst:
  case ValueKind::FloatLiteralInst:
  case ValueKind::StringLiteralInst:
    return true;
  default:
    return false;
  }
}

static bool isIdentifiedFunctionLocal(SILValue V) {
  return isa<AllocationInst>(*V) || isNoAliasArgument(V) || isLocalLiteral(V);
}

/// Returns true if we can prove that the two input SILValues which do not equal
/// can not alias.
static bool aliasUnequalObjects(SILValue O1, SILValue O2) {
  assert(O1 != O2 && "This function should only be called on unequal values.");

  // If O1 and O2 do not equal and they are both values that can be statically
  // and uniquely identified, they can not alias.
  if (isIdentifiableObject(O1) && isIdentifiableObject(O2))
    return true;

  // Function arguments can't alias with things that are known to be
  // unambigously identified at the function level.
  if ((isFunctionArgument(O1.getDef()) && isIdentifiedFunctionLocal(O2)) ||
      (isFunctionArgument(O2.getDef()) && isIdentifiedFunctionLocal(O1)))
    return true;

  // We failed to prove that the two objects are different.
  return false;
}

//===----------------------------------------------------------------------===//
//                                Entry Points
//===----------------------------------------------------------------------===//

AliasAnalysis::AliasResult AliasAnalysis::alias(SILValue V1, SILValue V2) {
  // If alias analysis is disabled, always return may alias.
  if (DisableAliasAnalysis)
    return AliasResult::MayAlias;

  // If the two values equal, quickly return must alias.
  if (V1 == V2)
    return AliasResult::MustAlias;

  DEBUG(llvm::dbgs() << "ALIAS ANALYSIS:\n    V1: " << *V1.getDef()
        << "    V2: " << *V2.getDef());
  // Strip off any casts on V1, V2.
  V1 = V1.stripCasts();
  V2 = V2.stripCasts();
  DEBUG(llvm::dbgs() << "        After Cast Stripping V1:" << *V1.getDef());
  DEBUG(llvm::dbgs() << "        After Cast Stripping V2:" << *V2.getDef());

  // Create a key to lookup if we have already computed an alias result for V1,
  // V2. Canonicalize our cache keys so that the pointer with the lower address
  // is always the first element of the pair. This ensures we do not pollute our
  // cache with two entries with the same key, albeit with the key's fields
  // swapped.
  auto Key = V1 < V2? std::make_pair(V1, V2) : std::make_pair(V2, V1);

  // If we find our key in the cache, just return the alias result.
  auto Pair = AliasCache.find(Key);
  if (Pair != AliasCache.end()) {
    DEBUG(llvm::dbgs() << "      Found value in the cache: "
          << unsigned(Pair->second));

    return Pair->second;
  }

  // Ok, we need to actually compute an Alias Analysis result for V1, V2. Begin
  // by finding the "base" of V1, V2 by stripping off all casts and GEPs.
  SILValue O1 = getUnderlyingObject(V1);
  SILValue O2 = getUnderlyingObject(V2);
  DEBUG(llvm::dbgs() << "        Underlying V1:" << *O1.getDef());
  DEBUG(llvm::dbgs() << "        Underlying V2:" << *O2.getDef());

  // If O1 and O2 do not equal, see if we can prove that they can not be the
  // same object. If we can, return No Alias.
  if (O1 != O2 && aliasUnequalObjects(O1, O2))
    return AliasCache[Key] = AliasResult::NoAlias;

  // We could not prove anything. Be conservative and return that V1, V2 may
  // alias.
  return AliasResult::MayAlias;
}

SILInstruction::MemoryBehavior
AliasAnalysis::getMemoryBehavior(SILInstruction *Inst, SILValue V) {
  DEBUG(llvm::dbgs() << "GET MEMORY BEHAVIOR FOR:\n    " << *Inst << "    "
        << *V.getDef());

  // If we already know that we do not read or write memory, just return None.
  if (!Inst->mayReadOrWriteMemory()) {
    DEBUG(llvm::dbgs() << "  Inst does not write memory. Returning None.\n");
    return MemoryBehavior::None;
  }

  switch (Inst->getKind()) {
  case ValueKind::LoadInst:
    // If the load address doesn't alias the given address, it doesn't read or
    // write the specified memory.
    if (alias(Inst->getOperand(0), V) == AliasResult::NoAlias) {
      DEBUG(llvm::dbgs() << "  Load does not alias inst. Returning None.\n");
      return MemoryBehavior::None;
    }

    // Otherwise be conservative and just return reads since loads can only
    // read.
    DEBUG(llvm::dbgs() << "  Could not prove load does not alias inst. "
          "Returning MayRead.\n");
    return MemoryBehavior::MayRead;
  case ValueKind::StoreInst:
    // If the store dest cannot alias the pointer in question, then the
    // specified value can not be modified by the store.
    if (alias(cast<StoreInst>(Inst)->getDest(), V) == AliasResult::NoAlias) {
      DEBUG(llvm::dbgs() << "  Store Dst does not alias inst. Returning "
            "None.\n");
      return MemoryBehavior::None;
    }

    // Otherwise, a store just writes.
    DEBUG(llvm::dbgs() << "  Could not prove store does not alias inst. "
          "Returning MayWrite.\n");
    return MemoryBehavior::MayWrite;
  case ValueKind::ApplyInst: {
    // If the ApplyInst is from a no-read builtin it can not read or write and
    // if it comes from a no-side effect builtin, it can only read.
    auto *AI = cast<ApplyInst>(Inst);
    auto *BFR = dyn_cast<BuiltinFunctionRefInst>(AI->getCallee().getDef());

    // If our callee is not a builtin, be conservative and return may have side
    // effects.
    if (!BFR) {
      DEBUG(llvm::dbgs() << "  Found apply we don't understand returning "
            "MHSF.\n");
      return MemoryBehavior::MayHaveSideEffects;
    }

    // If the builtin is read none, it does not read or write memory.
    if (isReadNone(BFR)) {
      DEBUG(llvm::dbgs() << "  Found apply of read none builtin. Returning"
            " None.\n");
      return MemoryBehavior::None;
    }
    // If the builtin is side effect free, then it can only read memory.
    if (isSideEffectFree(BFR)) {
      DEBUG(llvm::dbgs() << "  Found apply of side effect free builtin. "
            "Returning MayRead.\n");
      return MemoryBehavior::MayRead;
    }

    // Otherwise be conservative and return that we may have side effects.
    DEBUG(llvm::dbgs() << "  Found apply of side effect builtin. "
          "Returning MayHaveSideEffects.\n");
    return MemoryBehavior::MayHaveSideEffects;
  }
  default:
    // If we do not have a special case, just return the generic memory
    // behavior of Inst.
    return Inst->getMemoryBehavior();
  }
}

SILAnalysis *swift::createAliasAnalysis(SILModule *M) {
  return new AliasAnalysis(M);
}

llvm::raw_ostream &swift::operator<<(llvm::raw_ostream &OS,
                                     AliasAnalysis::AliasResult R) {
  switch (R) {
  case AliasAnalysis::AliasResult::NoAlias:
    return OS << "NoAlias";
  case AliasAnalysis::AliasResult::MayAlias:
    return OS << "MayAlias";
  case AliasAnalysis::AliasResult::MustAlias:
    return OS << "MustAlias";
  }
}
<|endoftext|>


<commit_before>#ifndef __JSON_HPP__
#define __JSON_HPP__

#include <cctype>
#include <string>
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
#include <array>
#include <regex>

namespace JSON {
	using namespace std;

	struct Error {};
	struct SyntaxError : public Error {};
	struct LoadError : public Error {};
	struct AccessError : public Error {};

	template<typename _Value, char const ..._szName>
	struct Field {
		static char const s_szName[];
		typedef _Value Type;
	};

	template<typename _Value, char const ..._szName>
	char const Field<_Value, _szName...>::s_szName[] = { _szName... };

	template<typename _Value, char const ..._szName>
	struct OptionalField {
		static char const s_szName[];
		typedef _Value Type;
	};

	template<typename _Value, char const ..._szName>
	char const OptionalField<_Value, _szName...>::s_szName[] = { _szName... };

	template<char const ..._sz>
	struct FieldName {
		static char const s_szName[];
	};

	template<char const ..._sz>
	char const FieldName<_sz...>::s_szName[] = { _sz... };

	template<typename _Name, typename ..._Fields>
	struct FieldType {};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	struct FieldType<FieldName<_szName...>, Field<_Value, _szName...>, _OtherFields...> {
		typedef _Value Type;
	};

	template<char const ..._szFieldName, typename _FirstField, typename ..._OtherFields>
	struct FieldType<FieldName<_szFieldName...>, _FirstField, _OtherFields...> {
		typedef typename FieldType<FieldName<_szFieldName...>, _OtherFields...>::Type Type;
	};

	template<typename ..._Fields>
	struct Object {};

	template<typename _Field, typename ..._Fields>
	struct Getter {};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	struct Getter<Field<_Value, _szName...>, Field<_Value, _szName...>, _OtherFields...> {
		inline static _Value &Get(Object<Field<_Value, _szName...>, _OtherFields...> &rObject) {
			return rObject.m_Value;
		}

		inline static _Value const &Get(Object<Field<_Value, _szName...>, _OtherFields...> const &rObject) {
			return rObject.m_Value;
		}
	};

	template<typename _Value, char const ..._szName, typename _FirstField, typename ..._OtherFields>
	struct Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...> {
		inline static _Value &Get(Object<_FirstField, _OtherFields...> &rObject) {
			return Getter<Field<_Value, _szName...>, _OtherFields...>::Get(rObject);
		}

		inline static _Value const &Get(Object<_FirstField, _OtherFields...> const &rObject) {
			return Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...>::Get(rObject);
		}
	};

	template<>
	struct Object<> {
		Object() {}
		virtual ~Object() {}
	};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	struct Object<Field<_Value, _szName...>, _OtherFields...> :
		public Object<_OtherFields...>
	{
		static char const s_szName[];
		_Value m_Value;

		Object() {}

		virtual ~Object() {}

		template<char const ..._szFieldName>
		inline typename FieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type &Get() {
			return Getter<
				Field<typename FieldType<
					FieldName<_szFieldName...>,
					Field<_Value, _szName...>,
					_OtherFields...
				>::Type, _szFieldName...>,
				Field<_Value, _szName...>,
				_OtherFields...
			>::Get(*this);
		}

		template<char const ..._szFieldName>
		inline typename FieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type const &Get() const {
			return Getter<
				Field<typename FieldType<
					FieldName<_szFieldName...>,
					Field<_Value, _szName...>,
					_OtherFields...
				>::Type, _szFieldName...>,
				Field<_Value, _szName...>,
				_OtherFields...
			>::Get(*this);
		}
	};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	char const Object<Field<_Value, _szName...>, _OtherFields...>::s_szName[] = { _szName... };

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	struct Object<OptionalField<_Value, _szName...>, _OtherFields...> :
		public Object<_OtherFields...>
	{
		static char const s_szName[];
		_Value m_Value;
		bool m_fPresent;

		Object()
			:
		m_fPresent(false) {}

		virtual ~Object() {}

		// TODO getters
	};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	char const Object<OptionalField<_Value, _szName...>, _OtherFields...>::s_szName[] = { _szName... };

	template<typename _Type>
	struct Serializer {
		template<typename _Iterator>
		static _Type Load(_Iterator &ri, _Iterator j);

		static string Store(_Type const &r);
	};

	template<>
	struct Serializer<nullptr_t> {
		template<typename _Iterator>
		static nullptr_t Load(_Iterator &ri, _Iterator j) {
			if (regex_search(ri, j, regex("^\\s*null"))) {
				return nullptr;
			} else {
				throw SyntaxError();
			}
		}

		static string Store(nullptr_t const &r) {
			return "null";
		}
	};

	template<>
	struct Serializer<bool> {
		template<typename _Iterator>
		static bool Load(_Iterator &ri, _Iterator j) {
			// TODO
			throw Error();
		}

		static string Store(bool const &r) {
			if (r) {
				return "true";
			} else {
				return "false";
			}
		}
	};

	template<>
	struct Serializer<int> {
		template<typename _Iterator>
		static int Load(_Iterator &ri, _Iterator j) {
			// TODO
			throw Error();
		}

		static string Store(int const &r) {
			ostringstream oss;
			oss << r;
			return oss.str();
		}
	};

	template<>
	struct Serializer<unsigned int> {
		template<typename _Iterator>
		static unsigned int Load(_Iterator &ri, _Iterator j) {
			// TODO
			throw Error();
		}

		static string Store(unsigned int const &r) {
			ostringstream oss;
			oss << r;
			return oss.str();
		}
	};

	template<>
	struct Serializer<double> {
		template<typename _Iterator>
		static double Load(_Iterator &ri, _Iterator j) {
			// TODO
			throw Error();
		}

		static string Store(double const &r) {
			ostringstream oss;
			oss << r;
			return oss.str();
		}
	};

	template<>
	struct Serializer<string> {
		template<typename _Iterator>
		static string Load(_Iterator &ri, _Iterator j) {
			// TODO
			throw Error();
		}

		static string Store(ostream &ros, string const &r) {
			return "\"" + r + "\""; // FIXME escape special characters
		}
	};

	template<typename ..._Fields>
	struct Serializer<Object<_Fields...>> {
		template<typename _Iterator>
		static Object<_Fields...> Load(_Iterator &ri, _Iterator j) {
			// TODO
			throw Error();
		}
	};

	template<typename _Element>
	struct Serializer<vector<_Element>> {
		template<typename _Iterator>
		static vector<_Element> Load(_Iterator &ri, _Iterator j) {
			// TODO
			throw Error();
		}
	};

	template<typename _Element, unsigned int _c>
	struct Serializer<array<_Element, _c>> {
		template<typename _Iterator>
		static array<_Element, _c> Load(_Iterator &ri, _Iterator j) {
			// TODO
			throw Error();
		}
	};

	template<typename _Type>
	inline _Type Load(string const &rstr) {
		return Serializer<_Type>::Load(rstr.begin(), rstr.end());
	}

	template<typename _Type>
	inline _Type Load(istream &ris) {
		string const str = string(istreambuf_iterator<char>(ris), istreambuf_iterator<char>());
		auto it = str.begin();
		return Serializer<_Type>::Load(it, str.end());
	}

	template<typename _Type>
	inline string Store(_Type const &r) {
		return Serializer<_Type>::Store(r);
	}

	template<typename _Type>
	inline ostream &Store(ostream &ros, _Type const &r) {
		return ros << Serializer<_Type>::Store(r);
	}
}

template<typename ..._Fields>
inline std::istream &operator >> (std::istream &ris, JSON::Object<_Fields...> &rObject) {
	rObject = JSON::Load<JSON::Object<_Fields...>>(ris);
	return ris;
}

template<typename ..._Fields>
inline std::ostream &operator << (std::ostream &ros, JSON::Object<_Fields...> &rObject) {
	return JSON::Store<JSON::Object<_Fields...>>(ros, rObject);
}

static constexpr char JSON_UNPACK(char const sz[], unsigned int i) {
	return (void)sz, (void)i, 0;
}

static constexpr char (*JSON_ALMOST_UNPACK())(char const[], unsigned int) {
	return JSON_UNPACK;
}

#define JSON_EMPTY(...)
#define JSON_DEFER(...) __VA_ARGS__ JSON_EMPTY()
#define JSON_EXPAND(...) __VA_ARGS__

#define JSON_EXPAND0 JSON_EXPAND
#define JSON_EXPAND1(...) JSON_EXPAND0(JSON_EXPAND0(__VA_ARGS__))
#define JSON_EXPAND2(...) JSON_EXPAND1(JSON_EXPAND1(__VA_ARGS__))
#define JSON_EXPAND3(...) JSON_EXPAND2(JSON_EXPAND2(__VA_ARGS__))
#define JSON_EXPAND4(...) JSON_EXPAND3(JSON_EXPAND3(__VA_ARGS__))
#define JSON_EXPAND5(...) JSON_EXPAND4(JSON_EXPAND4(__VA_ARGS__))
#define JSON_EXPAND6(...) JSON_EXPAND5(JSON_EXPAND5(__VA_ARGS__))
#define JSON_EXPAND_ALL JSON_EXPAND6

#define JSON_ALMOST_UNPACK() JSON_UNPACK
#define JSON_UNPACK(sz, i) ((i) < sizeof(sz)) ? (sz)[i] : 0, JSON_DEFER(JSON_ALMOST_UNPACK)()(sz, i + 1)

#define UNPACK(sz) JSON_EXPAND_ALL(JSON_UNPACK(sz, 0))

#endif
<commit_msg>Faster UNPACK implementation - *sigh*<commit_after>#ifndef __JSON_HPP__
#define __JSON_HPP__

#include <cctype>
#include <string>
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
#include <array>
#include <regex>

namespace JSON {
	using namespace std;

	struct Error {};
	struct SyntaxError : public Error {};
	struct LoadError : public Error {};
	struct AccessError : public Error {};

	template<typename _Value, char const ..._szName>
	struct Field {
		static char const s_szName[];
		typedef _Value Type;
	};

	template<typename _Value, char const ..._szName>
	char const Field<_Value, _szName...>::s_szName[] = { _szName... };

	template<typename _Value, char const ..._szName>
	struct OptionalField {
		static char const s_szName[];
		typedef _Value Type;
	};

	template<typename _Value, char const ..._szName>
	char const OptionalField<_Value, _szName...>::s_szName[] = { _szName... };

	template<char const ..._sz>
	struct FieldName {
		static char const s_szName[];
	};

	template<char const ..._sz>
	char const FieldName<_sz...>::s_szName[] = { _sz... };

	template<typename _Name, typename ..._Fields>
	struct FieldType {};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	struct FieldType<FieldName<_szName...>, Field<_Value, _szName...>, _OtherFields...> {
		typedef _Value Type;
	};

	template<char const ..._szFieldName, typename _FirstField, typename ..._OtherFields>
	struct FieldType<FieldName<_szFieldName...>, _FirstField, _OtherFields...> {
		typedef typename FieldType<FieldName<_szFieldName...>, _OtherFields...>::Type Type;
	};

	template<typename ..._Fields>
	struct Object {};

	template<typename _Field, typename ..._Fields>
	struct Getter {};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	struct Getter<Field<_Value, _szName...>, Field<_Value, _szName...>, _OtherFields...> {
		inline static _Value &Get(Object<Field<_Value, _szName...>, _OtherFields...> &rObject) {
			return rObject.m_Value;
		}

		inline static _Value const &Get(Object<Field<_Value, _szName...>, _OtherFields...> const &rObject) {
			return rObject.m_Value;
		}
	};

	template<typename _Value, char const ..._szName, typename _FirstField, typename ..._OtherFields>
	struct Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...> {
		inline static _Value &Get(Object<_FirstField, _OtherFields...> &rObject) {
			return Getter<Field<_Value, _szName...>, _OtherFields...>::Get(rObject);
		}

		inline static _Value const &Get(Object<_FirstField, _OtherFields...> const &rObject) {
			return Getter<Field<_Value, _szName...>, _FirstField, _OtherFields...>::Get(rObject);
		}
	};

	template<>
	struct Object<> {
		Object() {}
		virtual ~Object() {}
	};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	struct Object<Field<_Value, _szName...>, _OtherFields...> :
		public Object<_OtherFields...>
	{
		static char const s_szName[];
		_Value m_Value;

		Object() {}

		virtual ~Object() {}

		template<char const ..._szFieldName>
		inline typename FieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type &Get() {
			return Getter<
				Field<typename FieldType<
					FieldName<_szFieldName...>,
					Field<_Value, _szName...>,
					_OtherFields...
				>::Type, _szFieldName...>,
				Field<_Value, _szName...>,
				_OtherFields...
			>::Get(*this);
		}

		template<char const ..._szFieldName>
		inline typename FieldType<FieldName<_szFieldName...>, Field<_Value, _szName...>, _OtherFields...>::Type const &Get() const {
			return Getter<
				Field<typename FieldType<
					FieldName<_szFieldName...>,
					Field<_Value, _szName...>,
					_OtherFields...
				>::Type, _szFieldName...>,
				Field<_Value, _szName...>,
				_OtherFields...
			>::Get(*this);
		}
	};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	char const Object<Field<_Value, _szName...>, _OtherFields...>::s_szName[] = { _szName... };

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	struct Object<OptionalField<_Value, _szName...>, _OtherFields...> :
		public Object<_OtherFields...>
	{
		static char const s_szName[];
		_Value m_Value;
		bool m_fPresent;

		Object()
			:
		m_fPresent(false) {}

		virtual ~Object() {}

		// TODO getters
	};

	template<typename _Value, char const ..._szName, typename ..._OtherFields>
	char const Object<OptionalField<_Value, _szName...>, _OtherFields...>::s_szName[] = { _szName... };

	template<typename _Type>
	struct Serializer {
		template<typename _Iterator>
		static _Type Load(_Iterator &ri, _Iterator j);

		static string Store(_Type const &r);
	};

	template<>
	struct Serializer<nullptr_t> {
		template<typename _Iterator>
		static nullptr_t Load(_Iterator &ri, _Iterator j) {
			if (regex_search(ri, j, regex("^\\s*null"))) {
				return nullptr;
			} else {
				throw SyntaxError();
			}
		}

		static string Store(nullptr_t const &r) {
			return "null";
		}
	};

	template<>
	struct Serializer<bool> {
		template<typename _Iterator>
		static bool Load(_Iterator &ri, _Iterator j) {
			// TODO
			throw Error();
		}

		static string Store(bool const &r) {
			if (r) {
				return "true";
			} else {
				return "false";
			}
		}
	};

	template<>
	struct Serializer<int> {
		template<typename _Iterator>
		static int Load(_Iterator &ri, _Iterator j) {
			// TODO
			throw Error();
		}

		static string Store(int const &r) {
			ostringstream oss;
			oss << r;
			return oss.str();
		}
	};

	template<>
	struct Serializer<unsigned int> {
		template<typename _Iterator>
		static unsigned int Load(_Iterator &ri, _Iterator j) {
			// TODO
			throw Error();
		}

		static string Store(unsigned int const &r) {
			ostringstream oss;
			oss << r;
			return oss.str();
		}
	};

	template<>
	struct Serializer<double> {
		template<typename _Iterator>
		static double Load(_Iterator &ri, _Iterator j) {
			// TODO
			throw Error();
		}

		static string Store(double const &r) {
			ostringstream oss;
			oss << r;
			return oss.str();
		}
	};

	template<>
	struct Serializer<string> {
		template<typename _Iterator>
		static string Load(_Iterator &ri, _Iterator j) {
			// TODO
			throw Error();
		}

		static string Store(ostream &ros, string const &r) {
			return "\"" + r + "\""; // FIXME escape special characters
		}
	};

	template<typename ..._Fields>
	struct Serializer<Object<_Fields...>> {
		template<typename _Iterator>
		static Object<_Fields...> Load(_Iterator &ri, _Iterator j) {
			// TODO
			throw Error();
		}
	};

	template<typename _Element>
	struct Serializer<vector<_Element>> {
		template<typename _Iterator>
		static vector<_Element> Load(_Iterator &ri, _Iterator j) {
			// TODO
			throw Error();
		}
	};

	template<typename _Element, unsigned int _c>
	struct Serializer<array<_Element, _c>> {
		template<typename _Iterator>
		static array<_Element, _c> Load(_Iterator &ri, _Iterator j) {
			// TODO
			throw Error();
		}
	};

	template<typename _Type>
	inline _Type Load(string const &rstr) {
		return Serializer<_Type>::Load(rstr.begin(), rstr.end());
	}

	template<typename _Type>
	inline _Type Load(istream &ris) {
		string const str = string(istreambuf_iterator<char>(ris), istreambuf_iterator<char>());
		auto it = str.begin();
		return Serializer<_Type>::Load(it, str.end());
	}

	template<typename _Type>
	inline string Store(_Type const &r) {
		return Serializer<_Type>::Store(r);
	}

	template<typename _Type>
	inline ostream &Store(ostream &ros, _Type const &r) {
		return ros << Serializer<_Type>::Store(r);
	}
}

template<typename ..._Fields>
inline std::istream &operator >> (std::istream &ris, JSON::Object<_Fields...> &rObject) {
	rObject = JSON::Load<JSON::Object<_Fields...>>(ris);
	return ris;
}

template<typename ..._Fields>
inline std::ostream &operator << (std::ostream &ros, JSON::Object<_Fields...> &rObject) {
	return JSON::Store<JSON::Object<_Fields...>>(ros, rObject);
}

#define JSON_CHAR(sz, i) ((i) < sizeof(sz)) ? (sz)[i] : 0
#define JSON_UNPACK(sz) \
	JSON_CHAR((sz), 0), \
	JSON_CHAR((sz), 1), \
	JSON_CHAR((sz), 2), \
	JSON_CHAR((sz), 3), \
	JSON_CHAR((sz), 4), \
	JSON_CHAR((sz), 5), \
	JSON_CHAR((sz), 6), \
	JSON_CHAR((sz), 7), \
	JSON_CHAR((sz), 8), \
	JSON_CHAR((sz), 9), \
	JSON_CHAR((sz), 10), \
	JSON_CHAR((sz), 11), \
	JSON_CHAR((sz), 12), \
	JSON_CHAR((sz), 13), \
	JSON_CHAR((sz), 14), \
	JSON_CHAR((sz), 15), \
	JSON_CHAR((sz), 16), \
	JSON_CHAR((sz), 17), \
	JSON_CHAR((sz), 18), \
	JSON_CHAR((sz), 19), \
	JSON_CHAR((sz), 20), \
	JSON_CHAR((sz), 21), \
	JSON_CHAR((sz), 22), \
	JSON_CHAR((sz), 23), \
	JSON_CHAR((sz), 24), \
	JSON_CHAR((sz), 25), \
	JSON_CHAR((sz), 26), \
	JSON_CHAR((sz), 27), \
	JSON_CHAR((sz), 28), \
	JSON_CHAR((sz), 29), \
	JSON_CHAR((sz), 30), \
	JSON_CHAR((sz), 31), \
	JSON_CHAR((sz), 32), \
	JSON_CHAR((sz), 33), \
	JSON_CHAR((sz), 34), \
	JSON_CHAR((sz), 35), \
	JSON_CHAR((sz), 36), \
	JSON_CHAR((sz), 37), \
	JSON_CHAR((sz), 38), \
	JSON_CHAR((sz), 39), \
	JSON_CHAR((sz), 40), \
	JSON_CHAR((sz), 41), \
	JSON_CHAR((sz), 42), \
	JSON_CHAR((sz), 43), \
	JSON_CHAR((sz), 44), \
	JSON_CHAR((sz), 45), \
	JSON_CHAR((sz), 46), \
	JSON_CHAR((sz), 47), \
	JSON_CHAR((sz), 48), \
	JSON_CHAR((sz), 49), \
	JSON_CHAR((sz), 50), \
	JSON_CHAR((sz), 51), \
	JSON_CHAR((sz), 52), \
	JSON_CHAR((sz), 53), \
	JSON_CHAR((sz), 54), \
	JSON_CHAR((sz), 55), \
	JSON_CHAR((sz), 56), \
	JSON_CHAR((sz), 57), \
	JSON_CHAR((sz), 58), \
	JSON_CHAR((sz), 59), \
	JSON_CHAR((sz), 60), \
	JSON_CHAR((sz), 61), \
	JSON_CHAR((sz), 62), \
	JSON_CHAR((sz), 63), \
	JSON_CHAR((sz), 64), \
	JSON_CHAR((sz), 65), \
	JSON_CHAR((sz), 66), \
	JSON_CHAR((sz), 67), \
	JSON_CHAR((sz), 68), \
	JSON_CHAR((sz), 69), \
	JSON_CHAR((sz), 70), \
	JSON_CHAR((sz), 71), \
	JSON_CHAR((sz), 72), \
	JSON_CHAR((sz), 73), \
	JSON_CHAR((sz), 74), \
	JSON_CHAR((sz), 75), \
	JSON_CHAR((sz), 76), \
	JSON_CHAR((sz), 77), \
	JSON_CHAR((sz), 78), \
	JSON_CHAR((sz), 79), \
	JSON_CHAR((sz), 80), \
	JSON_CHAR((sz), 81), \
	JSON_CHAR((sz), 82), \
	JSON_CHAR((sz), 83), \
	JSON_CHAR((sz), 84), \
	JSON_CHAR((sz), 85), \
	JSON_CHAR((sz), 86), \
	JSON_CHAR((sz), 87), \
	JSON_CHAR((sz), 88), \
	JSON_CHAR((sz), 89), \
	JSON_CHAR((sz), 90), \
	JSON_CHAR((sz), 91), \
	JSON_CHAR((sz), 92), \
	JSON_CHAR((sz), 93), \
	JSON_CHAR((sz), 94), \
	JSON_CHAR((sz), 95), \
	JSON_CHAR((sz), 96), \
	JSON_CHAR((sz), 97), \
	JSON_CHAR((sz), 98), \
	JSON_CHAR((sz), 99)

#define UNPACK JSON_UNPACK

#endif
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <iostream>
#include "svm_interface.h"

struct svm_parameter param;     // set by parse_command_line
struct svm_problem prob;        // set by read_problem
struct svm_model *model;
struct svm_node *x_space;

void train(const int problemSize, const int dimensions, double dataset[], double labels[]) {
	/*
	==================
	Set all parameters
	==================
	*/
	param.svm_type = C_SVC;
	param.kernel_type = RBF;
	param.degree = 3;
	param.gamma = 0.5;
	param.coef0 = 0;
	param.nu = 0.5;
	param.cache_size = 100;
	param.C = 1;
	param.eps = 1e-3;
	param.p = 0.1;
	param.shrinking = 1;
	param.probability = 0;
	param.nr_weight = 0;
	param.weight_label = NULL;
	param.weight = NULL;

	/*
	==================
	Problem definition
	==================
	*/
	//Set the number of training data
	prob.l = problemSize;

	//Set the array containing the labels of all training data
	prob.y = labels;

	/*
	for (int i = 0; i < prob.l; i++) {
		double subset[dimensions];
		for (int j = 0; j < dimensions; j++) {
			subset[j] = dataset[i*dimensions+j];
		}
		double maximum = findMaximum();
	}*/

	svm_node** x = new svm_node*[prob.l];

	for (int row = 0; row < prob.l; row++) {
		svm_node* x_space = new svm_node[dimensions + 1];
		for (int col = 0; col < dimensions; col++) {
			x_space[col].index = col;
			x_space[col].value = dataset[row*dimensions + col];
		}
		x_space[dimensions].index = -1;  //Each row of properties should be terminated with a -1 according to the readme
		x_space[dimensions].value = 0;	 //Value not important
		x[row] = x_space;
	}

	prob.x = x;

	//Train model
	model = svm_train(&prob, &param);
}

double test(const int dimensions, double testData[]) {
	svm_node* testnode = new svm_node[dimensions+1];

	for (int i = 0; i < dimensions; i++) {
		testnode[i].index = i;
		testnode[i].value = testData[i];
	}
	testnode[dimensions].index = -1;
	testnode[dimensions].value = 0;

	double retval = svm_predict(model, testnode);

	svm_destroy_param(&param);
	delete[] prob.y;
	delete[] prob.x;
	delete[] x_space;
	delete[] testnode;

	return retval;
}<commit_msg>Put some preliminary code in comments.<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <iostream>
#include "svm_interface.h"

struct svm_parameter param;     // set by parse_command_line
struct svm_problem prob;        // set by read_problem
struct svm_model *model;
struct svm_node *x_space;

void train(const int problemSize, const int dimensions, double dataset[], double labels[]) {
	/*
	==================
	Set all parameters
	==================
	*/
	param.svm_type = C_SVC;
	param.kernel_type = RBF;
	param.degree = 3;
	param.gamma = 0.5;
	param.coef0 = 0;
	param.nu = 0.5;
	param.cache_size = 100;
	param.C = 1;
	param.eps = 1e-3;
	param.p = 0.1;
	param.shrinking = 1;
	param.probability = 0;
	param.nr_weight = 0;
	param.weight_label = NULL;
	param.weight = NULL;

	/*
	==================
	Problem definition
	==================
	*/
	//Set the number of training data
	prob.l = problemSize;

	//Set the array containing the labels of all training data
	prob.y = labels;

	/*
	//Rescale the dataset
	for (int i = 0; i < prob.l; i++) {
		double* subset = new double[dimensions];
		for (int j = 0; j < dimensions; j++) {
			subset[j] = dataset[i*dimensions+j];
		}
		double maximum = rescale();
	}*/

	svm_node** x = new svm_node*[prob.l];

	for (int row = 0; row < prob.l; row++) {
		svm_node* xRow = new svm_node[dimensions + 1];
		for (int col = 0; col < dimensions; col++) {
			xRow[col].index = col;
			xRow[col].value = dataset[row*dimensions + col];
		}
		xRow[dimensions].index = -1;  //Each row of properties should be terminated with a -1 according to the readme
		xRow[dimensions].value = 0;	 //Value not important
		x[row] = xRow;
	}

	prob.x = x;

	//Train model
	model = svm_train(&prob, &param);
}

double test(const int dimensions, double testData[]) {
	svm_node* testnode = new svm_node[dimensions+1];

	for (int i = 0; i < dimensions; i++) {
		testnode[i].index = i;
		testnode[i].value = testData[i];
	}
	testnode[dimensions].index = -1;
	testnode[dimensions].value = 0;

	double retval = svm_predict(model, testnode);

	svm_destroy_param(&param);
	delete[] prob.y;
	delete[] prob.x;
	delete[] x_space;
	delete[] testnode;

	return retval;
}<|endoftext|>


<commit_before>#include <string>
#include <climits>
#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    bool isMatch(string s, string p) {
        if (s.empty()) {
            for (int i = 0; i < p.size(); i++)
                if (p[i] != '*')
                    return false;
            return true;
        }
        if (p.empty())
            return false;

        char c = p[0];
        p = p.substr(1, p.size() - 1);
        if (c == '?' || c == s[0])
            return isMatch(s.substr(1, s.size() - 1), p);

        if (c == '*') {
            if (p.empty())
                return true;
            for (int i = 0; i < s.size(); i++)
                if (isMatch(s.substr(i, s.size() - i), p))
                    return true;
        }

		return false;
    }
};

void showAns(string s, string p, bool ans) {
    cout << "[" << s << "], [" << p << "] ";
    cout << ((ans) ? "is" : "is not") << " matched (" << ((ans) ? "True" : "False") << ")" << endl;
}

int main() {
    Solution sol;
	string s;
	string p;
	bool ans;

	s = "aa";
	p = "a";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "aa";
	p = "aa";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "aaa";
	p = "aa";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "aa";
	p = "*";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "aa";
	p = "a*";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "ab";
	p = "?*";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "aab";
	p = "c*a*b";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "";
	p = "";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "a";
	p = "";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "";
	p = "a";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "a";
	p = "*a";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "ba";
	p = "*a";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "cba";
	p = "*a";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "ba";
	p = "?a";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "cba";
	p = "?a";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "";
	p = "*";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "";
	p = "?";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "";
	p = "**";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

    return 0;
}
<commit_msg>leet: 44 still exceed time limit<commit_after>#include <string>
#include <climits>
#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    bool isMatch(string s, string p) {
        if (s.empty()) {
            for (int i = 0; i < p.size(); i++)
                if (p[i] != '*')
                    return false;
            return true;
        }
        if (p.empty())
            return false;

        char c = p[0];
        p = p.substr(1, p.size() - 1);
        if (c == '?' || c == s[0])
            return isMatch(s.substr(1, s.size() - 1), p);

        if (c == '*') {
            while (p.size() > 1 && p[0] == c)
                p = p.substr(1, p.size() - 1);
            if (p.empty())
                return true;
            for (int i = 0; i < s.size(); i++)
                if (isMatch(s.substr(i, s.size() - i), p))
                    return true;
        }

		return false;
    }
};

void showAns(string s, string p, bool ans) {
    cout << "[" << s << "], [" << p << "] ";
    cout << ((ans) ? "is" : "is not") << " matched (" << ((ans) ? "True" : "False") << ")" << endl;
}

int main() {
    Solution sol;
	string s;
	string p;
	bool ans;

	s = "aa";
	p = "a";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "aa";
	p = "aa";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "aaa";
	p = "aa";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "aa";
	p = "*";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "aa";
	p = "a*";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "ab";
	p = "?*";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "aab";
	p = "c*a*b";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "";
	p = "";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "a";
	p = "";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "";
	p = "a";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "a";
	p = "*a";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "ba";
	p = "*a";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "cba";
	p = "*a";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "ba";
	p = "?a";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "cba";
	p = "?a";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "";
	p = "*";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "";
	p = "?";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

	s = "";
	p = "**";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

    s = "aaabbbaabaaaaababaabaaabbabbbbbbbbaabababbabbbaaaaba";
    p = "a*******b";
	ans = sol.isMatch(s, p);
	showAns(s, p, ans);

    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: accmap.hxx,v $
 *
 *  $Revision: 1.23 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-24 16:09:27 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _ACCMAP_HXX
#define _ACCMAP_HXX

#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <com/sun/star/accessibility/XAccessible.hpp>
#endif

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif
#ifndef _VOS_REF_HXX_
#include <vos/ref.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif
#ifndef _SVX_ACCESSIBILITY_IACCESSIBLE_VIEW_FORWARDER_HXX
#include <svx/IAccessibleViewForwarder.hxx>
#endif
#ifndef _SVX_ACCESSIBILITY_IACCESSIBLE_PARENT_HXX
#include <svx/IAccessibleParent.hxx>
#endif
#ifndef _VIEWSH_HXX
#include "viewsh.hxx"
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _FRACT_HXX
#include <tools/fract.hxx>
#endif

#include <vector>

class Rectangle;
class SwFrm;
class SwRootFrm;
class SwPageFrm;
class SwAccessibleContext;
class SwAccessibleContextMap_Impl;
class SwAccessibleEventList_Impl;
class SwAccessibleEventMap_Impl;
class SwShapeList_Impl;
class SdrObject;
namespace accessibility { class AccessibleShape; }
class SwAccessibleShapeMap_Impl;
struct SwAccessibleEvent_Impl;
class SwRect;
class ViewShell;
class SwFrmOrObj;
class SwAccPreviewData;
// OD 14.01.2003 #103492#
#ifndef _PREVWPAGE_HXX
#include <prevwpage.hxx>
#endif

// real states for events
#define ACC_STATE_EDITABLE 0x01
#define ACC_STATE_OPAQUE 0x02

// pseudo states for events
#define ACC_STATE_CARET 0x80
#define ACC_STATE_RELATION_FROM 0x40
#define ACC_STATE_RELATION_TO 0x20

#define ACC_STATE_RELATION_MASK 0x60

#define ACC_STATE_MASK 0x1F

class SwAccessibleMap : public accessibility::IAccessibleViewForwarder,
                        public accessibility::IAccessibleParent
{
    ::vos::OMutex maMutex;
    ::vos::OMutex maEventMutex;
    SwAccessibleContextMap_Impl *mpFrmMap;
    SwAccessibleShapeMap_Impl *mpShapeMap;
    SwShapeList_Impl *mpShapes;
    SwAccessibleEventList_Impl *mpEvents;
    SwAccessibleEventMap_Impl *mpEventMap;
    ViewShell *mpVSh;
    /// for page preview: store preview data, VisArea, and mapping of
    /// preview-to-display coordinates
    SwAccPreviewData* mpPreview;

    ::com::sun::star::uno::WeakReference < ::com::sun::star::accessibility::XAccessible > mxCursorContext;

    sal_Int32 mnPara;
    sal_Int32 mnFootnote;
    sal_Int32 mnEndnote;

    sal_Bool mbShapeSelected;

    void FireEvent( const SwAccessibleEvent_Impl& rEvent );

    void AppendEvent( const SwAccessibleEvent_Impl& rEvent );

    void InvalidateCursorPosition(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::accessibility::XAccessible>& rAcc );
    void DoInvalidateShapeSelection();
    void DoInvalidateShapeFocus();
    void InvalidateShapeSelection();

    void _InvalidateRelationSet( const SwFrm* pFrm, sal_Bool bFrom );

    ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>
            _GetDocumentView( sal_Bool bPagePreview );

public:

    SwAccessibleMap( ViewShell *pSh );
    ~SwAccessibleMap();

    ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible> GetDocumentView();

    // OD 15.01.2003 #103492# - complete re-factoring of method due to new
    // page/print preview functionality.
    ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible> GetDocumentPreview(
                            const std::vector<PrevwPage*>& _rPrevwPages,
                            const Fraction&  _rScale,
                            const SwPageFrm* _pSelectedPageFrm,
                            const Size&      _rPrevwWinSize );

    ::vos::ORef < SwAccessibleContext > GetContextImpl(
                                                 const SwFrm *pFrm,
                                                sal_Bool bCreate = sal_True );
    ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible> GetContext(
                                                 const SwFrm *pFrm,
                                                sal_Bool bCreate = sal_True );

    ::vos::ORef < ::accessibility::AccessibleShape > GetContextImpl(
                                        const SdrObject *pObj,
                                        SwAccessibleContext *pParentImpl,
                                        sal_Bool bCreate = sal_True );
    ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible> GetContext(
                                        const SdrObject *pObj,
                                        SwAccessibleContext *pParentImpl,
                                        sal_Bool bCreate = sal_True );

    ViewShell *GetShell() const { return mpVSh; }
    inline const SwRect& GetVisArea() const;

    /** get size of a dedicated preview page

        OD 15.01.2003 #103492#
        complete re-factoring of previous method due to new page/print preview
        functionality.

        @author OD

        @param _nPrevwPageNum
        input parameter - physical page number of page visible in the page preview

        @return an object of class <Size>
    */
    Size GetPreViewPageSize( sal_uInt16 _nPrevwPageNum ) const;

    void RemoveContext( const SwFrm *pFrm );
    void RemoveContext( const SdrObject *pObj );

    // Dispose frame and its children if bRecursive is set
    void Dispose( const SwFrm *pFrm, const SdrObject *pObj,
                  sal_Bool bRecursive=sal_False );

    void InvalidatePosOrSize( const SwFrm *pFrm, const SdrObject *pObj,
                              const SwRect& rOldFrm );

    void InvalidateContent( const SwFrm *pFrm );

    void InvalidateCursorPosition( const SwFrm *pFrm );
    void InvalidateFocus();

    void SetCursorContext(
        const ::vos::ORef < SwAccessibleContext >& rCursorContext );

    // Invalidate state of whole tree. If an action is open, this call
    // is processed when the last action ends.
    void InvalidateStates( sal_uInt8 nStates, const SwFrm *pFrm=0 );

    void InvalidateRelationSet( const SwFrm* pMaster, const SwFrm* pFollow );

    // update preview data (and fire events if necessary)
    // OD 15.01.2003 #103492# - complete re-factoring of method due to new
    // page/print preview functionality.
    void UpdatePreview( const std::vector<PrevwPage*>& _rPrevwPages,
                        const Fraction&  _rScale,
                        const SwPageFrm* _pSelectedPageFrm,
                        const Size&      _rPrevwWinSize );

    void InvalidatePreViewSelection( sal_uInt16 nSelPage );
    sal_Bool IsPageSelected( const SwPageFrm *pPageFrm ) const;

    void FireEvents();

    // IAccessibleViewForwarder

    virtual sal_Bool IsValid() const;
    virtual Rectangle GetVisibleArea() const;
    virtual Point LogicToPixel (const Point& rPoint) const;
    virtual Size LogicToPixel (const Size& rSize) const;
    virtual Point PixelToLogic (const Point& rPoint) const;
    virtual Size PixelToLogic (const Size& rSize) const;

    // IAccessibleParent
    virtual sal_Bool ReplaceChild (
        ::accessibility::AccessibleShape* pCurrentChild,
        const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& _rxShape,
        const long _nIndex,
        const ::accessibility::AccessibleShapeTreeInfo& _rShapeTreeInfo
    )   throw (::com::sun::star::uno::RuntimeException);

    // additional Core/Pixel conversions for internal use; also works
    // for preview
    Point PixelToCore (const Point& rPoint) const;
    Rectangle CoreToPixel (const Rectangle& rRect) const;
    Rectangle PixelToCore (const Rectangle& rRect) const;

private:
    /** get mapping mode for LogicToPixel and PixelToLogic conversions

        OD 15.01.2003 #103492#
        Replacement method <PreviewAdjust(..)> by new method <GetMapMode>.
        Method returns mapping mode of current output device and adjusts it,
        if the shell is in page/print preview.
        Necessary, because <PreviewAdjust(..)> changes mapping mode at current
        output device for mapping logic document positions to page preview window
        positions and vice versa and doesn't take care to recover its changes.

        @author OD

        @param _rPoint
        input parameter - constant reference to point to determine the mapping
        mode adjustments for page/print preview.

        @param _orMapMode
        output parameter - reference to the mapping mode, which is determined
        by the method
    */
    void GetMapMode( const Point& _rPoint,
                     MapMode&     _orMapMode ) const;
};

// helper class that stores preview data
class SwAccPreviewData
{
    typedef std::vector<Rectangle> Rectangles;
    Rectangles maPreviewRects;
    Rectangles maLogicRects;

    SwRect maVisArea;
    Fraction maScale;

    const SwPageFrm *mpSelPage;

    /** adjust logic page retangle to its visible part

        OD 17.01.2003 #103492#

        @author OD

        @param _iorLogicPgSwRect
        input/output parameter - reference to the logic page rectangle, which
        has to be adjusted.

        @param _rPrevwPgSwRect
        input parameter - constant reference to the corresponding preview page
        rectangle; needed to determine the visible part of the logic page rectangle.

        @param _rPrevwWinSize
        input paramter - constant reference to the preview window size in TWIP;
        needed to determine the visible part of the logic page rectangle
    */
    void AdjustLogicPgRectToVisibleArea( SwRect&         _iorLogicPgSwRect,
                                         const SwRect&   _rPrevwPgSwRect,
                                         const Size&     _rPrevwWinSize );

public:
    SwAccPreviewData();
    ~SwAccPreviewData();

    // OD 14.01.2003 #103492# - complete re-factoring of method due to new
    // page/print preview functionality.
    void Update( const std::vector<PrevwPage*>& _rPrevwPages,
                 const Fraction&  _rScale,
                 const SwPageFrm* _pSelectedPageFrm,
                 const Size&      _rPrevwWinSize );

    // OD 14.01.2003 #103492# - complete re-factoring of method due to new
    // page/print preview functionality.
    void InvalidateSelection( const SwPageFrm* _pSelectedPageFrm );

    const SwRect& GetVisArea() const;

    MapMode GetMapModeForPreview( ) const;

    /** Adjust the MapMode so that the preview page appears at the
     * proper position. rPoint identifies the page for which the
     * MapMode should be adjusted. If bFromPreview is true, rPoint is
     * a preview coordinate; else it's a document coordinate. */
    // OD 17.01.2003 #103492# - delete unused 3rd parameter.
    void AdjustMapMode( MapMode& rMapMode,
                        const Point& rPoint ) const;

    inline const SwPageFrm *GetSelPage() const { return mpSelPage; }

    void DisposePage(const SwPageFrm *pPageFrm );
};

inline const SwRect& SwAccessibleMap::GetVisArea() const
{
    DBG_ASSERT( !mpVSh->IsPreView() || (mpPreview != NULL),
                "preview without preview data?" );
    return mpVSh->IsPreView() ? mpPreview->GetVisArea() : mpVSh->VisArea();
}
#endif
<commit_msg>INTEGRATION: CWS tune05 (1.23.564); FILE MERGED 2004/07/22 10:55:11 cmc 1.23.564.1: #i30554# unused SwAccessibleMap::PixelToCore varient<commit_after>/*************************************************************************
 *
 *  $RCSfile: accmap.hxx,v $
 *
 *  $Revision: 1.24 $
 *
 *  last change: $Author: obo $ $Date: 2004-08-12 11:59:25 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _ACCMAP_HXX
#define _ACCMAP_HXX

#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <com/sun/star/accessibility/XAccessible.hpp>
#endif

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif
#ifndef _VOS_REF_HXX_
#include <vos/ref.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif
#ifndef _SVX_ACCESSIBILITY_IACCESSIBLE_VIEW_FORWARDER_HXX
#include <svx/IAccessibleViewForwarder.hxx>
#endif
#ifndef _SVX_ACCESSIBILITY_IACCESSIBLE_PARENT_HXX
#include <svx/IAccessibleParent.hxx>
#endif
#ifndef _VIEWSH_HXX
#include "viewsh.hxx"
#endif

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _FRACT_HXX
#include <tools/fract.hxx>
#endif

#include <vector>

class Rectangle;
class SwFrm;
class SwRootFrm;
class SwPageFrm;
class SwAccessibleContext;
class SwAccessibleContextMap_Impl;
class SwAccessibleEventList_Impl;
class SwAccessibleEventMap_Impl;
class SwShapeList_Impl;
class SdrObject;
namespace accessibility { class AccessibleShape; }
class SwAccessibleShapeMap_Impl;
struct SwAccessibleEvent_Impl;
class SwRect;
class ViewShell;
class SwFrmOrObj;
class SwAccPreviewData;
// OD 14.01.2003 #103492#
#ifndef _PREVWPAGE_HXX
#include <prevwpage.hxx>
#endif

// real states for events
#define ACC_STATE_EDITABLE 0x01
#define ACC_STATE_OPAQUE 0x02

// pseudo states for events
#define ACC_STATE_CARET 0x80
#define ACC_STATE_RELATION_FROM 0x40
#define ACC_STATE_RELATION_TO 0x20

#define ACC_STATE_RELATION_MASK 0x60

#define ACC_STATE_MASK 0x1F

class SwAccessibleMap : public accessibility::IAccessibleViewForwarder,
                        public accessibility::IAccessibleParent
{
    ::vos::OMutex maMutex;
    ::vos::OMutex maEventMutex;
    SwAccessibleContextMap_Impl *mpFrmMap;
    SwAccessibleShapeMap_Impl *mpShapeMap;
    SwShapeList_Impl *mpShapes;
    SwAccessibleEventList_Impl *mpEvents;
    SwAccessibleEventMap_Impl *mpEventMap;
    ViewShell *mpVSh;
    /// for page preview: store preview data, VisArea, and mapping of
    /// preview-to-display coordinates
    SwAccPreviewData* mpPreview;

    ::com::sun::star::uno::WeakReference < ::com::sun::star::accessibility::XAccessible > mxCursorContext;

    sal_Int32 mnPara;
    sal_Int32 mnFootnote;
    sal_Int32 mnEndnote;

    sal_Bool mbShapeSelected;

    void FireEvent( const SwAccessibleEvent_Impl& rEvent );

    void AppendEvent( const SwAccessibleEvent_Impl& rEvent );

    void InvalidateCursorPosition(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::accessibility::XAccessible>& rAcc );
    void DoInvalidateShapeSelection();
    void DoInvalidateShapeFocus();
    void InvalidateShapeSelection();

    void _InvalidateRelationSet( const SwFrm* pFrm, sal_Bool bFrom );

    ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>
            _GetDocumentView( sal_Bool bPagePreview );

public:

    SwAccessibleMap( ViewShell *pSh );
    ~SwAccessibleMap();

    ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible> GetDocumentView();

    // OD 15.01.2003 #103492# - complete re-factoring of method due to new
    // page/print preview functionality.
    ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible> GetDocumentPreview(
                            const std::vector<PrevwPage*>& _rPrevwPages,
                            const Fraction&  _rScale,
                            const SwPageFrm* _pSelectedPageFrm,
                            const Size&      _rPrevwWinSize );

    ::vos::ORef < SwAccessibleContext > GetContextImpl(
                                                 const SwFrm *pFrm,
                                                sal_Bool bCreate = sal_True );
    ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible> GetContext(
                                                 const SwFrm *pFrm,
                                                sal_Bool bCreate = sal_True );

    ::vos::ORef < ::accessibility::AccessibleShape > GetContextImpl(
                                        const SdrObject *pObj,
                                        SwAccessibleContext *pParentImpl,
                                        sal_Bool bCreate = sal_True );
    ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible> GetContext(
                                        const SdrObject *pObj,
                                        SwAccessibleContext *pParentImpl,
                                        sal_Bool bCreate = sal_True );

    ViewShell *GetShell() const { return mpVSh; }
    inline const SwRect& GetVisArea() const;

    /** get size of a dedicated preview page

        OD 15.01.2003 #103492#
        complete re-factoring of previous method due to new page/print preview
        functionality.

        @author OD

        @param _nPrevwPageNum
        input parameter - physical page number of page visible in the page preview

        @return an object of class <Size>
    */
    Size GetPreViewPageSize( sal_uInt16 _nPrevwPageNum ) const;

    void RemoveContext( const SwFrm *pFrm );
    void RemoveContext( const SdrObject *pObj );

    // Dispose frame and its children if bRecursive is set
    void Dispose( const SwFrm *pFrm, const SdrObject *pObj,
                  sal_Bool bRecursive=sal_False );

    void InvalidatePosOrSize( const SwFrm *pFrm, const SdrObject *pObj,
                              const SwRect& rOldFrm );

    void InvalidateContent( const SwFrm *pFrm );

    void InvalidateCursorPosition( const SwFrm *pFrm );
    void InvalidateFocus();

    void SetCursorContext(
        const ::vos::ORef < SwAccessibleContext >& rCursorContext );

    // Invalidate state of whole tree. If an action is open, this call
    // is processed when the last action ends.
    void InvalidateStates( sal_uInt8 nStates, const SwFrm *pFrm=0 );

    void InvalidateRelationSet( const SwFrm* pMaster, const SwFrm* pFollow );

    // update preview data (and fire events if necessary)
    // OD 15.01.2003 #103492# - complete re-factoring of method due to new
    // page/print preview functionality.
    void UpdatePreview( const std::vector<PrevwPage*>& _rPrevwPages,
                        const Fraction&  _rScale,
                        const SwPageFrm* _pSelectedPageFrm,
                        const Size&      _rPrevwWinSize );

    void InvalidatePreViewSelection( sal_uInt16 nSelPage );
    sal_Bool IsPageSelected( const SwPageFrm *pPageFrm ) const;

    void FireEvents();

    // IAccessibleViewForwarder

    virtual sal_Bool IsValid() const;
    virtual Rectangle GetVisibleArea() const;
    virtual Point LogicToPixel (const Point& rPoint) const;
    virtual Size LogicToPixel (const Size& rSize) const;
    virtual Point PixelToLogic (const Point& rPoint) const;
    virtual Size PixelToLogic (const Size& rSize) const;

    // IAccessibleParent
    virtual sal_Bool ReplaceChild (
        ::accessibility::AccessibleShape* pCurrentChild,
        const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& _rxShape,
        const long _nIndex,
        const ::accessibility::AccessibleShapeTreeInfo& _rShapeTreeInfo
    )   throw (::com::sun::star::uno::RuntimeException);

    // additional Core/Pixel conversions for internal use; also works
    // for preview
    Point PixelToCore (const Point& rPoint) const;
    Rectangle CoreToPixel (const Rectangle& rRect) const;

private:
    /** get mapping mode for LogicToPixel and PixelToLogic conversions

        OD 15.01.2003 #103492#
        Replacement method <PreviewAdjust(..)> by new method <GetMapMode>.
        Method returns mapping mode of current output device and adjusts it,
        if the shell is in page/print preview.
        Necessary, because <PreviewAdjust(..)> changes mapping mode at current
        output device for mapping logic document positions to page preview window
        positions and vice versa and doesn't take care to recover its changes.

        @author OD

        @param _rPoint
        input parameter - constant reference to point to determine the mapping
        mode adjustments for page/print preview.

        @param _orMapMode
        output parameter - reference to the mapping mode, which is determined
        by the method
    */
    void GetMapMode( const Point& _rPoint,
                     MapMode&     _orMapMode ) const;
};

// helper class that stores preview data
class SwAccPreviewData
{
    typedef std::vector<Rectangle> Rectangles;
    Rectangles maPreviewRects;
    Rectangles maLogicRects;

    SwRect maVisArea;
    Fraction maScale;

    const SwPageFrm *mpSelPage;

    /** adjust logic page retangle to its visible part

        OD 17.01.2003 #103492#

        @author OD

        @param _iorLogicPgSwRect
        input/output parameter - reference to the logic page rectangle, which
        has to be adjusted.

        @param _rPrevwPgSwRect
        input parameter - constant reference to the corresponding preview page
        rectangle; needed to determine the visible part of the logic page rectangle.

        @param _rPrevwWinSize
        input paramter - constant reference to the preview window size in TWIP;
        needed to determine the visible part of the logic page rectangle
    */
    void AdjustLogicPgRectToVisibleArea( SwRect&         _iorLogicPgSwRect,
                                         const SwRect&   _rPrevwPgSwRect,
                                         const Size&     _rPrevwWinSize );

public:
    SwAccPreviewData();
    ~SwAccPreviewData();

    // OD 14.01.2003 #103492# - complete re-factoring of method due to new
    // page/print preview functionality.
    void Update( const std::vector<PrevwPage*>& _rPrevwPages,
                 const Fraction&  _rScale,
                 const SwPageFrm* _pSelectedPageFrm,
                 const Size&      _rPrevwWinSize );

    // OD 14.01.2003 #103492# - complete re-factoring of method due to new
    // page/print preview functionality.
    void InvalidateSelection( const SwPageFrm* _pSelectedPageFrm );

    const SwRect& GetVisArea() const;

    MapMode GetMapModeForPreview( ) const;

    /** Adjust the MapMode so that the preview page appears at the
     * proper position. rPoint identifies the page for which the
     * MapMode should be adjusted. If bFromPreview is true, rPoint is
     * a preview coordinate; else it's a document coordinate. */
    // OD 17.01.2003 #103492# - delete unused 3rd parameter.
    void AdjustMapMode( MapMode& rMapMode,
                        const Point& rPoint ) const;

    inline const SwPageFrm *GetSelPage() const { return mpSelPage; }

    void DisposePage(const SwPageFrm *pPageFrm );
};

inline const SwRect& SwAccessibleMap::GetVisArea() const
{
    DBG_ASSERT( !mpVSh->IsPreView() || (mpPreview != NULL),
                "preview without preview data?" );
    return mpVSh->IsPreView() ? mpPreview->GetVisArea() : mpVSh->VisArea();
}
#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: flypos.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 17:14:25 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _FLYPOS_HXX
#define _FLYPOS_HXX

#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif

class SwCntntNode;
class ViewShell;
class SwFrmFmt;
class SwNodeIndex;

// Struktur zum Erfragen der akt. freifliegenden Rahmen am Dokument.
class SwPosFlyFrm
{
    const SwFrmFmt* pFrmFmt;    // das FlyFrmFmt
//  SwPosition* pPos;           // Position in den ContentNode
    SwNodeIndex* pNdIdx;        // es reicht ein Index auf den Node
    UINT32 nOrdNum;
public:
    SwPosFlyFrm( const SwNodeIndex& , const SwFrmFmt*, USHORT nArrPos );
    virtual ~SwPosFlyFrm(); // virtual fuer die Writer (DLL !!)

    // operatoren fuer das Sort-Array
    BOOL operator==( const SwPosFlyFrm& );
    BOOL operator<( const SwPosFlyFrm& );

    const SwFrmFmt& GetFmt() const { return *pFrmFmt; }
    const SwNodeIndex& GetNdIndex() const { return *pNdIdx; }
    UINT32 GetOrdNum() const { return nOrdNum; }
};

typedef SwPosFlyFrm* SwPosFlyFrmPtr;
SV_DECL_PTRARR_SORT( SwPosFlyFrms, SwPosFlyFrmPtr, 0, 40 )

#endif _FLYPOS_HXX
<commit_msg>INTEGRATION: CWS rt02 (1.1.1.1.438); FILE MERGED 2003/09/30 15:44:03 rt 1.1.1.1.438.1: #i19697# Fixed comment after preprocessor directive<commit_after>/*************************************************************************
 *
 *  $RCSfile: flypos.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2003-10-06 14:31:00 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _FLYPOS_HXX
#define _FLYPOS_HXX

#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif

class SwCntntNode;
class ViewShell;
class SwFrmFmt;
class SwNodeIndex;

// Struktur zum Erfragen der akt. freifliegenden Rahmen am Dokument.
class SwPosFlyFrm
{
    const SwFrmFmt* pFrmFmt;    // das FlyFrmFmt
//  SwPosition* pPos;           // Position in den ContentNode
    SwNodeIndex* pNdIdx;        // es reicht ein Index auf den Node
    UINT32 nOrdNum;
public:
    SwPosFlyFrm( const SwNodeIndex& , const SwFrmFmt*, USHORT nArrPos );
    virtual ~SwPosFlyFrm(); // virtual fuer die Writer (DLL !!)

    // operatoren fuer das Sort-Array
    BOOL operator==( const SwPosFlyFrm& );
    BOOL operator<( const SwPosFlyFrm& );

    const SwFrmFmt& GetFmt() const { return *pFrmFmt; }
    const SwNodeIndex& GetNdIndex() const { return *pNdIdx; }
    UINT32 GetOrdNum() const { return nOrdNum; }
};

typedef SwPosFlyFrm* SwPosFlyFrmPtr;
SV_DECL_PTRARR_SORT( SwPosFlyFrms, SwPosFlyFrmPtr, 0, 40 )

#endif // _FLYPOS_HXX
<|endoftext|>