<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------

#include "ValuePrinterSynthesizer.h"

#include "ASTUtils.h"
#include "ChainedConsumer.h"
#include "cling/Interpreter/Interpreter.h"

#include "clang/AST/DeclGroup.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/ExprCXX.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/Sema.h"

using namespace clang;

namespace cling {

  ValuePrinterSynthesizer::ValuePrinterSynthesizer(Interpreter* Interp)
    : m_Interpreter(Interp)
  { }

  ValuePrinterSynthesizer::~ValuePrinterSynthesizer() {}

  void ValuePrinterSynthesizer::TransformTopLevelDecl(DeclGroupRef DGR) {
    for (DeclGroupRef::iterator I = DGR.begin(), E = DGR.end(); I != E; ++I)
      if (FunctionDecl* FD = dyn_cast<FunctionDecl>(*I)) {
        if (FD->getNameAsString().find("__cling_Un1Qu3"))
          return;

        if (CompoundStmt* CS = dyn_cast<CompoundStmt>(FD->getBody())) {
          for (CompoundStmt::body_iterator
                 J = CS->body_begin(), E = CS->body_end(); J != E; ++J) {
            if (J+1 ==  E || !isa<NullStmt>(*(J+1))) {
              Expr* To = 0;
              if (ReturnStmt* RS = dyn_cast<ReturnStmt>(*J))
                To = RS->getRetValue();
              else
                To = dyn_cast<Expr>(*J);
              if (To) {
                ChainedConsumer* C = dyn_cast<ChainedConsumer>(&m_Sema->Consumer);
                bool p, q;
                p = C->DisableConsumer(ChainedConsumer::kDeclExtractor);
                q = C->DisableConsumer(ChainedConsumer::kValuePrinterSynthesizer);
                Expr* Result = 0;
                if (m_Sema->getLangOpts().CPlusPlus)
                  Result = SynthesizeCppVP(To);
                else
                  Result = SynthesizeVP(To);

                if (ReturnStmt* RS = dyn_cast<ReturnStmt>(*J))
                  RS->setRetValue(Result);
                else
                  *J = Result;
                C->RestorePreviousState(ChainedConsumer::kDeclExtractor, p);
                C->RestorePreviousState(ChainedConsumer::kValuePrinterSynthesizer, q);
              }
            }
          }
          // Clear the artificial NullStmt-s
          if (!ClearNullStmts(CS)) {
            // if no body remove the wrapper
            DeclContext* DC = FD->getDeclContext();
            Scope* S = m_Sema->getScopeForContext(DC);
            if (S)
              S->RemoveDecl(FD);
            DC->removeDecl(FD);
          }
        }
      }
  }

  // We need to artificially create:
  // cling::valuePrinterInternal::PrintValue((void*) raw_ostream,
  //                                         (ASTContext)Ctx, (Expr*)E, &i);
  Expr* ValuePrinterSynthesizer::SynthesizeCppVP(Expr* E) {
    QualType QT = E->getType();
    // For now we skip void and function pointer types.
    if (!QT.isNull() && (QT->isVoidType() || QT->isFunctionType()))
      return 0;

    // 1. Call gCling->getValuePrinterStream()
    // 1.1. Find gCling
    SourceLocation NoSLoc = SourceLocation();

    NamespaceDecl* NSD = Lookup::Namespace(m_Sema, "cling");
    NSD = Lookup::Namespace(m_Sema, "valuePrinterInternal", NSD);

    DeclarationName PVName = &m_Context->Idents.get("PrintValue");
    LookupResult R(*m_Sema, PVName, NoSLoc, Sema::LookupOrdinaryName,
                   Sema::ForRedeclaration);

    m_Sema->LookupQualifiedName(R, NSD);
    assert(!R.empty() && "Cannot find PrintValue(...)");

    CXXScopeSpec CSS;
    Expr* UnresolvedLookup
      = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take();

    // 2.4. Prepare the params

    // 2.4.1 Lookup the llvm::raw_ostream
    CXXRecordDecl* RawOStreamRD
      = dyn_cast<CXXRecordDecl>(Lookup::Named(m_Sema, "raw_ostream",
                                              Lookup::Namespace(m_Sema, "llvm")));

    assert(RawOStreamRD && "Declaration of the expr not found!");
    QualType RawOStreamRDTy = m_Context->getTypeDeclType(RawOStreamRD);
    // 2.4.2 Lookup the expr type
    CXXRecordDecl* ExprRD
      = dyn_cast<CXXRecordDecl>(Lookup::Named(m_Sema, "Expr",
                                              Lookup::Namespace(m_Sema, "clang")));
   assert(ExprRD && "Declaration of the expr not found!");
    QualType ExprRDTy = m_Context->getTypeDeclType(ExprRD);
    // 2.4.3 Lookup ASTContext type
    CXXRecordDecl* ASTContextRD
      = dyn_cast<CXXRecordDecl>(Lookup::Named(m_Sema, "ASTContext",
                                              Lookup::Namespace(m_Sema, "clang")));
    assert(ASTContextRD && "Declaration of the expr not found!");
    QualType ASTContextRDTy = m_Context->getTypeDeclType(ASTContextRD);

    Expr* RawOStreamTy
      = Synthesize::CStyleCastPtrExpr(m_Sema, RawOStreamRDTy,
                               (uint64_t)&m_Interpreter->getValuePrinterStream()
                                      );

    Expr* ExprTy = Synthesize::CStyleCastPtrExpr(m_Sema, ExprRDTy, (uint64_t)E);
    Expr* ASTContextTy = Synthesize::CStyleCastPtrExpr(m_Sema,
                                                       ASTContextRDTy,
                                                       (uint64_t)m_Context);

    // E might contain temporaries. This means that the topmost expr is
    // ExprWithCleanups. This contains the information about the temporaries and
    // signals when they should be destroyed.
    // Here we replace E with call to value printer and we must extend the life
    // time of those temporaries to the end of the new CallExpr.
    bool NeedsCleanup = false;
    if (ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(E)) {
      E = EWC->getSubExpr();
      NeedsCleanup = true;
    }

    ASTOwningVector<Expr*> CallArgs(*m_Sema);
    CallArgs.push_back(RawOStreamTy);
    CallArgs.push_back(ExprTy);
    CallArgs.push_back(ASTContextTy);
    CallArgs.push_back(E);

    Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext);
    Expr* Result = m_Sema->ActOnCallExpr(S, UnresolvedLookup, NoSLoc,
                                         move_arg(CallArgs), NoSLoc).take();

    Result = m_Sema->ActOnFinishFullExpr(Result).take();
    if (NeedsCleanup && !isa<ExprWithCleanups>(Result)) {
      llvm::ArrayRef<ExprWithCleanups::CleanupObject> Cleanups;
      ExprWithCleanups* EWC
        = ExprWithCleanups::Create(*m_Context, Result, Cleanups);
      Result = EWC;
    }

    assert(Result && "Cannot create value printer!");

    return Result;
  }

  // We need to artificially create:
  // cling_PrintValue(void* (ASTContext)C, void* (Expr)E, const void* (&i)
  Expr* ValuePrinterSynthesizer::SynthesizeVP(Expr* E) {
    QualType QT = E->getType();
    // For now we skip void and function pointer types.
    if (!QT.isNull() && (QT->isVoidType() || QT->isFunctionType()))
      return 0;

    // Find cling_PrintValue
    SourceLocation NoSLoc = SourceLocation();
    DeclarationName PVName = &m_Context->Idents.get("cling_PrintValue");
    LookupResult R(*m_Sema, PVName, NoSLoc, Sema::LookupOrdinaryName,
                   Sema::ForRedeclaration);

    Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext);
    m_Sema->LookupName(R, S);
    assert(!R.empty() && "Cannot find PrintValue(...)");

    CXXScopeSpec CSS;
    Expr* UnresolvedLookup
      = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take();

    Expr* VoidEArg = Synthesize::CStyleCastPtrExpr(m_Sema, m_Context->VoidPtrTy,
                                                   (uint64_t)E);
    Expr* VoidCArg = Synthesize::CStyleCastPtrExpr(m_Sema, m_Context->VoidPtrTy,
                                                   (uint64_t)m_Context);

    if (!QT->isPointerType()) {
      while(ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E))
        E = ICE->getSubExpr();
      E = m_Sema->BuildUnaryOp(S, NoSLoc, UO_AddrOf, E).take();
    }

    ASTOwningVector<Expr*> CallArgs(*m_Sema);
    CallArgs.push_back(VoidEArg);
    CallArgs.push_back(VoidCArg);
    CallArgs.push_back(E);

    Expr* Result = m_Sema->ActOnCallExpr(S, UnresolvedLookup, NoSLoc,
                                         move_arg(CallArgs), NoSLoc).take();
    assert(Result && "Cannot create value printer!");

    return Result;
  }

  unsigned ValuePrinterSynthesizer::ClearNullStmts(CompoundStmt* CS) {
    llvm::SmallVector<Stmt*, 8> FBody;
    for (StmtRange range = CS->children(); range; ++range)
      if (!isa<NullStmt>(*range))
        FBody.push_back(*range);

    CS->setStmts(*m_Context, FBody.data(), FBody.size());
    return FBody.size();
  }

} // namespace cling
<commit_msg>Check first the whether the consumer was able to synthesize the value printer call.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------

#include "ValuePrinterSynthesizer.h"

#include "ASTUtils.h"
#include "ChainedConsumer.h"
#include "cling/Interpreter/Interpreter.h"

#include "clang/AST/DeclGroup.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/ExprCXX.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/Sema.h"

using namespace clang;

namespace cling {

  ValuePrinterSynthesizer::ValuePrinterSynthesizer(Interpreter* Interp)
    : m_Interpreter(Interp)
  { }

  ValuePrinterSynthesizer::~ValuePrinterSynthesizer() {}

  void ValuePrinterSynthesizer::TransformTopLevelDecl(DeclGroupRef DGR) {
    for (DeclGroupRef::iterator I = DGR.begin(), E = DGR.end(); I != E; ++I)
      if (FunctionDecl* FD = dyn_cast<FunctionDecl>(*I)) {
        if (FD->getNameAsString().find("__cling_Un1Qu3"))
          return;

        if (CompoundStmt* CS = dyn_cast<CompoundStmt>(FD->getBody())) {
          for (CompoundStmt::body_iterator
                 J = CS->body_begin(), E = CS->body_end(); J != E; ++J) {
            if (J+1 ==  E || !isa<NullStmt>(*(J+1))) {
              Expr* To = 0;
              if (ReturnStmt* RS = dyn_cast<ReturnStmt>(*J))
                To = RS->getRetValue();
              else
                To = dyn_cast<Expr>(*J);
              if (To) {
                ChainedConsumer* C = dyn_cast<ChainedConsumer>(&m_Sema->Consumer);
                bool p, q;
                p = C->DisableConsumer(ChainedConsumer::kDeclExtractor);
                q = C->DisableConsumer(ChainedConsumer::kValuePrinterSynthesizer);
                Expr* Result = 0;
                if (m_Sema->getLangOpts().CPlusPlus)
                  Result = SynthesizeCppVP(To);
                else
                  Result = SynthesizeVP(To);

                if (Result)
                  if (ReturnStmt* RS = dyn_cast<ReturnStmt>(*J))
                    RS->setRetValue(Result);
                  else
                    *J = Result;

                C->RestorePreviousState(ChainedConsumer::kDeclExtractor, p);
                C->RestorePreviousState(ChainedConsumer::kValuePrinterSynthesizer, q);
              }
            }
          }
          // Clear the artificial NullStmt-s
          if (!ClearNullStmts(CS)) {
            // if no body remove the wrapper
            DeclContext* DC = FD->getDeclContext();
            Scope* S = m_Sema->getScopeForContext(DC);
            if (S)
              S->RemoveDecl(FD);
            DC->removeDecl(FD);
          }
        }
      }
  }

  // We need to artificially create:
  // cling::valuePrinterInternal::PrintValue((void*) raw_ostream,
  //                                         (ASTContext)Ctx, (Expr*)E, &i);
  Expr* ValuePrinterSynthesizer::SynthesizeCppVP(Expr* E) {
    QualType QT = E->getType();
    // For now we skip void and function pointer types.
    if (!QT.isNull() && (QT->isVoidType() || QT->isFunctionType()))
      return 0;

    // 1. Call gCling->getValuePrinterStream()
    // 1.1. Find gCling
    SourceLocation NoSLoc = SourceLocation();

    NamespaceDecl* NSD = Lookup::Namespace(m_Sema, "cling");
    NSD = Lookup::Namespace(m_Sema, "valuePrinterInternal", NSD);

    DeclarationName PVName = &m_Context->Idents.get("PrintValue");
    LookupResult R(*m_Sema, PVName, NoSLoc, Sema::LookupOrdinaryName,
                   Sema::ForRedeclaration);

    m_Sema->LookupQualifiedName(R, NSD);
    assert(!R.empty() && "Cannot find PrintValue(...)");

    CXXScopeSpec CSS;
    Expr* UnresolvedLookup
      = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take();

    // 2.4. Prepare the params

    // 2.4.1 Lookup the llvm::raw_ostream
    CXXRecordDecl* RawOStreamRD
      = dyn_cast<CXXRecordDecl>(Lookup::Named(m_Sema, "raw_ostream",
                                              Lookup::Namespace(m_Sema, "llvm")));

    assert(RawOStreamRD && "Declaration of the expr not found!");
    QualType RawOStreamRDTy = m_Context->getTypeDeclType(RawOStreamRD);
    // 2.4.2 Lookup the expr type
    CXXRecordDecl* ExprRD
      = dyn_cast<CXXRecordDecl>(Lookup::Named(m_Sema, "Expr",
                                              Lookup::Namespace(m_Sema, "clang")));
   assert(ExprRD && "Declaration of the expr not found!");
    QualType ExprRDTy = m_Context->getTypeDeclType(ExprRD);
    // 2.4.3 Lookup ASTContext type
    CXXRecordDecl* ASTContextRD
      = dyn_cast<CXXRecordDecl>(Lookup::Named(m_Sema, "ASTContext",
                                              Lookup::Namespace(m_Sema, "clang")));
    assert(ASTContextRD && "Declaration of the expr not found!");
    QualType ASTContextRDTy = m_Context->getTypeDeclType(ASTContextRD);

    Expr* RawOStreamTy
      = Synthesize::CStyleCastPtrExpr(m_Sema, RawOStreamRDTy,
                               (uint64_t)&m_Interpreter->getValuePrinterStream()
                                      );

    Expr* ExprTy = Synthesize::CStyleCastPtrExpr(m_Sema, ExprRDTy, (uint64_t)E);
    Expr* ASTContextTy = Synthesize::CStyleCastPtrExpr(m_Sema,
                                                       ASTContextRDTy,
                                                       (uint64_t)m_Context);

    // E might contain temporaries. This means that the topmost expr is
    // ExprWithCleanups. This contains the information about the temporaries and
    // signals when they should be destroyed.
    // Here we replace E with call to value printer and we must extend the life
    // time of those temporaries to the end of the new CallExpr.
    bool NeedsCleanup = false;
    if (ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(E)) {
      E = EWC->getSubExpr();
      NeedsCleanup = true;
    }

    ASTOwningVector<Expr*> CallArgs(*m_Sema);
    CallArgs.push_back(RawOStreamTy);
    CallArgs.push_back(ExprTy);
    CallArgs.push_back(ASTContextTy);
    CallArgs.push_back(E);

    Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext);
    Expr* Result = m_Sema->ActOnCallExpr(S, UnresolvedLookup, NoSLoc,
                                         move_arg(CallArgs), NoSLoc).take();

    Result = m_Sema->ActOnFinishFullExpr(Result).take();
    if (NeedsCleanup && !isa<ExprWithCleanups>(Result)) {
      llvm::ArrayRef<ExprWithCleanups::CleanupObject> Cleanups;
      ExprWithCleanups* EWC
        = ExprWithCleanups::Create(*m_Context, Result, Cleanups);
      Result = EWC;
    }

    assert(Result && "Cannot create value printer!");

    return Result;
  }

  // We need to artificially create:
  // cling_PrintValue(void* (ASTContext)C, void* (Expr)E, const void* (&i)
  Expr* ValuePrinterSynthesizer::SynthesizeVP(Expr* E) {
    QualType QT = E->getType();
    // For now we skip void and function pointer types.
    if (!QT.isNull() && (QT->isVoidType() || QT->isFunctionType()))
      return 0;

    // Find cling_PrintValue
    SourceLocation NoSLoc = SourceLocation();
    DeclarationName PVName = &m_Context->Idents.get("cling_PrintValue");
    LookupResult R(*m_Sema, PVName, NoSLoc, Sema::LookupOrdinaryName,
                   Sema::ForRedeclaration);

    Scope* S = m_Sema->getScopeForContext(m_Sema->CurContext);
    m_Sema->LookupName(R, S);
    assert(!R.empty() && "Cannot find PrintValue(...)");

    CXXScopeSpec CSS;
    Expr* UnresolvedLookup
      = m_Sema->BuildDeclarationNameExpr(CSS, R, /*ADL*/ false).take();

    Expr* VoidEArg = Synthesize::CStyleCastPtrExpr(m_Sema, m_Context->VoidPtrTy,
                                                   (uint64_t)E);
    Expr* VoidCArg = Synthesize::CStyleCastPtrExpr(m_Sema, m_Context->VoidPtrTy,
                                                   (uint64_t)m_Context);

    if (!QT->isPointerType()) {
      while(ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(E))
        E = ICE->getSubExpr();
      E = m_Sema->BuildUnaryOp(S, NoSLoc, UO_AddrOf, E).take();
    }

    ASTOwningVector<Expr*> CallArgs(*m_Sema);
    CallArgs.push_back(VoidEArg);
    CallArgs.push_back(VoidCArg);
    CallArgs.push_back(E);

    Expr* Result = m_Sema->ActOnCallExpr(S, UnresolvedLookup, NoSLoc,
                                         move_arg(CallArgs), NoSLoc).take();
    assert(Result && "Cannot create value printer!");

    return Result;
  }

  unsigned ValuePrinterSynthesizer::ClearNullStmts(CompoundStmt* CS) {
    llvm::SmallVector<Stmt*, 8> FBody;
    for (StmtRange range = CS->children(); range; ++range)
      if (!isa<NullStmt>(*range))
        FBody.push_back(*range);

    CS->setStmts(*m_Context, FBody.data(), FBody.size());
    return FBody.size();
  }

} // namespace cling
<|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2011
  \file      rdortp.cpp
  \authors
  \authors     (rdo@rk9.bmstu.ru)
  \date
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "simulator/compiler/parser/pch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/compiler/parser/rdortp.h"
#include "simulator/compiler/parser/rdoparser.h"
#include "simulator/compiler/parser/rdoparser_lexer.h"
#include "simulator/runtime/rdocalc.h"
// --------------------------------------------------------------------------------

OPEN_RDO_PARSER_NAMESPACE

int rtplex(PTR(YYSTYPE) lpval, PTR(YYLTYPE) llocp, PTR(void) lexer)
{
	LEXER->m_lpval = lpval;
	LEXER->m_lploc = llocp;
	return LEXER->yylex();
}

void rtperror(PTR(char) message)
{
	UNUSED(message);
}

// --------------------------------------------------------------------------------
// -------------------- RDORTPResType
// --------------------------------------------------------------------------------
RDORTPResType::RDORTPResType(CREF(LPRDOParser) pParser, CREF(RDOParserSrcInfo) src_info, rbool permanent)
	: RDOParserSrcInfo(src_info            )
	, m_number        (pParser->getRTP_id())
	, m_permanent     (permanent           )
{
	pParser->insertRTPResType(LPRDORTPResType(this));
}

RDORTPResType::~RDORTPResType()
{}

LPRDORSSResource RDORTPResType::createRes(CREF(LPRDOParser) pParser, CREF(RDOParserSrcInfo) src_info)
{
	return rdo::Factory<RDORSSResource>::create(pParser, src_info, this);
}

void RDORTPResType::addParam(CREF(LPRDORTPParam) param)
{
	if (findRTPParam(param->name()))
	{
		RDOParser::s_parser()->error().error(param->src_info(), rdo::format("  : %s", param->name().c_str()));
	}
	m_params.push_back(param);
}

void RDORTPResType::addParam(CREF(tstring) param_name, rdoRuntime::RDOType::TypeID param_typeID)
{
	UNUSED(param_name  );
	UNUSED(param_typeID);
}

LPRDORTPParam RDORTPResType::findRTPParam(CREF(tstring) paramName) const
{
	ParamList::const_iterator it = std::find_if(m_params.begin(), m_params.end(), compareName<RDORTPParam>(paramName));
	return it != m_params.end() ? *it : LPRDORTPParam();
}

ruint RDORTPResType::getRTPParamNumber(CREF(tstring) paramName) const
{
	ParamList::const_iterator it = std::find_if(m_params.begin(), m_params.end(), compareName<RDORTPParam>(paramName));
	return it != m_params.end() ? it - m_params.begin() : UNDEFINED_PARAM;
}

void RDORTPResType::writeModelStructure(REF(std::ostream) stream) const
{
	stream << getNumber() << " " << name() << " " << getParams().size() << std::endl;
	for (ruint i = 0; i < getParams().size(); i++)
	{
		stream << "  " << (i+1) << " ";
		getParams().at(i)->writeModelStructure(stream);
	}
}

tstring RDORTPResType::name() const
{
	static tstring s_name;
	s_name = src_text();
	return s_name;
}

LPRDOType RDORTPResType::type_cast(CREF(LPRDOType) from, CREF(RDOParserSrcInfo) from_src_info, CREF(RDOParserSrcInfo) to_src_info, CREF(RDOParserSrcInfo) src_info) const
{
	UNUSED(from_src_info);

	switch (from->typeID())
	{
	case rdoRuntime::RDOType::t_pointer:
		{
			LPRDOType pThisRTPType(const_cast<PTR(RDORTPResType)>(this));
			//!
			if (pThisRTPType == from)
				return pThisRTPType;
			//!  ,
			rdoParse::g_error().push_only(src_info,     _T("  "));
			rdoParse::g_error().push_only(to_src_info,   to_src_info.src_text());
			rdoParse::g_error().push_done();
			break;
		}
	default:
		{
			rdoParse::g_error().push_only(src_info,    rdo::format(_T("  , : %s"), from_src_info.src_text().c_str()));
			rdoParse::g_error().push_only(to_src_info, rdo::format(_T(". : %s"), to_src_info.src_text().c_str()));
			rdoParse::g_error().push_done();
			break;
		}
	}
	return NULL;
}

LPRDOValue RDORTPResType::value_cast(CREF(LPRDOValue) pFrom, CREF(RDOParserSrcInfo) to_src_info, CREF(RDOParserSrcInfo) src_info) const
{
	ASSERT(pFrom);

	LPRDORTPResType pRTPResType = pFrom->typeInfo()->type().object_dynamic_cast<RDORTPResType>();

	LPRDOType pFromType = pFrom->typeInfo()->type();
	LPRDOType pThisType = const_cast<PTR(RDORTPResType)>(this);
	if (pRTPResType)
	{
			//!
			if (pFromType == pThisType)
				return pFrom;
			//!  ,
			rdoParse::g_error().push_only(src_info,     _T("  "));
			rdoParse::g_error().push_only(to_src_info,   to_src_info.src_text());
			rdoParse::g_error().push_done();
	}
	rdoParse::g_error().push_only(src_info,    rdo::format(_T(" , : %s"), pFrom->src_text().c_str()));
	rdoParse::g_error().push_only(to_src_info, rdo::format(_T(". : %s"), to_src_info.src_text().c_str()));
	rdoParse::g_error().push_done();

	return NULL;
}

rdoRuntime::LPRDOCalc RDORTPResType::calc_cast(CREF(rdoRuntime::LPRDOCalc) pCalc, CREF(LPRDOType) pType) const
{
	return RDOType::calc_cast(pCalc, pType);
}

rdoRuntime::RDOValue RDORTPResType::get_default() const
{
	return rdoRuntime::RDOValue();
	//return rdoRuntime::RDOValue (pResourceType,pResource);
}

/*
// --------------------------------------------------------------------------------
// -------------------- RDORTPFuzzyMembershiftFun - -
// --------------------------------------------------------------------------------
RDORTPFuzzyMembershiftFun::RDORTPFuzzyMembershiftFun(CREF(LPRDOParser) pParser):
	RDOParserObject(pParser)
{
/*	for (ruint i = 0; i < m_points.size(); i++)
	{
//		double x = m_points[i]->getX();
	}

	Items::iterator it = m_points.begin();
	while (it != m_points.end())
	{
		double x = (*it)->getX();
		it++;
	}
}
// --------------------------------------------------------------------------------
// -------------------- RDORTPFuzzyTerm -
// --------------------------------------------------------------------------------
RDORTPFuzzyTerm::RDORTPFuzzyTerm(CREF(LPRDOParser) pParser, CREF(RDOParserSrcInfo) src_info, PTR(RDORTPFuzzyMembershiftFun) pMembersfift_fun):
	RDOParserObject(pParser)
{

}*/

CLOSE_RDO_PARSER_NAMESPACE
<commit_msg> - форматирование<commit_after>/*!
  \copyright (c) RDO-Team, 2011
  \file      rdortp.cpp
  \authors
  \authors     (rdo@rk9.bmstu.ru)
  \date
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "simulator/compiler/parser/pch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/compiler/parser/rdortp.h"
#include "simulator/compiler/parser/rdoparser.h"
#include "simulator/compiler/parser/rdoparser_lexer.h"
#include "simulator/runtime/rdocalc.h"
// --------------------------------------------------------------------------------

OPEN_RDO_PARSER_NAMESPACE

int rtplex(PTR(YYSTYPE) lpval, PTR(YYLTYPE) llocp, PTR(void) lexer)
{
	LEXER->m_lpval = lpval;
	LEXER->m_lploc = llocp;
	return LEXER->yylex();
}

void rtperror(PTR(char) message)
{
	UNUSED(message);
}

// --------------------------------------------------------------------------------
// -------------------- RDORTPResType
// --------------------------------------------------------------------------------
RDORTPResType::RDORTPResType(CREF(LPRDOParser) pParser, CREF(RDOParserSrcInfo) src_info, rbool permanent)
	: RDOParserSrcInfo(src_info            )
	, m_number        (pParser->getRTP_id())
	, m_permanent     (permanent           )
{
	pParser->insertRTPResType(LPRDORTPResType(this));
}

RDORTPResType::~RDORTPResType()
{}

LPRDORSSResource RDORTPResType::createRes(CREF(LPRDOParser) pParser, CREF(RDOParserSrcInfo) src_info)
{
	return rdo::Factory<RDORSSResource>::create(pParser, src_info, this);
}

void RDORTPResType::addParam(CREF(LPRDORTPParam) param)
{
	if (findRTPParam(param->name()))
	{
		RDOParser::s_parser()->error().error(param->src_info(), rdo::format("  : %s", param->name().c_str()));
	}
	m_params.push_back(param);
}

void RDORTPResType::addParam(CREF(tstring) param_name, rdoRuntime::RDOType::TypeID param_typeID)
{
	UNUSED(param_name  );
	UNUSED(param_typeID);
}

LPRDORTPParam RDORTPResType::findRTPParam(CREF(tstring) paramName) const
{
	ParamList::const_iterator it = std::find_if(m_params.begin(), m_params.end(), compareName<RDORTPParam>(paramName));
	return it != m_params.end() ? *it : LPRDORTPParam();
}

ruint RDORTPResType::getRTPParamNumber(CREF(tstring) paramName) const
{
	ParamList::const_iterator it = std::find_if(m_params.begin(), m_params.end(), compareName<RDORTPParam>(paramName));
	return it != m_params.end() ? it - m_params.begin() : UNDEFINED_PARAM;
}

void RDORTPResType::writeModelStructure(REF(std::ostream) stream) const
{
	stream << getNumber() << " " << name() << " " << getParams().size() << std::endl;
	for (ruint i = 0; i < getParams().size(); i++)
	{
		stream << "  " << (i+1) << " ";
		getParams().at(i)->writeModelStructure(stream);
	}
}

tstring RDORTPResType::name() const
{
	static tstring s_name;
	s_name = src_text();
	return s_name;
}

LPRDOType RDORTPResType::type_cast(CREF(LPRDOType) pFrom, CREF(RDOParserSrcInfo) from_src_info, CREF(RDOParserSrcInfo) to_src_info, CREF(RDOParserSrcInfo) src_info) const
{
	UNUSED(from_src_info);

	switch (pFrom->typeID())
	{
	case rdoRuntime::RDOType::t_pointer:
		{
			LPRDOType pThisRTPType(const_cast<PTR(RDORTPResType)>(this));

			//!
			if (pThisRTPType == pFrom)
				return pThisRTPType;

			//!  ,
			rdoParse::g_error().push_only(src_info,    _T("  "));
			rdoParse::g_error().push_only(to_src_info, to_src_info.src_text());
			rdoParse::g_error().push_done();
			break;
		}
	default:
		{
			rdoParse::g_error().push_only(src_info,    rdo::format(_T("  , : %s"), from_src_info.src_text().c_str()));
			rdoParse::g_error().push_only(to_src_info, rdo::format(_T(". : %s"), to_src_info.src_text().c_str()));
			rdoParse::g_error().push_done();
			break;
		}
	}

	return LPRDOType(NULL);
}

LPRDOValue RDORTPResType::value_cast(CREF(LPRDOValue) pFrom, CREF(RDOParserSrcInfo) to_src_info, CREF(RDOParserSrcInfo) src_info) const
{
	ASSERT(pFrom);

	LPRDORTPResType pRTPResType = pFrom->typeInfo()->type().object_dynamic_cast<RDORTPResType>();

	LPRDOType pFromType = pFrom->typeInfo()->type();
	LPRDOType pThisType = const_cast<PTR(RDORTPResType)>(this);
	if (pRTPResType)
	{
		//!
		if (pFromType == pThisType)
			return pFrom;

		//!  ,
		rdoParse::g_error().push_only(src_info,    _T("  "));
		rdoParse::g_error().push_only(to_src_info, to_src_info.src_text());
		rdoParse::g_error().push_done();
	}
	rdoParse::g_error().push_only(src_info,    rdo::format(_T(" , : %s"), pFrom->src_text().c_str()));
	rdoParse::g_error().push_only(to_src_info, rdo::format(_T(". : %s"), to_src_info.src_text().c_str()));
	rdoParse::g_error().push_done();

	return LPRDOValue(NULL);
}

rdoRuntime::LPRDOCalc RDORTPResType::calc_cast(CREF(rdoRuntime::LPRDOCalc) pCalc, CREF(LPRDOType) pType) const
{
	return RDOType::calc_cast(pCalc, pType);
}

rdoRuntime::RDOValue RDORTPResType::get_default() const
{
	return rdoRuntime::RDOValue();
	//return rdoRuntime::RDOValue (pResourceType,pResource);
}

/*
// --------------------------------------------------------------------------------
// -------------------- RDORTPFuzzyMembershiftFun - -
// --------------------------------------------------------------------------------
RDORTPFuzzyMembershiftFun::RDORTPFuzzyMembershiftFun(CREF(LPRDOParser) pParser):
	RDOParserObject(pParser)
{
/*	for (ruint i = 0; i < m_points.size(); i++)
	{
//		double x = m_points[i]->getX();
	}

	Items::iterator it = m_points.begin();
	while (it != m_points.end())
	{
		double x = (*it)->getX();
		it++;
	}
}
// --------------------------------------------------------------------------------
// -------------------- RDORTPFuzzyTerm -
// --------------------------------------------------------------------------------
RDORTPFuzzyTerm::RDORTPFuzzyTerm(CREF(LPRDOParser) pParser, CREF(RDOParserSrcInfo) src_info, PTR(RDORTPFuzzyMembershiftFun) pMembersfift_fun):
	RDOParserObject(pParser)
{

}*/

CLOSE_RDO_PARSER_NAMESPACE
<|endoftext|>


<commit_before>#include "allocore/al_Allocore.hpp"
#include "allocore/graphics/al_Isosurface.hpp"
#include "alloutil/al_ControlNav.hpp"

using namespace al;

GraphicsGL gl;
Light light;
Material material;
Camera cam;
Nav nav;
Stereographic stereo;

const int N = 32;
float volData[N*N*N];
Isosurface iso;
double phase=0;

void drawbox() {
	gl.begin(gl.LINES);
	gl.color(1,1,1);
	for (int z=-1; z<=1; z+=2) {
		for (int y=-1; y<=1; y+=2) {
			for (int x=-1; x<=1; x+=2) {
				gl.vertex(x, y, z);
			}
		}
		for (int y=-1; y<=1; y+=2) {
			for (int x=-1; x<=1; x+=2) {
				gl.vertex(y, x, z);
			}
		}
		for (int y=-1; y<=1; y+=2) {
			for (int x=-1; x<=1; x+=2) {
				gl.vertex(y, z, x);
			}
		}
	}
	gl.end();
}

struct MyWindow : public Window, public Drawable{

	void onDraw(Graphics& gl){
		gl.depthTesting(1);

		material.shininess(10)();
		light();

		iso.level(0);
		iso.generate(volData, N, 1./N);

		gl.pushMatrix(gl.MODELVIEW);
			glEnable(GL_RESCALE_NORMAL);
			gl.translate(-1,-1,-1);
			gl.scale(2);
			iso.color(0.6,0.6,0.6);
			gl.draw(iso);
		gl.popMatrix();

		drawbox();
	}

	bool onFrame(){
		nav.smooth(0.8);
		nav.step(1.);
		stereo.draw(gl, cam, nav, Viewport(width(), height()), *this);

		if((phase += 0.0005) > 2*M_PI) phase -= 2*M_PI;

		static bool once = false;

		if(!once){ once = true;
		for(int k=0; k<N; ++k){ double z = double(k)/N * 4*M_PI;
		for(int j=0; j<N; ++j){ double y = double(j)/N * 4*M_PI;
		for(int i=0; i<N; ++i){ double x = double(i)/N * 4*M_PI;

			volData[k*N*N + j*N + i]
				= cos(x * cos(phase*7))
				+ cos(y * cos(phase*8))
				+ cos(z * cos(phase*9));
		}}}
		}

		return true;
	}
};

int main (int argc, char * argv[]){

	iso.primitive(Graphics::TRIANGLES);

	nav.pos(0,0,-5);

	MyWindow win;
	win.create(Window::Dim(800,600), "Isosurface Example", 140);

	win.add(new StandardWindowKeyControls);
	win.add(new NavInputControl(nav));

	Window::startLoop();
	return 0;
}
<commit_msg>example isosurface simplifications<commit_after>#include "allocore/al_Allocore.hpp"
#include "allocore/graphics/al_Isosurface.hpp"
#include "alloutil/al_ControlNav.hpp"

using namespace al;

GraphicsGL gl;
Light light;
Camera cam;
Nav nav(Vec3d(0,0,-5));
Stereographic stereo;

const int N = 32;
float volData[N*N*N];
Isosurface iso;
double phase=0;

struct MyWindow : public Window, public Drawable{

	void onDraw(Graphics& gl){
		gl.depthTesting(1);

		gl.enable(gl.COLOR_MATERIAL);
		light();

		iso.level(0);
		iso.generate(volData, N, 1./N);

		gl.pushMatrix(gl.MODELVIEW);
			glEnable(GL_RESCALE_NORMAL);
			gl.translate(-1,-1,-1);
			gl.scale(2);
			iso.color(0.6,0.6,0.6);
			gl.draw(iso);
		gl.popMatrix();

		gl.mesh().primitive(gl.LINES).reset();
		addWireBox(gl.mesh());
		gl.draw();
	}

	bool onFrame(){
		nav.smooth(0.8);
		nav.step(1.);
		stereo.draw(gl, cam, nav, Viewport(width(), height()), *this);

		if((phase += 0.0005) > 2*M_PI) phase -= 2*M_PI;

		static bool once = false;

		if(!once){ //once = true;
		for(int k=0; k<N; ++k){ double z = double(k)/N * 4*M_PI;
		for(int j=0; j<N; ++j){ double y = double(j)/N * 4*M_PI;
		for(int i=0; i<N; ++i){ double x = double(i)/N * 4*M_PI;

			volData[k*N*N + j*N + i]
				= cos(x * cos(phase*7))
				+ cos(y * cos(phase*8))
				+ cos(z * cos(phase*9));
		}}}
		}

		return true;
	}
};

int main(){
	iso.primitive(Graphics::TRIANGLES);

	MyWindow win;
	win.create(Window::Dim(800,600), "Isosurface Example", 140);

	win.add(new StandardWindowKeyControls);
	win.add(new NavInputControl(nav));

	Window::startLoop();
	return 0;
}
<|endoftext|>


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

#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <stdio.h>
#include <stdexcept>
#include "xmltopologyreader.h"

bool XMLTopologyReader::ReadTopology(string filename, Topology &top)
{
  _top = ⊤

  _parser.NextHandler(this, &XMLTopologyReader::ParseRoot);
  _parser.Open(filename);

  return true;
}

void XMLTopologyReader::ReadTopolFile(string file)
{
    TopologyReader *reader;
    reader = TopReaderFactory().Create(file);
    if(!reader)
        throw runtime_error(file + ": unknown topology format");

    reader->ReadTopology(file, *_top);

    delete reader;
}

void XMLTopologyReader::ParseRoot(const string &el, map<string, string> &attr)
{
    if(el == "topology") {
        if(attr["base"] != "")
            ReadTopolFile(attr["base"]);
        _parser.NextHandler(this, &XMLTopologyReader::ParseTopology);
    }
    else {
        throw std::runtime_error("wrong root node in xml topology file");
    }
}

void XMLTopologyReader::ParseTopology(const string &el, map<string, string> &attr)
{
    if(el == "molecules")
         _parser.NextHandler(this, &XMLTopologyReader::ParseMolecules);
}

void XMLTopologyReader::ParseMolecules(const string &el, map<string, string> &attr)
{
    map<string, string>::iterator iter;
    if (el == "clear") {
        _top->ClearMoleculeList();
        _parser.IgnoreChilds();
    }
    else if (el == "rename") {
        string molname = attr["name"];
        string range = attr["range"];
        if (molname == "" || range == "")
            throw runtime_error("invalid rename tag");
        _top->RenameMolecules(range, molname);
        _parser.IgnoreChilds();
    }
    if (el == "define") {
        string molname = attr["name"];
        string first = attr["first"];
        string nbeads = attr["nbeads"];
        string nmols = attr["nmols"];
        if (molname == "" && first == "" && nbeads == "" && nmols == "")
            throw runtime_error("invalid define tag");
        _top->CreateMoleculesByRange(molname,
                boost::lexical_cast<int>(first),
                boost::lexical_cast<int>(nbeads),
                boost::lexical_cast<int>(nmols));
        _parser.IgnoreChilds();
    }
}<commit_msg>xmltopologyreader.cc: new line at end of file<commit_after>/*
 * Copyright 2009 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <stdio.h>
#include <stdexcept>
#include "xmltopologyreader.h"

bool XMLTopologyReader::ReadTopology(string filename, Topology &top)
{
  _top = ⊤

  _parser.NextHandler(this, &XMLTopologyReader::ParseRoot);
  _parser.Open(filename);

  return true;
}

void XMLTopologyReader::ReadTopolFile(string file)
{
    TopologyReader *reader;
    reader = TopReaderFactory().Create(file);
    if(!reader)
        throw runtime_error(file + ": unknown topology format");

    reader->ReadTopology(file, *_top);

    delete reader;
}

void XMLTopologyReader::ParseRoot(const string &el, map<string, string> &attr)
{
    if(el == "topology") {
        if(attr["base"] != "")
            ReadTopolFile(attr["base"]);
        _parser.NextHandler(this, &XMLTopologyReader::ParseTopology);
    }
    else {
        throw std::runtime_error("wrong root node in xml topology file");
    }
}

void XMLTopologyReader::ParseTopology(const string &el, map<string, string> &attr)
{
    if(el == "molecules")
         _parser.NextHandler(this, &XMLTopologyReader::ParseMolecules);
}

void XMLTopologyReader::ParseMolecules(const string &el, map<string, string> &attr)
{
    map<string, string>::iterator iter;
    if (el == "clear") {
        _top->ClearMoleculeList();
        _parser.IgnoreChilds();
    }
    else if (el == "rename") {
        string molname = attr["name"];
        string range = attr["range"];
        if (molname == "" || range == "")
            throw runtime_error("invalid rename tag");
        _top->RenameMolecules(range, molname);
        _parser.IgnoreChilds();
    }
    if (el == "define") {
        string molname = attr["name"];
        string first = attr["first"];
        string nbeads = attr["nbeads"];
        string nmols = attr["nmols"];
        if (molname == "" && first == "" && nbeads == "" && nmols == "")
            throw runtime_error("invalid define tag");
        _top->CreateMoleculesByRange(molname,
                boost::lexical_cast<int>(first),
                boost::lexical_cast<int>(nbeads),
                boost::lexical_cast<int>(nmols));
        _parser.IgnoreChilds();
    }
}
<|endoftext|>


<commit_before>#include <sys/resource.h>

#include <map>

#include <QApplication>
#include <QString>
#include <QSoundEffect>

#include "cereal/messaging/messaging.h"
#include "selfdrive/common/util.h"
#include "selfdrive/hardware/hw.h"
#include "selfdrive/ui/ui.h"

// TODO: detect when we can't play sounds
// TODO: detect when we can't display the UI

class Sound : public QObject {
public:
  explicit Sound(QObject *parent = 0) {
    // TODO: merge again and add EQ in the amp config
    const QString sound_asset_path = Hardware::TICI ? "../assets/sounds_tici/" : "../assets/sounds/";
    std::tuple<AudibleAlert, QString, bool> sound_list[] = {
      {AudibleAlert::CHIME_DISENGAGE, sound_asset_path + "disengaged.wav", false},
      {AudibleAlert::CHIME_ENGAGE, sound_asset_path + "engaged.wav", false},
      {AudibleAlert::CHIME_WARNING1, sound_asset_path + "warning_1.wav", false},
      {AudibleAlert::CHIME_WARNING2, sound_asset_path + "warning_2.wav", false},
      {AudibleAlert::CHIME_WARNING2_REPEAT, sound_asset_path + "warning_2.wav", true},
      {AudibleAlert::CHIME_WARNING_REPEAT, sound_asset_path + "warning_repeat.wav", true},
      {AudibleAlert::CHIME_ERROR, sound_asset_path + "error.wav", false},
      {AudibleAlert::CHIME_PROMPT, sound_asset_path + "error.wav", false}
    };
    for (auto &[alert, fn, loops] : sound_list) {
      sounds[alert].first.setSource(QUrl::fromLocalFile(fn));
      sounds[alert].second = loops ? QSoundEffect::Infinite : 0;
      QObject::connect(&sounds[alert].first, &QSoundEffect::statusChanged, this, &Sound::checkStatus);
    }

    sm = new SubMaster({"carState", "controlsState"});

    QTimer *timer = new QTimer(this);
    QObject::connect(timer, &QTimer::timeout, this, &Sound::update);
    timer->start();
  };
  ~Sound() {
    delete sm;
  };

private slots:
  void checkStatus() {
    for (auto &[alert, kv] : sounds) {
      assert(kv.first.status() != QSoundEffect::Error);
    }
  }

  void update() {
    sm->update(100);
    if (sm->updated("carState")) {
      // scale volume with speed
      volume = util::map_val((*sm)["carState"].getCarState().getVEgo(), 0.f, 20.f,
                             Hardware::MIN_VOLUME, Hardware::MAX_VOLUME);
    }
    if (sm->updated("controlsState")) {
      const cereal::ControlsState::Reader &cs = (*sm)["controlsState"].getControlsState();
      setAlert({QString::fromStdString(cs.getAlertText1()),
                QString::fromStdString(cs.getAlertText2()),
                QString::fromStdString(cs.getAlertType()),
                cs.getAlertSize(), cs.getAlertSound()});
    } else if (sm->rcv_frame("controlsState") > 0 && (*sm)["controlsState"].getControlsState().getEnabled() &&
               ((nanos_since_boot() - sm->rcv_time("controlsState")) / 1e9 > CONTROLS_TIMEOUT)) {
      setAlert(CONTROLS_UNRESPONSIVE_ALERT);
    }
  }

  void setAlert(Alert a) {
    if (!alert.equal(a)) {
      alert = a;
      // stop sounds
      for (auto &kv : sounds) {
        // Only stop repeating sounds
        auto &[sound, loops] = kv.second;
        if (sound.loopsRemaining() == QSoundEffect::Infinite) {
          sound.stop();
        }
      }

      // play sound
      if (alert.sound != AudibleAlert::NONE) {
        auto &[sound, loops] = sounds[alert.sound];
        sound.setLoopCount(loops);
        sound.setVolume(volume);
        sound.play();
      }
    }
  }

private:
  Alert alert;
  float volume = Hardware::MIN_VOLUME;
  std::map<AudibleAlert, std::pair<QSoundEffect, int>> sounds;
  SubMaster *sm;
};

int main(int argc, char **argv) {
  setpriority(PRIO_PROCESS, 0, -20);

  QApplication a(argc, argv);
  Sound sound;
  return a.exec();
}
<commit_msg>soundd: fix path to sound files (#21801)<commit_after>#include <sys/resource.h>

#include <map>

#include <QApplication>
#include <QString>
#include <QSoundEffect>

#include "cereal/messaging/messaging.h"
#include "selfdrive/common/util.h"
#include "selfdrive/hardware/hw.h"
#include "selfdrive/ui/ui.h"

// TODO: detect when we can't play sounds
// TODO: detect when we can't display the UI

class Sound : public QObject {
public:
  explicit Sound(QObject *parent = 0) {
    // TODO: merge again and add EQ in the amp config
    const QString sound_asset_path = Hardware::TICI() ? "../assets/sounds_tici/" : "../assets/sounds/";
    std::tuple<AudibleAlert, QString, bool> sound_list[] = {
      {AudibleAlert::CHIME_DISENGAGE, sound_asset_path + "disengaged.wav", false},
      {AudibleAlert::CHIME_ENGAGE, sound_asset_path + "engaged.wav", false},
      {AudibleAlert::CHIME_WARNING1, sound_asset_path + "warning_1.wav", false},
      {AudibleAlert::CHIME_WARNING2, sound_asset_path + "warning_2.wav", false},
      {AudibleAlert::CHIME_WARNING2_REPEAT, sound_asset_path + "warning_2.wav", true},
      {AudibleAlert::CHIME_WARNING_REPEAT, sound_asset_path + "warning_repeat.wav", true},
      {AudibleAlert::CHIME_ERROR, sound_asset_path + "error.wav", false},
      {AudibleAlert::CHIME_PROMPT, sound_asset_path + "error.wav", false}
    };
    for (auto &[alert, fn, loops] : sound_list) {
      QSoundEffect *s = new QSoundEffect(this);
      QObject::connect(s, &QSoundEffect::statusChanged, this, &Sound::checkStatus);
      s->setSource(QUrl::fromLocalFile(fn));
      sounds[alert] = {s, loops ? QSoundEffect::Infinite : 0};
    }

    sm = new SubMaster({"carState", "controlsState"});

    QTimer *timer = new QTimer(this);
    QObject::connect(timer, &QTimer::timeout, this, &Sound::update);
    timer->start();
  };
  ~Sound() {
    delete sm;
  };

private slots:
  void checkStatus() {
    QSoundEffect *s = qobject_cast<QSoundEffect*>(sender());
    assert(s->status() != QSoundEffect::Error);
  }

  void update() {
    sm->update(100);
    if (sm->updated("carState")) {
      // scale volume with speed
      volume = util::map_val((*sm)["carState"].getCarState().getVEgo(), 0.f, 20.f,
                             Hardware::MIN_VOLUME, Hardware::MAX_VOLUME);
    }
    if (sm->updated("controlsState")) {
      const cereal::ControlsState::Reader &cs = (*sm)["controlsState"].getControlsState();
      setAlert({QString::fromStdString(cs.getAlertText1()),
                QString::fromStdString(cs.getAlertText2()),
                QString::fromStdString(cs.getAlertType()),
                cs.getAlertSize(), cs.getAlertSound()});
    } else if (sm->rcv_frame("controlsState") > 0 && (*sm)["controlsState"].getControlsState().getEnabled() &&
               ((nanos_since_boot() - sm->rcv_time("controlsState")) / 1e9 > CONTROLS_TIMEOUT)) {
      setAlert(CONTROLS_UNRESPONSIVE_ALERT);
    }
  }

  void setAlert(Alert a) {
    if (!alert.equal(a)) {
      alert = a;
      // stop sounds
      for (auto &[s, loops] : sounds) {
        // Only stop repeating sounds
        if (s->loopsRemaining() == QSoundEffect::Infinite) {
          s->stop();
        }
      }

      // play sound
      if (alert.sound != AudibleAlert::NONE) {
        auto &[s, loops] = sounds[alert.sound];
        s->setLoopCount(loops);
        s->setVolume(volume);
        s->play();
      }
    }
  }

private:
  Alert alert;
  float volume = Hardware::MIN_VOLUME;
  QMap<AudibleAlert, QPair<QSoundEffect*, int>> sounds;
  SubMaster *sm;
};

int main(int argc, char **argv) {
  setpriority(PRIO_PROCESS, 0, -20);

  QApplication a(argc, argv);
  Sound sound;
  return a.exec();
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2020.  All rights reserved
 */
#include "../StroikaPreComp.h"

#include "../Debug/Demangle.h"
#include "../Execution/Exceptions.h"

#include "String_Constant.h"

#include "ToString.h"

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;

/*
 ********************************************************************************
 ************************************* ToString *********************************
 ********************************************************************************
 */
namespace Stroika::Foundation::Characters {
    template <>
    String ToString (const exception_ptr& e)
    {
        static const String kExceptPefix_{L"Exception: "sv};
        static const String kUnknown_{L"Unknown Exception"sv};
        try {
            rethrow_exception (e);
        }
        catch (const Execution::ExceptionStringHelper& e) {
            //saying Exception: first produces 'Exception: HTTP exception: status 404 (URL not found)}' - redundant. Not sure about all cases, but try this way.
            //return kExceptPefix_ + e.As<String> ();
            return e.As<String> ();
        }
        catch (const exception& e) {
            return kExceptPefix_ + String::FromNarrowSDKString (e.what ());
        }
        catch (...) {
            // fall through
        }
        return kUnknown_;
    }
    template <>
    String ToString (const type_info& t)
    {
        //nb: demangle needed for gcc, but not msvc (but harmless there)
        return Debug::Demangle (String::FromNarrowSDKString (t.name ()));
    }
    template <>
    String ToString (const type_index& t)
    {
        //nb: demangle needed for gcc, but not msvc (but harmless there)
        return Debug::Demangle (String::FromNarrowSDKString (t.name ()));
    }

    String ToString (const char* t)
    {
        // No way to know the 'right' characterset in this case, but as this is mostly used for debugging, no biggie. The caller
        // can be more careful if he cares about charset. This should be safe, and mostly helpful
        return String::FromISOLatin1 (t);
    }

    template <>
    String ToString (const bool& t)
    {
        static const String kTrue_{L"true"sv};
        static const String kFalse{L"false"sv};
        return t ? kTrue_ : kFalse;
    }

    namespace {
        template <typename T>
        inline String num2Str_ (T t, std::ios_base::fmtflags flags)
        {
            static_assert (sizeof (t) <= sizeof (int));
            wchar_t buf[1024];
            switch (flags) {
                case std::ios_base::dec:
                    (void)::swprintf (buf, NEltsOf (buf), L"%d", t);
                    break;
                case std::ios_base::hex:
                    (void)::swprintf (buf, NEltsOf (buf), L"0x%x", t);
                    break;
                default:
                    AssertNotReached ();    // @todo support octal
            }
            return buf;
        }
        template <typename T>
        inline String num2Strl_ (T t, std::ios_base::fmtflags flags)
        {
            wchar_t buf[1024];
            static_assert (sizeof (t) == sizeof (long int));
            switch (flags) {
                case std::ios_base::dec:
                    (void)::swprintf (buf, NEltsOf (buf), L"%ld", t);
                    break;
                case std::ios_base::hex:
                    (void)::swprintf (buf, NEltsOf (buf), L"0x%lx", t);
                    break;
                default:
                    AssertNotReached (); // @todo support octal
            }
            return buf;
        }
        template <typename T>
        inline String num2Strll_ (T t, std::ios_base::fmtflags flags)
        {
            wchar_t buf[1024];
            static_assert (sizeof (t) == sizeof (long long int));
            switch (flags) {
                case std::ios_base::dec:
                    (void)::swprintf (buf, NEltsOf (buf), L"%lld", t);
                    break;
                case std::ios_base::hex:
                    (void)::swprintf (buf, NEltsOf (buf), L"0x%llx", t);
                    break;
                default:
                    AssertNotReached (); // @todo support octal
            }
            return buf;
        }
    }

    template <>
    String ToString (const signed char t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const short int t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const int t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const long int t, std::ios_base::fmtflags flags)
    {
        return num2Strl_ (t, flags);
    }
    template <>
    String ToString (const long long int t, std::ios_base::fmtflags flags)
    {
        return num2Strll_ (t, flags);
    }
    template <>
    String ToString (const unsigned char t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const unsigned short t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const unsigned int t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const unsigned long t, std::ios_base::fmtflags flags)
    {
        return num2Strl_ (t, flags);
    }
    template <>
    String ToString (const unsigned long long t, std::ios_base::fmtflags flags)
    {
        return num2Strll_ (t, flags);
    }

    namespace Private_ {
        String ToString_ex_ (const std::exception& t)
        {
            if (auto p = dynamic_cast<const Execution::ExceptionStringHelper*> (&t)) {
                return p->As<String> ();
            }
            //saying Exception: first produces 'Exception: HTTP exception: status 404 (URL not found)}' - redundant. Not sure about all cases, but try this way.
            //return String_Constant {L"Exception: " } + String::FromNarrowSDKString (t.what ()) + String_Constant {L"}" };
            return String::FromNarrowSDKString (t.what ());
        }
    }
}
<commit_msg>cosmetic<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2020.  All rights reserved
 */
#include "../StroikaPreComp.h"

#include "../Debug/Demangle.h"
#include "../Execution/Exceptions.h"

#include "String_Constant.h"

#include "ToString.h"

using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Characters;

/*
 ********************************************************************************
 ************************************* ToString *********************************
 ********************************************************************************
 */
namespace Stroika::Foundation::Characters {
    template <>
    String ToString (const exception_ptr& e)
    {
        static const String kExceptPefix_{L"Exception: "sv};
        static const String kUnknown_{L"Unknown Exception"sv};
        try {
            rethrow_exception (e);
        }
        catch (const Execution::ExceptionStringHelper& e) {
            //saying Exception: first produces 'Exception: HTTP exception: status 404 (URL not found)}' - redundant. Not sure about all cases, but try this way.
            //return kExceptPefix_ + e.As<String> ();
            return e.As<String> ();
        }
        catch (const exception& e) {
            return kExceptPefix_ + String::FromNarrowSDKString (e.what ());
        }
        catch (...) {
            // fall through
        }
        return kUnknown_;
    }
    template <>
    String ToString (const type_info& t)
    {
        //nb: demangle needed for gcc, but not msvc (but harmless there)
        return Debug::Demangle (String::FromNarrowSDKString (t.name ()));
    }
    template <>
    String ToString (const type_index& t)
    {
        //nb: demangle needed for gcc, but not msvc (but harmless there)
        return Debug::Demangle (String::FromNarrowSDKString (t.name ()));
    }

    String ToString (const char* t)
    {
        // No way to know the 'right' characterset in this case, but as this is mostly used for debugging, no biggie. The caller
        // can be more careful if he cares about charset. This should be safe, and mostly helpful
        return String::FromISOLatin1 (t);
    }

    template <>
    String ToString (const bool& t)
    {
        static const String kTrue_{L"true"sv};
        static const String kFalse{L"false"sv};
        return t ? kTrue_ : kFalse;
    }

    namespace {
        template <typename T>
        inline String num2Str_ (T t, std::ios_base::fmtflags flags)
        {
            static_assert (sizeof (t) <= sizeof (int));
            wchar_t buf[1024];
            switch (flags) {
                case std::ios_base::dec:
                    (void)::swprintf (buf, NEltsOf (buf), L"%d", t);
                    break;
                case std::ios_base::hex:
                    (void)::swprintf (buf, NEltsOf (buf), L"0x%x", t);
                    break;
                default:
                    AssertNotReached (); // @todo support octal
            }
            return buf;
        }
        template <typename T>
        inline String num2Strl_ (T t, std::ios_base::fmtflags flags)
        {
            wchar_t buf[1024];
            static_assert (sizeof (t) == sizeof (long int));
            switch (flags) {
                case std::ios_base::dec:
                    (void)::swprintf (buf, NEltsOf (buf), L"%ld", t);
                    break;
                case std::ios_base::hex:
                    (void)::swprintf (buf, NEltsOf (buf), L"0x%lx", t);
                    break;
                default:
                    AssertNotReached (); // @todo support octal
            }
            return buf;
        }
        template <typename T>
        inline String num2Strll_ (T t, std::ios_base::fmtflags flags)
        {
            wchar_t buf[1024];
            static_assert (sizeof (t) == sizeof (long long int));
            switch (flags) {
                case std::ios_base::dec:
                    (void)::swprintf (buf, NEltsOf (buf), L"%lld", t);
                    break;
                case std::ios_base::hex:
                    (void)::swprintf (buf, NEltsOf (buf), L"0x%llx", t);
                    break;
                default:
                    AssertNotReached (); // @todo support octal
            }
            return buf;
        }
    }

    template <>
    String ToString (const signed char t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const short int t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const int t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const long int t, std::ios_base::fmtflags flags)
    {
        return num2Strl_ (t, flags);
    }
    template <>
    String ToString (const long long int t, std::ios_base::fmtflags flags)
    {
        return num2Strll_ (t, flags);
    }
    template <>
    String ToString (const unsigned char t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const unsigned short t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const unsigned int t, std::ios_base::fmtflags flags)
    {
        return num2Str_ (t, flags);
    }
    template <>
    String ToString (const unsigned long t, std::ios_base::fmtflags flags)
    {
        return num2Strl_ (t, flags);
    }
    template <>
    String ToString (const unsigned long long t, std::ios_base::fmtflags flags)
    {
        return num2Strll_ (t, flags);
    }

    namespace Private_ {
        String ToString_ex_ (const std::exception& t)
        {
            if (auto p = dynamic_cast<const Execution::ExceptionStringHelper*> (&t)) {
                return p->As<String> ();
            }
            //saying Exception: first produces 'Exception: HTTP exception: status 404 (URL not found)}' - redundant. Not sure about all cases, but try this way.
            //return String_Constant {L"Exception: " } + String::FromNarrowSDKString (t.what ()) + String_Constant {L"}" };
            return String::FromNarrowSDKString (t.what ());
        }
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 Timur Iskhodzhanov and MIPT students. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "gtest/gtest.h"

template<typename K, typename V>
class LruCache {
 public:
  explicit LruCache(int size) {}

  void Put(const K &key, const V &value) {}

  // Doesn't update timestamps.
  bool Contains(const K &key) const { return false; }

  // Updates timestamps.
  bool Lookup(const K &key, V *value) { return false; }

  bool LookupNoUpdate(const K &key, V *value) const { return false; }
};

TEST(LruCacheTests, /*DISABLED_*/Simple) {
  LruCache<int, int> lru(2);

  ASSERT_FALSE(lru.Contains(1));
  lru.Put(1 /* key */, 42 /* value */);
  ASSERT_TRUE(lru.Contains(1));
  int value = -1;
  ASSERT_TRUE(lru.Lookup(1, &value));
  ASSERT_EQ(42, value);

  lru.Put(13, 77);
  ASSERT_TRUE(lru.Contains(13));
  ASSERT_TRUE(lru.Contains(1));
}

TEST(LruCacheTests, DISABLED_Eviction) {
  LruCache<int, int> lru(2);
  lru.Put(1, 42);
  lru.Put(2, 13);
  ASSERT_TRUE(lru.Contains(1));
  ASSERT_TRUE(lru.Contains(2));

  lru.Put(3, 77);  // should evict '1'.
  ASSERT_FALSE(lru.Contains(1));
  ASSERT_TRUE(lru.Contains(2));
  ASSERT_TRUE(lru.Contains(3));

  lru.Put(2, 42);  // refreshes the timestamp of '2'
  ASSERT_TRUE(lru.Contains(2));
  int value = -1;
  ASSERT_TRUE(lru.LookupNoUpdate(2, &value));
  ASSERT_EQ(42, value);
  ASSERT_TRUE(lru.Contains(3));

  lru.Put(4, 99);  // should evict '3'.
  ASSERT_TRUE(lru.Contains(2));
  ASSERT_FALSE(lru.Contains(3));
  ASSERT_TRUE(lru.Contains(4));
}
<commit_msg>Fix it. Finally.<commit_after>// Copyright (c) 2011 Timur Iskhodzhanov and MIPT students. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "gtest/gtest.h"

template<typename K, typename V>
class LruCache {
 public:
  explicit LruCache(int size) {}

  void Put(const K &key, const V &value) {}

  // Doesn't update timestamps.
  bool Contains(const K &key) const { return false; }

  // Updates timestamps.
  bool Lookup(const K &key, V *value) { return false; }

  bool LookupNoUpdate(const K &key, V *value) const { return false; }
};

TEST(LruCacheTests, DISABLED_Simple) {
  LruCache<int, int> lru(2);

  ASSERT_FALSE(lru.Contains(1));
  lru.Put(1 /* key */, 42 /* value */);
  ASSERT_TRUE(lru.Contains(1));
  int value = -1;
  ASSERT_TRUE(lru.Lookup(1, &value));
  ASSERT_EQ(42, value);

  lru.Put(13, 77);
  ASSERT_TRUE(lru.Contains(13));
  ASSERT_TRUE(lru.Contains(1));
}

TEST(LruCacheTests, DISABLED_Eviction) {
  LruCache<int, int> lru(2);
  lru.Put(1, 42);
  lru.Put(2, 13);
  ASSERT_TRUE(lru.Contains(1));
  ASSERT_TRUE(lru.Contains(2));

  lru.Put(3, 77);  // should evict '1'.
  ASSERT_FALSE(lru.Contains(1));
  ASSERT_TRUE(lru.Contains(2));
  ASSERT_TRUE(lru.Contains(3));

  lru.Put(2, 42);  // refreshes the timestamp of '2'
  ASSERT_TRUE(lru.Contains(2));
  int value = -1;
  ASSERT_TRUE(lru.LookupNoUpdate(2, &value));
  ASSERT_EQ(42, value);
  ASSERT_TRUE(lru.Contains(3));

  lru.Put(4, 99);  // should evict '3'.
  ASSERT_TRUE(lru.Contains(2));
  ASSERT_FALSE(lru.Contains(3));
  ASSERT_TRUE(lru.Contains(4));
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2013.  All rights reserved
 */
#ifndef _Stroika_Foundation_Containers_Sequence_inl_
#define _Stroika_Foundation_Containers_Sequence_inl_

#include    "../Debug/Assertions.h"

#include    "Concrete/Sequence_Factory.h"
#include    "Private/IterableUtils.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   Containers {

            /*
             ********************************************************************************
             **************************** Sequence<T, TRAITS> *******************************
             ********************************************************************************
             */
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>::Sequence ()
                : inherited (Concrete::Sequence_Factory<T, TRAITS>::mk ())
            {
            }
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>::Sequence (const Sequence<T, TRAITS>& s)
                : inherited (static_cast<const inherited&> (s))
            {
            }
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>::Sequence (const initializer_list<T>& s)
                : inherited (Concrete::Sequence_Factory<T, TRAITS>::mk ())
            {
                AppendAll (s);
            }
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>::Sequence (const vector<T>& s)
                : inherited (Concrete::Sequence_Factory<T, TRAITS>::mk ())
            {
                AppendAll (s);
            }
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  Sequence<T, TRAITS>::Sequence (const CONTAINER_OF_T& s)
                : inherited (Concrete::Sequence_Factory<T, TRAITS>::mk ())
            {
                AppendAll (s);
            }
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>::Sequence (const _SharedPtrIRep& rep)
                : inherited (typename inherited::_SharedPtrIRep (rep))
            {
                RequireNotNull (rep);
            }
            template    <typename T, typename TRAITS>
            template    <typename COPY_FROM_ITERATOR_OF_T>
            inline Sequence<T, TRAITS>::Sequence (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
                : inherited (Concrete::Sequence_Factory<T, TRAITS>::mk ())
            {
                AppendAll (start, end);
            }
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>& Sequence<T, TRAITS>::operator= (const Sequence<T, TRAITS>& rhs)
            {
                inherited::operator= (rhs);
                return *this;
            }
            template    <typename T, typename TRAITS>
            inline  const typename  Sequence<T, TRAITS>::_IRep&    Sequence<T, TRAITS>::_GetRep () const
            {
                EnsureMember (&inherited::_GetRep (), _IRep);       // static_cast more efficient, but assert to verify safe
                return *static_cast<const _IRep*> (&inherited::_GetRep ());
            }
            template    <typename T, typename TRAITS>
            inline  typename    Sequence<T, TRAITS>::_IRep&  Sequence<T, TRAITS>::_GetRep ()
            {
                EnsureMember (&inherited::_GetRep (), _IRep);       // static_cast more efficient, but assert to verify safe
                return *static_cast<_IRep*> (&inherited::_GetRep ());
            }
            template    <typename T, typename TRAITS>
            inline  bool    Sequence<T, TRAITS>::Contains (T item) const
            {
                RequireConceptAppliesToTypeInFunction(Concept_EqualsCompareFunctionType, EqualsCompareFunctionType);
                return Private::Contains_<T, EqualsCompareFunctionType> (*this, item);
            }
            template    <typename T, typename TRAITS>
            template    <typename ELEMENT_COMPARER>
            inline  int    Sequence<T, TRAITS>::Compare (const Iterable<T>& rhs) const
            {
                return Private::Compare_<T, ELEMENT_COMPARER> (*this, rhs);
            }
            template    <typename T, typename TRAITS>
            inline  bool    Sequence<T, TRAITS>::Equals (const Sequence<T, TRAITS>& rhs) const
            {
                RequireConceptAppliesToTypeInFunction(Concept_EqualsCompareFunctionType, EqualsCompareFunctionType);
                return Private::Equals_<T, EqualsCompareFunctionType> (*this, rhs);
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::RemoveAll ()
            {
                _GetRep ().Remove (0, this->GetLength ());
            }
            template    <typename T, typename TRAITS>
            inline  T    Sequence<T, TRAITS>::GetAt (size_t i) const
            {
                Require (i < this->GetLength ());
                return _GetRep ().GetAt (i);
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::SetAt (size_t i, T item)
            {
                Require (i < this->GetLength ());
                _GetRep ().SetAt (i, item);
            }
            template    <typename T, typename TRAITS>
            inline  T    Sequence<T, TRAITS>::operator[] (size_t i) const
            {
                Require (i < this->GetLength ());
                return _GetRep ().GetAt (i);
            }
            template    <typename T, typename TRAITS>
            inline  size_t    Sequence<T, TRAITS>::IndexOf (T item) const
            {
                RequireConceptAppliesToTypeInFunction(Concept_EqualsCompareFunctionType, EqualsCompareFunctionType);
                return Private::IndexOf_<T, EqualsCompareFunctionType> (*this, item, kBadSequenceIndex);
            }
            template    <typename T, typename TRAITS>
            inline  size_t    Sequence<T, TRAITS>::IndexOf (const Sequence<T, TRAITS>& s) const
            {
                RequireConceptAppliesToTypeInFunction(Concept_EqualsCompareFunctionType, EqualsCompareFunctionType);
                return Private::IndexOf_<T, EqualsCompareFunctionType> (*this, s, kBadSequenceIndex);
            }
            template    <typename T, typename TRAITS>
            inline  size_t    Sequence<T, TRAITS>::IndexOf (const Iterator<T>& i) const
            {
                return _GetRep ().IndexOf (i);
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::Insert (size_t i, T item)
            {
                Require (i <= this->GetLength ());
                return _GetRep ().Insert (i, &item, &item + 1);
            }
            template    <typename T, typename TRAITS>
            template    <typename COPY_FROM_ITERATOR_OF_T>
            void    Sequence<T, TRAITS>::InsertAll (size_t i, COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
            {
                Require (i <= this->GetLength ());
                size_t  insertAt = i;
                for (auto i = start; i != end; ++i) {
                    Insert (insertAt++, *i);
                }
            }
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  void    Sequence<T, TRAITS>::InsertAll (size_t i, const CONTAINER_OF_T& s)
            {
                Require (i <= this->GetLength ());
                InsertAll (i, s.begin (), s.end ());
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::Prepend (T item)
            {
                Insert (0, item);
            }
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  void    Sequence<T, TRAITS>::PrependAll (const CONTAINER_OF_T& s)
            {
                InsertAll (0, s);
            }
            template    <typename T, typename TRAITS>
            template    <typename COPY_FROM_ITERATOR_OF_T>
            inline void Sequence<T, TRAITS>::PrependAll (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
            {
                InsertAll (0, start, end);
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::Append (T item)
            {
                _GetRep ().Insert (kBadSequenceIndex, &item, &item + 1);
            }
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  void    Sequence<T, TRAITS>::AppendAll (const CONTAINER_OF_T& s)
            {
                for (auto i : s) {
                    _GetRep ().Insert (kBadSequenceIndex, &i, &i + 1);
                }
            }
            template    <typename T, typename TRAITS>
            template    <typename COPY_FROM_ITERATOR_OF_T>
            inline void Sequence<T, TRAITS>::AppendAll (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
            {
                for (auto i = start; i != end; ++i) {
                    _GetRep ().Insert (kBadSequenceIndex, &*i, (&*i) + 1);
                }
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::Update (const Iterator<T>& i, T newValue)
            {
                _GetRep ().Update (i, newValue);
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::Remove (size_t i)
            {
                Require (i < this->GetLength ());
                _GetRep ().Remove (i, i + 1);
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::Remove (size_t start, size_t end)
            {
                Require (start <= end and end <= this->GetLength ());
                _GetRep ().Remove (start, end);
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::Remove (const Iterator<T>& i)
            {
                _GetRep ().Remove (i);
            }
            template    <typename T, typename TRAITS>
            template    <typename   CONTAINER_OF_T>
            inline  CONTAINER_OF_T  Sequence<T, TRAITS>::As () const
            {
                return CONTAINER_OF_T (this->begin (), this->end ());
            }
            template    <typename T, typename TRAITS>
            template    <typename   CONTAINER_OF_T>
            inline  void    Sequence<T, TRAITS>::As (CONTAINER_OF_T* into) const
            {
                RequireNotNull (into);
                *into = CONTAINER_OF_T (this->begin (), this->end ());
            }
            template    <typename T, typename TRAITS>
            inline  T    Sequence<T, TRAITS>::GetFirst () const
            {
                Require (not this->IsEmpty ());
                return GetAt (0);
            }
            template    <typename T, typename TRAITS>
            inline  T    Sequence<T, TRAITS>::GetLast () const
            {
                Require (not this->IsEmpty ());
                // IRep::GetAt() defined to allow special kBadSequenceIndex
                return _GetRep ().GetAt (kBadSequenceIndex);
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::push_back (T item)
            {
                Append (item);
            }
            template    <typename T, typename TRAITS>
            inline  T    Sequence<T, TRAITS>::back () const
            {
                return GetLast ();
            }
            template    <typename T, typename TRAITS>
            inline  T    Sequence<T, TRAITS>::front () const
            {
                return GetFirst ();
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::clear ()
            {
                RemoveAll ();
            }
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>& Sequence<T, TRAITS>::operator+= (T item)
            {
                Append (item);
                return *this;
            }
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>& Sequence<T, TRAITS>::operator+= (const Sequence<T, TRAITS>& items)
            {
                AppendAll (items);
                return *this;
            }
            template    <typename T, typename TRAITS>
            inline  bool Sequence<T, TRAITS>::operator< (const Sequence<T, TRAITS>& rhs) const
            {
                return Compare (rhs) < 0;
            }
            template    <typename T, typename TRAITS>
            inline  bool Sequence<T, TRAITS>::operator<= (const Sequence<T, TRAITS>& rhs) const
            {
                return Compare (rhs) <= 0;
            }
            template    <typename T, typename TRAITS>
            inline  bool Sequence<T, TRAITS>::operator> (const Sequence<T, TRAITS>& rhs) const
            {
                return Compare (rhs) > 0;
            }
            template    <typename T, typename TRAITS>
            inline  bool Sequence<T, TRAITS>::operator>= (const Sequence<T, TRAITS>& rhs) const
            {
                return Compare (rhs) >= 0;
            }
            template    <typename T, typename TRAITS>
            inline  bool Sequence<T, TRAITS>::operator== (const Sequence<T, TRAITS>& rhs) const
            {
                return Equals (rhs);
            }
            template    <typename T, typename TRAITS>
            inline  bool Sequence<T, TRAITS>::operator!= (const Sequence<T, TRAITS>& rhs) const
            {
                return not Equals (rhs);
            }

            /*
             ********************************************************************************
             *************************** Sequence<T>::_IRep *********************************
             ********************************************************************************
             */
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>::_IRep::_IRep ()
            {
            }
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>::_IRep::~_IRep ()
            {
            }

        }
    }
}
#endif /* _Stroika_Foundation_Containers_Sequence_inl_ */
<commit_msg>replace &*i, (&*i) + 1 with an explicit tmp; not sure what that is needed, but vs 2k13 seems to barf (bad code) otehrwise, and I'm not sure they are wrong. Easier to write with temp and not worht digging into now)<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2013.  All rights reserved
 */
#ifndef _Stroika_Foundation_Containers_Sequence_inl_
#define _Stroika_Foundation_Containers_Sequence_inl_

#include    "../Debug/Assertions.h"

#include    "Concrete/Sequence_Factory.h"
#include    "Private/IterableUtils.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   Containers {

            /*
             ********************************************************************************
             **************************** Sequence<T, TRAITS> *******************************
             ********************************************************************************
             */
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>::Sequence ()
                : inherited (Concrete::Sequence_Factory<T, TRAITS>::mk ())
            {
            }
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>::Sequence (const Sequence<T, TRAITS>& s)
                : inherited (static_cast<const inherited&> (s))
            {
            }
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>::Sequence (const initializer_list<T>& s)
                : inherited (Concrete::Sequence_Factory<T, TRAITS>::mk ())
            {
                AppendAll (s);
            }
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>::Sequence (const vector<T>& s)
                : inherited (Concrete::Sequence_Factory<T, TRAITS>::mk ())
            {
                AppendAll (s);
            }
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  Sequence<T, TRAITS>::Sequence (const CONTAINER_OF_T& s)
                : inherited (Concrete::Sequence_Factory<T, TRAITS>::mk ())
            {
                AppendAll (s);
            }
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>::Sequence (const _SharedPtrIRep& rep)
                : inherited (typename inherited::_SharedPtrIRep (rep))
            {
                RequireNotNull (rep);
            }
            template    <typename T, typename TRAITS>
            template    <typename COPY_FROM_ITERATOR_OF_T>
            inline Sequence<T, TRAITS>::Sequence (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
                : inherited (Concrete::Sequence_Factory<T, TRAITS>::mk ())
            {
                AppendAll (start, end);
            }
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>& Sequence<T, TRAITS>::operator= (const Sequence<T, TRAITS>& rhs)
            {
                inherited::operator= (rhs);
                return *this;
            }
            template    <typename T, typename TRAITS>
            inline  const typename  Sequence<T, TRAITS>::_IRep&    Sequence<T, TRAITS>::_GetRep () const
            {
                EnsureMember (&inherited::_GetRep (), _IRep);       // static_cast more efficient, but assert to verify safe
                return *static_cast<const _IRep*> (&inherited::_GetRep ());
            }
            template    <typename T, typename TRAITS>
            inline  typename    Sequence<T, TRAITS>::_IRep&  Sequence<T, TRAITS>::_GetRep ()
            {
                EnsureMember (&inherited::_GetRep (), _IRep);       // static_cast more efficient, but assert to verify safe
                return *static_cast<_IRep*> (&inherited::_GetRep ());
            }
            template    <typename T, typename TRAITS>
            inline  bool    Sequence<T, TRAITS>::Contains (T item) const
            {
                RequireConceptAppliesToTypeInFunction(Concept_EqualsCompareFunctionType, EqualsCompareFunctionType);
                return Private::Contains_<T, EqualsCompareFunctionType> (*this, item);
            }
            template    <typename T, typename TRAITS>
            template    <typename ELEMENT_COMPARER>
            inline  int    Sequence<T, TRAITS>::Compare (const Iterable<T>& rhs) const
            {
                return Private::Compare_<T, ELEMENT_COMPARER> (*this, rhs);
            }
            template    <typename T, typename TRAITS>
            inline  bool    Sequence<T, TRAITS>::Equals (const Sequence<T, TRAITS>& rhs) const
            {
                RequireConceptAppliesToTypeInFunction(Concept_EqualsCompareFunctionType, EqualsCompareFunctionType);
                return Private::Equals_<T, EqualsCompareFunctionType> (*this, rhs);
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::RemoveAll ()
            {
                _GetRep ().Remove (0, this->GetLength ());
            }
            template    <typename T, typename TRAITS>
            inline  T    Sequence<T, TRAITS>::GetAt (size_t i) const
            {
                Require (i < this->GetLength ());
                return _GetRep ().GetAt (i);
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::SetAt (size_t i, T item)
            {
                Require (i < this->GetLength ());
                _GetRep ().SetAt (i, item);
            }
            template    <typename T, typename TRAITS>
            inline  T    Sequence<T, TRAITS>::operator[] (size_t i) const
            {
                Require (i < this->GetLength ());
                return _GetRep ().GetAt (i);
            }
            template    <typename T, typename TRAITS>
            inline  size_t    Sequence<T, TRAITS>::IndexOf (T item) const
            {
                RequireConceptAppliesToTypeInFunction(Concept_EqualsCompareFunctionType, EqualsCompareFunctionType);
                return Private::IndexOf_<T, EqualsCompareFunctionType> (*this, item, kBadSequenceIndex);
            }
            template    <typename T, typename TRAITS>
            inline  size_t    Sequence<T, TRAITS>::IndexOf (const Sequence<T, TRAITS>& s) const
            {
                RequireConceptAppliesToTypeInFunction(Concept_EqualsCompareFunctionType, EqualsCompareFunctionType);
                return Private::IndexOf_<T, EqualsCompareFunctionType> (*this, s, kBadSequenceIndex);
            }
            template    <typename T, typename TRAITS>
            inline  size_t    Sequence<T, TRAITS>::IndexOf (const Iterator<T>& i) const
            {
                return _GetRep ().IndexOf (i);
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::Insert (size_t i, T item)
            {
                Require (i <= this->GetLength ());
                return _GetRep ().Insert (i, &item, &item + 1);
            }
            template    <typename T, typename TRAITS>
            template    <typename COPY_FROM_ITERATOR_OF_T>
            void    Sequence<T, TRAITS>::InsertAll (size_t i, COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
            {
                Require (i <= this->GetLength ());
                size_t  insertAt = i;
                for (auto i = start; i != end; ++i) {
                    Insert (insertAt++, *i);
                }
            }
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  void    Sequence<T, TRAITS>::InsertAll (size_t i, const CONTAINER_OF_T& s)
            {
                Require (i <= this->GetLength ());
                InsertAll (i, s.begin (), s.end ());
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::Prepend (T item)
            {
                Insert (0, item);
            }
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  void    Sequence<T, TRAITS>::PrependAll (const CONTAINER_OF_T& s)
            {
                InsertAll (0, s);
            }
            template    <typename T, typename TRAITS>
            template    <typename COPY_FROM_ITERATOR_OF_T>
            inline void Sequence<T, TRAITS>::PrependAll (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
            {
                InsertAll (0, start, end);
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::Append (T item)
            {
                _GetRep ().Insert (kBadSequenceIndex, &item, &item + 1);
            }
            template    <typename T, typename TRAITS>
            template    <typename CONTAINER_OF_T>
            inline  void    Sequence<T, TRAITS>::AppendAll (const CONTAINER_OF_T& s)
            {
                for (auto i : s) {
                    _GetRep ().Insert (kBadSequenceIndex, &i, &i + 1);
                }
            }
            template    <typename T, typename TRAITS>
            template    <typename COPY_FROM_ITERATOR_OF_T>
            inline void Sequence<T, TRAITS>::AppendAll (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end)
            {
                for (auto i = start; i != end; ++i) {
                    auto tmp = *i;
                    _GetRep ().Insert (kBadSequenceIndex, &tmp, &tmp + 1);
                }
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::Update (const Iterator<T>& i, T newValue)
            {
                _GetRep ().Update (i, newValue);
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::Remove (size_t i)
            {
                Require (i < this->GetLength ());
                _GetRep ().Remove (i, i + 1);
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::Remove (size_t start, size_t end)
            {
                Require (start <= end and end <= this->GetLength ());
                _GetRep ().Remove (start, end);
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::Remove (const Iterator<T>& i)
            {
                _GetRep ().Remove (i);
            }
            template    <typename T, typename TRAITS>
            template    <typename   CONTAINER_OF_T>
            inline  CONTAINER_OF_T  Sequence<T, TRAITS>::As () const
            {
                return CONTAINER_OF_T (this->begin (), this->end ());
            }
            template    <typename T, typename TRAITS>
            template    <typename   CONTAINER_OF_T>
            inline  void    Sequence<T, TRAITS>::As (CONTAINER_OF_T* into) const
            {
                RequireNotNull (into);
                *into = CONTAINER_OF_T (this->begin (), this->end ());
            }
            template    <typename T, typename TRAITS>
            inline  T    Sequence<T, TRAITS>::GetFirst () const
            {
                Require (not this->IsEmpty ());
                return GetAt (0);
            }
            template    <typename T, typename TRAITS>
            inline  T    Sequence<T, TRAITS>::GetLast () const
            {
                Require (not this->IsEmpty ());
                // IRep::GetAt() defined to allow special kBadSequenceIndex
                return _GetRep ().GetAt (kBadSequenceIndex);
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::push_back (T item)
            {
                Append (item);
            }
            template    <typename T, typename TRAITS>
            inline  T    Sequence<T, TRAITS>::back () const
            {
                return GetLast ();
            }
            template    <typename T, typename TRAITS>
            inline  T    Sequence<T, TRAITS>::front () const
            {
                return GetFirst ();
            }
            template    <typename T, typename TRAITS>
            inline  void    Sequence<T, TRAITS>::clear ()
            {
                RemoveAll ();
            }
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>& Sequence<T, TRAITS>::operator+= (T item)
            {
                Append (item);
                return *this;
            }
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>& Sequence<T, TRAITS>::operator+= (const Sequence<T, TRAITS>& items)
            {
                AppendAll (items);
                return *this;
            }
            template    <typename T, typename TRAITS>
            inline  bool Sequence<T, TRAITS>::operator< (const Sequence<T, TRAITS>& rhs) const
            {
                return Compare (rhs) < 0;
            }
            template    <typename T, typename TRAITS>
            inline  bool Sequence<T, TRAITS>::operator<= (const Sequence<T, TRAITS>& rhs) const
            {
                return Compare (rhs) <= 0;
            }
            template    <typename T, typename TRAITS>
            inline  bool Sequence<T, TRAITS>::operator> (const Sequence<T, TRAITS>& rhs) const
            {
                return Compare (rhs) > 0;
            }
            template    <typename T, typename TRAITS>
            inline  bool Sequence<T, TRAITS>::operator>= (const Sequence<T, TRAITS>& rhs) const
            {
                return Compare (rhs) >= 0;
            }
            template    <typename T, typename TRAITS>
            inline  bool Sequence<T, TRAITS>::operator== (const Sequence<T, TRAITS>& rhs) const
            {
                return Equals (rhs);
            }
            template    <typename T, typename TRAITS>
            inline  bool Sequence<T, TRAITS>::operator!= (const Sequence<T, TRAITS>& rhs) const
            {
                return not Equals (rhs);
            }

            /*
             ********************************************************************************
             *************************** Sequence<T>::_IRep *********************************
             ********************************************************************************
             */
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>::_IRep::_IRep ()
            {
            }
            template    <typename T, typename TRAITS>
            inline  Sequence<T, TRAITS>::_IRep::~_IRep ()
            {
            }

        }
    }
}
#endif /* _Stroika_Foundation_Containers_Sequence_inl_ */
<|endoftext|>