<commit_before>//..............................................................................
//
//  This file is part of the Jancy toolkit.
//
//  Jancy is distributed under the MIT license.
//  For details see accompanying license.txt file,
//  the public copy of which is also available at:
//  http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................

#include "pch.h"
#include "jnc_ct_ReactorClassType.h"
#include "jnc_ct_Module.h"
#include "jnc_ct_Parser.llk.h"

namespace jnc {
namespace ct {

//..............................................................................

ReactorClassType::ReactorClassType ()
{
	m_classTypeKind = ClassTypeKind_Reactor;
	m_reactionCount = 0;
	m_bindSiteCount = 0;
	memset (m_fieldArray, 0, sizeof (m_fieldArray));
	memset (m_methodArray, 0, sizeof (m_methodArray));
}

void
ReactorClassType::prepareTypeString ()
{
	TypeStringTuple* tuple = getTypeStringTuple ();
	tuple->m_typeStringPrefix.format ("reactor %s", m_qualifiedName.sz ());
	tuple->m_typeStringSuffix = m_methodArray [ReactorMethodKind_Start]->getType ()->getShortType ()->getTypeStringSuffix ();
}

void
ReactorClassType::prepareDoxyLinkedText ()
{
	TypeStringTuple* tuple = getTypeStringTuple ();
	tuple->m_doxyLinkedTextPrefix.format ("reactor %s", m_qualifiedName.sz ());
	tuple->m_doxyLinkedTextSuffix = m_methodArray [ReactorMethodKind_Start]->getType ()->getShortType ()->getDoxyLinkedTextSuffix ();
}

bool
ReactorClassType::setBody (sl::BoxList <Token>* tokenList)
{
	if (!m_body.isEmpty ())
	{
		err::setFormatStringError ("'%s' already has a body", m_tag.sz ());
		return false;
	}

	m_body.takeOver (tokenList);
	m_module->markForCompile (this);
	return true;
}

bool
ReactorClassType::calcLayout ()
{
	bool result;

	if (m_body.isEmpty ())
	{
		err::setFormatStringError ("reactor '%s' has no body", m_tag.sz ());
		return false;
	}

	// scan

	Parser parser (m_module);
	parser.m_stage = Parser::Stage_ReactorScan;
	parser.m_reactorType = this;

	Function* start = m_methodArray [ReactorMethodKind_Start];
	Function* prevFunction = m_module->m_functionMgr.setCurrentFunction (start);

	m_module->m_namespaceMgr.openNamespace (this);

	result = parser.parseTokenList (SymbolKind_reactor_body_0, m_body, false);
	if (!result)
		return false;

	m_module->m_namespaceMgr.closeNamespace ();
	m_module->m_functionMgr.setCurrentFunction (prevFunction);

	if (!parser.m_reactionCount)
	{
		err::setFormatStringError ("reactor '%s' has no reactions", m_tag.sz ());
		return false;
	}

	if (!parser.m_reactorTotalBindSiteCount)
	{
		err::setFormatStringError ("reactor '%s' has no bindings", m_tag.sz ());
		return false;
	}

	m_reactionCount = parser.m_reactionCount;
	m_bindSiteCount = parser.m_reactorTotalBindSiteCount;

	printf ("ReactorClassType::calcLayout (): m_bindSiteCount: %d; m_reactionCount: %d\n",
		m_bindSiteCount,
		m_reactionCount
		);

	Type* bindSiteType = m_module->m_typeMgr.getStdType (StdType_ReactorBindSite);
	ArrayType* arrayType = bindSiteType->getArrayType (m_bindSiteCount);
	m_fieldArray [ReactorFieldKind_BindSiteArray] = createField ("!m_bindSiteArray", arrayType);

	arrayType = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int32)->getArrayType (m_reactionCount);
	m_fieldArray [ReactorFieldKind_ReactionStateArray] = createField ("!m_reactionStateArray", arrayType);

	result = ClassType::calcLayout ();
	if (!result)
		return false;

	return true;
}

bool
ReactorClassType::subscribe (const sl::ConstList <Reaction>& reactionList)
{
	bool result;

	StructType* bindSiteType = (StructType*) m_module->m_typeMgr.getStdType (StdType_ReactorBindSite);

	sl::Array <StructField*> fieldArray = bindSiteType->getMemberFieldArray ();
	StructField* eventPtrField = fieldArray [0];
	StructField* cookieField = fieldArray.getBack ();

	Value thisValue = m_module->m_functionMgr.getThisValue ();
	ASSERT (thisValue);

	Value bindSiteArrayValue;
	result = m_module->m_operatorMgr.getField (
		thisValue,
		m_fieldArray [ReactorFieldKind_BindSiteArray],
		NULL,
		&bindSiteArrayValue
		);

	if (!result)
		return false;

	sl::Iterator <Reaction> reaction = reactionList.getHead ();
	size_t reactionIdx = 0;
	size_t bindSiteIdx = 0;
	for (; reaction; reaction++, reactionIdx++)
	{
		Function* function = reaction->m_function;
		function->m_reactionIndex = reactionIdx;

		sl::BoxIterator <Value> value = reaction->m_bindSiteList.getHead ();
		for (; value; value++, bindSiteIdx++)
		{
			Value eventValue = *value;
			Value handlerValue = function;

			Closure* closure = handlerValue.createClosure ();
			closure->insertThisArgValue (thisValue);

			result =
				m_module->m_operatorMgr.prepareOperand (&eventValue) &&
				m_module->m_operatorMgr.prepareOperand (&handlerValue);

			if (!result)
				return false;

			if (eventValue.getType ()->getTypeKind () == TypeKind_ClassRef)
			{
				result = m_module->m_operatorMgr.unaryOperator (UnOpKind_Addr, &eventValue); // turn into a pointer
				ASSERT (result);
			}

			Value idxValue (bindSiteIdx, m_module->m_typeMgr.getPrimitiveType (TypeKind_SizeT));
			Value addMethodValue;
			Value cookieValue;
			Value bindSiteValue;
			Value dstEventValue;
			Value dstCookieValue;

			result =
				m_module->m_operatorMgr.memberOperator (eventValue, "add", &addMethodValue) &&
				m_module->m_operatorMgr.callOperator (addMethodValue, handlerValue, &cookieValue) &&
				m_module->m_operatorMgr.binaryOperator (BinOpKind_Idx, bindSiteArrayValue, idxValue, &bindSiteValue) &&
				m_module->m_operatorMgr.getStructField (bindSiteValue, eventPtrField, NULL, &dstEventValue) &&
				m_module->m_operatorMgr.getStructField (bindSiteValue, cookieField, NULL, &dstCookieValue) &&
				m_module->m_operatorMgr.storeDataRef (dstCookieValue, cookieValue);

			if (!result)
				return false;

			// bit-cast event pointers is enough

			m_module->m_llvmIrBuilder.createBitCast (eventValue, eventPtrField->getType (), &eventValue);
			m_module->m_llvmIrBuilder.createStore (eventValue, dstEventValue);
		}
	}

	ASSERT (reactionIdx == m_reactionCount);
	ASSERT (bindSiteIdx <= m_bindSiteCount);
	return true;
}

bool
ReactorClassType::callStopMethod ()
{
	Value thisValue = m_module->m_functionMgr.getThisValue ();
	ASSERT (thisValue);

	Value stopMethodValue = m_methodArray [ReactorMethodKind_Stop];
	Closure* closure = stopMethodValue.createClosure ();
	closure->insertThisArgValue (thisValue);
	return m_module->m_operatorMgr.callOperator (stopMethodValue);
}

bool
ReactorClassType::compileConstructor ()
{
	ASSERT (m_constructor);

	bool result;

	size_t argCount = m_constructor->getType ()->getArgArray ().getCount ();
	ASSERT (argCount == 1 || argCount == 2);

	Value argValueArray [2];
	m_module->m_functionMgr.internalPrologue (m_constructor, argValueArray, argCount);

	if (argCount == 2)
	{
		StructField* field = m_fieldArray [ReactorFieldKind_Parent];
		ASSERT (field);

		Value parentFieldValue;
		result =
			m_module->m_operatorMgr.getClassField (argValueArray [0], field, NULL, &parentFieldValue) &&
			m_module->m_operatorMgr.storeDataRef (parentFieldValue, argValueArray [1]);

		if (!result)
			return false;
	}

	m_module->m_functionMgr.internalEpilogue ();
	return true;
}

bool
ReactorClassType::compileDestructor ()
{
	ASSERT (m_destructor);

	bool result;

	Value argValue;
	m_module->m_functionMgr.internalPrologue (m_destructor, &argValue, 1);

	result = callStopMethod ();
	if (!result)
		return false;

	m_module->m_functionMgr.internalEpilogue ();
	return true;
}

bool
ReactorClassType::compileStartMethod ()
{
	bool result;

	Function* startMethod = m_methodArray [ReactorMethodKind_Start];
	Function* stopMethod = m_methodArray [ReactorMethodKind_Stop];

	m_module->m_functionMgr.prologue (startMethod, m_body.getHead ()->m_pos);

	Value thisValue = m_module->m_functionMgr.getThisValue ();
	ASSERT (thisValue);

	// stop

	result = callStopMethod ();
	if (!result)
		return false;

	// save arguments

	sl::Array <FunctionArg*> argArray = startMethod->getType ()->getArgArray ();
	size_t argCount = argArray.getCount ();
	size_t i = 1;

	sl::Iterator <StructField> argFieldIt = m_firstArgField;
	llvm::Function::arg_iterator llvmArgIt = startMethod->getLlvmFunction ()->arg_begin();
	llvmArgIt++;

	for (; i < argCount; i++, llvmArgIt++, argFieldIt++)
	{
		FunctionArg* arg = argArray [i];
		llvm::Value* llvmArg = llvmArgIt;
		StructField* argField = *argFieldIt;

		if (!arg->isNamed ())
			continue;

		Value argValue (llvmArg, arg->getType ());

		Value storeValue;
		result = m_module->m_operatorMgr.getField (thisValue, argField, NULL, &storeValue);
		if (!result)
			return false;

		m_module->m_llvmIrBuilder.createStore (argValue, storeValue);
	}

	// compile start

	Parser parser (m_module);
	parser.m_stage = Parser::Stage_ReactorStarter;
	parser.m_reactorType = this;

	result = parser.parseTokenList (SymbolKind_reactor_body, m_body, true);
	if (!result)
		return false;

	// modify state

	Value stateValue;
	result =
		m_module->m_operatorMgr.getField (thisValue, m_fieldArray [ReactorFieldKind_State], NULL, &stateValue) &&
		m_module->m_operatorMgr.storeDataRef (
			stateValue,
			Value ((int64_t) 1, m_module->m_typeMgr.getPrimitiveType (TypeKind_IntPtr))
			);

	if (!result)
		return false;

	// done

	result = m_module->m_functionMgr.epilogue ();
	if (!result)
		return false;

	return true;
}
bool
ReactorClassType::compileStopMethod ()
{
	bool result;

	StructType* bindSiteType = (StructType*) m_module->m_typeMgr.getStdType (StdType_ReactorBindSite);

	sl::Array <StructField*> fieldArray = bindSiteType->getMemberFieldArray ();
	StructField* eventPtrField = fieldArray [0];
	StructField* cookieField = fieldArray.getBack ();

	m_module->m_functionMgr.internalPrologue (m_methodArray [ReactorMethodKind_Stop]);

	Value thisValue = m_module->m_functionMgr.getThisValue ();
	ASSERT (thisValue);

	BasicBlock* unadviseBlock = m_module->m_controlFlowMgr.createBlock ("unadvise_block");
	BasicBlock* followBlock = m_module->m_controlFlowMgr.createBlock ("follow_block");

	Value stateValue;
	Value stateCmpValue;
	Value bindSiteArrayValue;

	result =
		m_module->m_operatorMgr.getField (thisValue, m_fieldArray [ReactorFieldKind_State], NULL, &stateValue) &&
		m_module->m_controlFlowMgr.conditionalJump (stateValue, unadviseBlock, followBlock);

	if (!result)
		return false;

	result = m_module->m_operatorMgr.getField (thisValue, m_fieldArray [ReactorFieldKind_BindSiteArray], NULL, &bindSiteArrayValue);
	if (!result)
		return false;

	for (size_t i = 0; i < m_bindSiteCount; i++)
	{
		Value idxValue (i, m_module->m_typeMgr.getPrimitiveType (TypeKind_SizeT));
		Value bindSiteValue;
		Value eventValue;
		Value cookieValue;
		Value removeMethodValue;

		result =
			m_module->m_operatorMgr.binaryOperator (BinOpKind_Idx, bindSiteArrayValue, idxValue, &bindSiteValue) &&
			m_module->m_operatorMgr.getStructField (bindSiteValue, eventPtrField, NULL, &eventValue) &&
			m_module->m_operatorMgr.getStructField (bindSiteValue, cookieField, NULL, &cookieValue) &&
			m_module->m_operatorMgr.memberOperator (eventValue, "remove", &removeMethodValue) &&
			m_module->m_operatorMgr.callOperator (removeMethodValue, cookieValue);

		if (!result)
			return false;
	}

	result = m_module->m_operatorMgr.storeDataRef (
		stateValue,
		Value ((int64_t) 0, m_module->m_typeMgr.getPrimitiveType (TypeKind_IntPtr))
		);

	ASSERT (result);

	m_module->m_controlFlowMgr.follow (followBlock);

	m_module->m_functionMgr.internalEpilogue ();

	return true;
}

//..............................................................................

} // namespace ct
} // namespace jnc
<commit_msg>[jnc_ct] removed debug printf from reactor calc-layout<commit_after>//..............................................................................
//
//  This file is part of the Jancy toolkit.
//
//  Jancy is distributed under the MIT license.
//  For details see accompanying license.txt file,
//  the public copy of which is also available at:
//  http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................

#include "pch.h"
#include "jnc_ct_ReactorClassType.h"
#include "jnc_ct_Module.h"
#include "jnc_ct_Parser.llk.h"

namespace jnc {
namespace ct {

//..............................................................................

ReactorClassType::ReactorClassType ()
{
	m_classTypeKind = ClassTypeKind_Reactor;
	m_reactionCount = 0;
	m_bindSiteCount = 0;
	memset (m_fieldArray, 0, sizeof (m_fieldArray));
	memset (m_methodArray, 0, sizeof (m_methodArray));
}

void
ReactorClassType::prepareTypeString ()
{
	TypeStringTuple* tuple = getTypeStringTuple ();
	tuple->m_typeStringPrefix.format ("reactor %s", m_qualifiedName.sz ());
	tuple->m_typeStringSuffix = m_methodArray [ReactorMethodKind_Start]->getType ()->getShortType ()->getTypeStringSuffix ();
}

void
ReactorClassType::prepareDoxyLinkedText ()
{
	TypeStringTuple* tuple = getTypeStringTuple ();
	tuple->m_doxyLinkedTextPrefix.format ("reactor %s", m_qualifiedName.sz ());
	tuple->m_doxyLinkedTextSuffix = m_methodArray [ReactorMethodKind_Start]->getType ()->getShortType ()->getDoxyLinkedTextSuffix ();
}

bool
ReactorClassType::setBody (sl::BoxList <Token>* tokenList)
{
	if (!m_body.isEmpty ())
	{
		err::setFormatStringError ("'%s' already has a body", m_tag.sz ());
		return false;
	}

	m_body.takeOver (tokenList);
	m_module->markForCompile (this);
	return true;
}

bool
ReactorClassType::calcLayout ()
{
	bool result;

	if (m_body.isEmpty ())
	{
		err::setFormatStringError ("reactor '%s' has no body", m_tag.sz ());
		return false;
	}

	// scan

	Parser parser (m_module);
	parser.m_stage = Parser::Stage_ReactorScan;
	parser.m_reactorType = this;

	Function* start = m_methodArray [ReactorMethodKind_Start];
	Function* prevFunction = m_module->m_functionMgr.setCurrentFunction (start);

	m_module->m_namespaceMgr.openNamespace (this);

	result = parser.parseTokenList (SymbolKind_reactor_body_0, m_body, false);
	if (!result)
		return false;

	m_module->m_namespaceMgr.closeNamespace ();
	m_module->m_functionMgr.setCurrentFunction (prevFunction);

	if (!parser.m_reactionCount)
	{
		err::setFormatStringError ("reactor '%s' has no reactions", m_tag.sz ());
		return false;
	}

	if (!parser.m_reactorTotalBindSiteCount)
	{
		err::setFormatStringError ("reactor '%s' has no bindings", m_tag.sz ());
		return false;
	}

	m_reactionCount = parser.m_reactionCount;
	m_bindSiteCount = parser.m_reactorTotalBindSiteCount;

	Type* bindSiteType = m_module->m_typeMgr.getStdType (StdType_ReactorBindSite);
	ArrayType* arrayType = bindSiteType->getArrayType (m_bindSiteCount);
	m_fieldArray [ReactorFieldKind_BindSiteArray] = createField ("!m_bindSiteArray", arrayType);

	arrayType = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int32)->getArrayType (m_reactionCount);
	m_fieldArray [ReactorFieldKind_ReactionStateArray] = createField ("!m_reactionStateArray", arrayType);

	result = ClassType::calcLayout ();
	if (!result)
		return false;

	return true;
}

bool
ReactorClassType::subscribe (const sl::ConstList <Reaction>& reactionList)
{
	bool result;

	StructType* bindSiteType = (StructType*) m_module->m_typeMgr.getStdType (StdType_ReactorBindSite);

	sl::Array <StructField*> fieldArray = bindSiteType->getMemberFieldArray ();
	StructField* eventPtrField = fieldArray [0];
	StructField* cookieField = fieldArray.getBack ();

	Value thisValue = m_module->m_functionMgr.getThisValue ();
	ASSERT (thisValue);

	Value bindSiteArrayValue;
	result = m_module->m_operatorMgr.getField (
		thisValue,
		m_fieldArray [ReactorFieldKind_BindSiteArray],
		NULL,
		&bindSiteArrayValue
		);

	if (!result)
		return false;

	sl::Iterator <Reaction> reaction = reactionList.getHead ();
	size_t reactionIdx = 0;
	size_t bindSiteIdx = 0;
	for (; reaction; reaction++, reactionIdx++)
	{
		Function* function = reaction->m_function;
		function->m_reactionIndex = reactionIdx;

		sl::BoxIterator <Value> value = reaction->m_bindSiteList.getHead ();
		for (; value; value++, bindSiteIdx++)
		{
			Value eventValue = *value;
			Value handlerValue = function;

			Closure* closure = handlerValue.createClosure ();
			closure->insertThisArgValue (thisValue);

			result =
				m_module->m_operatorMgr.prepareOperand (&eventValue) &&
				m_module->m_operatorMgr.prepareOperand (&handlerValue);

			if (!result)
				return false;

			if (eventValue.getType ()->getTypeKind () == TypeKind_ClassRef)
			{
				result = m_module->m_operatorMgr.unaryOperator (UnOpKind_Addr, &eventValue); // turn into a pointer
				ASSERT (result);
			}

			Value idxValue (bindSiteIdx, m_module->m_typeMgr.getPrimitiveType (TypeKind_SizeT));
			Value addMethodValue;
			Value cookieValue;
			Value bindSiteValue;
			Value dstEventValue;
			Value dstCookieValue;

			result =
				m_module->m_operatorMgr.memberOperator (eventValue, "add", &addMethodValue) &&
				m_module->m_operatorMgr.callOperator (addMethodValue, handlerValue, &cookieValue) &&
				m_module->m_operatorMgr.binaryOperator (BinOpKind_Idx, bindSiteArrayValue, idxValue, &bindSiteValue) &&
				m_module->m_operatorMgr.getStructField (bindSiteValue, eventPtrField, NULL, &dstEventValue) &&
				m_module->m_operatorMgr.getStructField (bindSiteValue, cookieField, NULL, &dstCookieValue) &&
				m_module->m_operatorMgr.storeDataRef (dstCookieValue, cookieValue);

			if (!result)
				return false;

			// bit-cast event pointers is enough

			m_module->m_llvmIrBuilder.createBitCast (eventValue, eventPtrField->getType (), &eventValue);
			m_module->m_llvmIrBuilder.createStore (eventValue, dstEventValue);
		}
	}

	ASSERT (reactionIdx == m_reactionCount);
	ASSERT (bindSiteIdx <= m_bindSiteCount);
	return true;
}

bool
ReactorClassType::callStopMethod ()
{
	Value thisValue = m_module->m_functionMgr.getThisValue ();
	ASSERT (thisValue);

	Value stopMethodValue = m_methodArray [ReactorMethodKind_Stop];
	Closure* closure = stopMethodValue.createClosure ();
	closure->insertThisArgValue (thisValue);
	return m_module->m_operatorMgr.callOperator (stopMethodValue);
}

bool
ReactorClassType::compileConstructor ()
{
	ASSERT (m_constructor);

	bool result;

	size_t argCount = m_constructor->getType ()->getArgArray ().getCount ();
	ASSERT (argCount == 1 || argCount == 2);

	Value argValueArray [2];
	m_module->m_functionMgr.internalPrologue (m_constructor, argValueArray, argCount);

	if (argCount == 2)
	{
		StructField* field = m_fieldArray [ReactorFieldKind_Parent];
		ASSERT (field);

		Value parentFieldValue;
		result =
			m_module->m_operatorMgr.getClassField (argValueArray [0], field, NULL, &parentFieldValue) &&
			m_module->m_operatorMgr.storeDataRef (parentFieldValue, argValueArray [1]);

		if (!result)
			return false;
	}

	m_module->m_functionMgr.internalEpilogue ();
	return true;
}

bool
ReactorClassType::compileDestructor ()
{
	ASSERT (m_destructor);

	bool result;

	Value argValue;
	m_module->m_functionMgr.internalPrologue (m_destructor, &argValue, 1);

	result = callStopMethod ();
	if (!result)
		return false;

	m_module->m_functionMgr.internalEpilogue ();
	return true;
}

bool
ReactorClassType::compileStartMethod ()
{
	bool result;

	Function* startMethod = m_methodArray [ReactorMethodKind_Start];
	Function* stopMethod = m_methodArray [ReactorMethodKind_Stop];

	m_module->m_functionMgr.prologue (startMethod, m_body.getHead ()->m_pos);

	Value thisValue = m_module->m_functionMgr.getThisValue ();
	ASSERT (thisValue);

	// stop

	result = callStopMethod ();
	if (!result)
		return false;

	// save arguments

	sl::Array <FunctionArg*> argArray = startMethod->getType ()->getArgArray ();
	size_t argCount = argArray.getCount ();
	size_t i = 1;

	sl::Iterator <StructField> argFieldIt = m_firstArgField;
	llvm::Function::arg_iterator llvmArgIt = startMethod->getLlvmFunction ()->arg_begin();
	llvmArgIt++;

	for (; i < argCount; i++, llvmArgIt++, argFieldIt++)
	{
		FunctionArg* arg = argArray [i];
		llvm::Value* llvmArg = llvmArgIt;
		StructField* argField = *argFieldIt;

		if (!arg->isNamed ())
			continue;

		Value argValue (llvmArg, arg->getType ());

		Value storeValue;
		result = m_module->m_operatorMgr.getField (thisValue, argField, NULL, &storeValue);
		if (!result)
			return false;

		m_module->m_llvmIrBuilder.createStore (argValue, storeValue);
	}

	// compile start

	Parser parser (m_module);
	parser.m_stage = Parser::Stage_ReactorStarter;
	parser.m_reactorType = this;

	result = parser.parseTokenList (SymbolKind_reactor_body, m_body, true);
	if (!result)
		return false;

	// modify state

	Value stateValue;
	result =
		m_module->m_operatorMgr.getField (thisValue, m_fieldArray [ReactorFieldKind_State], NULL, &stateValue) &&
		m_module->m_operatorMgr.storeDataRef (
			stateValue,
			Value ((int64_t) 1, m_module->m_typeMgr.getPrimitiveType (TypeKind_IntPtr))
			);

	if (!result)
		return false;

	// done

	result = m_module->m_functionMgr.epilogue ();
	if (!result)
		return false;

	return true;
}
bool
ReactorClassType::compileStopMethod ()
{
	bool result;

	StructType* bindSiteType = (StructType*) m_module->m_typeMgr.getStdType (StdType_ReactorBindSite);

	sl::Array <StructField*> fieldArray = bindSiteType->getMemberFieldArray ();
	StructField* eventPtrField = fieldArray [0];
	StructField* cookieField = fieldArray.getBack ();

	m_module->m_functionMgr.internalPrologue (m_methodArray [ReactorMethodKind_Stop]);

	Value thisValue = m_module->m_functionMgr.getThisValue ();
	ASSERT (thisValue);

	BasicBlock* unadviseBlock = m_module->m_controlFlowMgr.createBlock ("unadvise_block");
	BasicBlock* followBlock = m_module->m_controlFlowMgr.createBlock ("follow_block");

	Value stateValue;
	Value stateCmpValue;
	Value bindSiteArrayValue;

	result =
		m_module->m_operatorMgr.getField (thisValue, m_fieldArray [ReactorFieldKind_State], NULL, &stateValue) &&
		m_module->m_controlFlowMgr.conditionalJump (stateValue, unadviseBlock, followBlock);

	if (!result)
		return false;

	result = m_module->m_operatorMgr.getField (thisValue, m_fieldArray [ReactorFieldKind_BindSiteArray], NULL, &bindSiteArrayValue);
	if (!result)
		return false;

	for (size_t i = 0; i < m_bindSiteCount; i++)
	{
		Value idxValue (i, m_module->m_typeMgr.getPrimitiveType (TypeKind_SizeT));
		Value bindSiteValue;
		Value eventValue;
		Value cookieValue;
		Value removeMethodValue;

		result =
			m_module->m_operatorMgr.binaryOperator (BinOpKind_Idx, bindSiteArrayValue, idxValue, &bindSiteValue) &&
			m_module->m_operatorMgr.getStructField (bindSiteValue, eventPtrField, NULL, &eventValue) &&
			m_module->m_operatorMgr.getStructField (bindSiteValue, cookieField, NULL, &cookieValue) &&
			m_module->m_operatorMgr.memberOperator (eventValue, "remove", &removeMethodValue) &&
			m_module->m_operatorMgr.callOperator (removeMethodValue, cookieValue);

		if (!result)
			return false;
	}

	result = m_module->m_operatorMgr.storeDataRef (
		stateValue,
		Value ((int64_t) 0, m_module->m_typeMgr.getPrimitiveType (TypeKind_IntPtr))
		);

	ASSERT (result);

	m_module->m_controlFlowMgr.follow (followBlock);

	m_module->m_functionMgr.internalEpilogue ();

	return true;
}

//..............................................................................

} // namespace ct
} // namespace jnc
<|endoftext|>


<commit_before><commit_msg>use CHECK(false) in ConvertGrpcTimeoutToUS<commit_after><|endoftext|>


<commit_before><commit_msg>use the already computed maxPlayer count when we start up instead of the counting ourselves<commit_after><|endoftext|>


<commit_before>/**
 * \brief	Example with LPC11C24 and Siemens S75 display.
 *
 * The S75 display is connected to GPIOs. Pinout is as follows:
 *
 *
 */

#include <xpcc/architecture.hpp>

// How to include the defines?
// #include "xpcc_config.hpp" does not work.
#include "../../../../../build/lpcxpresso/lpc11c24/display_s75/libxpcc/xpcc_config.hpp"
#include <xpcc/driver/ui/display/siemens_s75.hpp>

#include <xpcc/workflow/timeout.hpp>

namespace lcd
{
	GPIO__OUTPUT(D0,   3,  2);
	GPIO__OUTPUT(D1,   2,  2);
	GPIO__OUTPUT(D2,   2,  1);
	GPIO__OUTPUT(D3,   2,  0);
	GPIO__OUTPUT(D4,   1,  5);
	GPIO__OUTPUT(D5,   2, 11);
	GPIO__OUTPUT(D6,   0,  8);
	GPIO__OUTPUT(D7,   0,  9);

	typedef xpcc::gpio::Port<D7, D6, D5, D4, D3, D2, D1, D0> Port;

	GPIO__OUTPUT(Rs,    0,  6);		// = CD = Command / Data
	GPIO__OUTPUT(Reset, 3,  0);
	GPIO__OUTPUT(Cs,    3,  1);
	GPIO__OUTPUT(Wr,    1,  4);
}

typedef xpcc::SiemensS75Landscape<lcd::Port, lcd::Cs, lcd::Rs, lcd::Wr, lcd::Reset> Display;

#define LED_TOGGLE_TICKS 100		// 100 ticks = 1 Hz flash rate
#define COUNT_MAX		3			// how high to count on the LED display

GPIO__OUTPUT(Led, 0, 7);

Display display;

int
main(void)
{
	SystemInit();

	xpcc::lpc11::SysTickTimer::enable();

	// Set LED port pin to output
	Led::setOutput();

	while (1)
	{
		static uint16_t ii = 10;
		Led::toggle();
		xpcc::delay_ms(100);
		Led::toggle();
		xpcc::delay_ms(50);

		if (!--ii)
			break;
	}

	lcd::Port::setOutput();

	// Initialise the display
	display.initialize();
	display.setFont(xpcc::font::Assertion);

	bool dir = true;
	uint8_t y = 0;
	while (1)
	{
		display.clear();
		display.setCursor(5, y);
		display << "Hello";
		display.setCursor(46, 16);
		display << "World!";

		display.drawLine(0, y, 40, 31 - y);
		display.drawLine(132 - 40, 31 - y, 132, y);

		if (dir) {
			y++;
			if (y >= 5) {
				dir = false;
			}
		}
		else {
			y--;
			if (y == 0) {
				dir = true;
			}
		}
		// finished, copy to lcd
		display.update();
	}
}
<commit_msg>Siemens S75 display tested at LPCxpresso LPC1114<commit_after>/**
 * \brief	Example with LPC11C24 and Siemens S75 display.
 *
 * The S75 display is connected to GPIOs.
 *
 * LPClink does not work.
 * Program with serial boot loader
 * 1) Connect FT/GPIO to GND
 * 2) Power up
 * 3) lpc21isp -debug5 ../../../../../build/lpcxpresso/lpc11c24/display_s75/display_s75.hex  /dev/tty.SLAB_USBtoUART 57600 14746
 * 4) Power down
 * 5) Disconnect FT/GPIO
 * 6) Power up
 *
 * See siemens_s75.hpp for pinout
 *
 */

#include <xpcc/architecture.hpp>

// How to include the defines?
// #include "xpcc_config.hpp" does not work.
#include "../../../../../build/lpcxpresso/lpc11c24/display_s75/libxpcc/xpcc_config.hpp"
#include <xpcc/driver/ui/display/tft_memory_bus.hpp>
#include <xpcc/driver/ui/display/siemens_s75.hpp>

#include <xpcc/workflow/timeout.hpp>

namespace lcd
{
	GPIO__IO(D0,   3,  2);
	GPIO__IO(D1,   2,  2);
	GPIO__IO(D2,   2,  1);
	GPIO__IO(D3,   2,  0);
	GPIO__IO(D4,   1,  5);
	GPIO__IO(D5,   2, 10);
	GPIO__IO(D6,   3,  5); // wrong text on silkscreen
	GPIO__IO(D7,   1,  9);

	GPIO__OUTPUT(Cd,    0,  6);		// = CD = Command / Data
	GPIO__OUTPUT(Cs,    3,  1);
	GPIO__OUTPUT(Wr,    3,  4); // wrong text on silkscreen

	GPIO__OUTPUT(Reset, 3,  0);

	typedef xpcc::gpio::Port<D7, D6, D5, D4, D3, D2, D1, D0> Port;
	typedef xpcc::TftMemoryBus8BitGpio<Port, Cs, xpcc::gpio::Unused, Wr, Cd> ParallelBus;

	// Display
	typedef xpcc::SiemensS75LandscapeRight<lcd::ParallelBus, lcd::Reset> Display;

}

#define LED_TOGGLE_TICKS 100		// 100 ticks = 1 Hz flash rate
#define COUNT_MAX		3			// how high to count on the LED display

GPIO__OUTPUT(Led, 0, 7);

lcd::ParallelBus
parallelBus;

lcd::Display display(parallelBus);

int
main(void)
{
	SystemInit();

	xpcc::lpc11::SysTickTimer::enable();

	// Set LED port pin to output
	Led::setOutput();

	while (1)
	{
		static uint16_t ii = 10;
		Led::toggle();
		xpcc::delay_ms(100);
		Led::toggle();
		xpcc::delay_ms(50);

		if (!--ii)
			break;
	}

	// Initialise the display
	lcd::Reset::setOutput();

	lcd::Cd::setOutput();
	lcd::Cs::setOutput();
	lcd::Wr::setOutput();

	lcd::D0::setInput();
	lcd::D1::setInput();
	lcd::D2::setInput();
	lcd::D3::setInput();
	lcd::D4::setInput();
	lcd::D5::setInput();
	lcd::D6::setInput();
	lcd::D7::setInput();

	lcd::ParallelBus::initialize();

	display.initialize();
	display.setFont(xpcc::font::Assertion);

	bool dir = true;
	uint8_t y = 0;
	while (1)
	{
		display.clear();
		display.setCursor(5, y);
		display << "Hello";
		display.setCursor(46, 16);
		display << "World!";

		display.drawLine(0, y, 40, 31 - y);
		display.drawLine(132 - 40, 31 - y, 132, y);

		if (dir) {
			y++;
			if (y >= 5) {
				dir = false;
			}
		}
		else {
			y--;
			if (y == 0) {
				dir = true;
			}
		}
		// finished, copy to lcd
		display.update();
	}
}
<|endoftext|>


<commit_before>
#include "module.h"
#include "processor.h"

#include <boost/lexical_cast.hpp>

namespace job_stream {
namespace module {

Module* Module::make() {
    return new Module();
}

Module::Module() : level(0) {
}

void Module::populateAfterRestore(const YAML::Node& globalConfig,
        const YAML::Node& config) {
    job::JobBase::populateAfterRestore(globalConfig, config);

    for (auto it = this->jobMap.begin(); it != this->jobMap.end(); it++) {
        it->second->processor = this->processor;
        it->second->populateAfterRestore(globalConfig,
                config["jobs"][it->second->id]);
    }

    if (this->reducer) {
        this->reducer->processor = this->processor;
        this->reducer->populateAfterRestore(globalConfig, config["reducer"]);
    }
}

void Module::postSetup() {
    //Sanity checks - jobs cannot be a sequence if input is defined.
    if (this->config["jobs"].IsSequence()) {
        if (this->config["input"]) {
            std::ostringstream ss;
            ss << "Module " << this->getFullName() << " has input defined but "
                    "jobs is a list";
            throw std::runtime_error(ss.str());
        }
    }
    else if (!this->config["input"]) {
        if (!this->config["jobs"].IsSequence()) {
            std::ostringstream ss;
            ss << "Module " << this->getFullName() << " has no input defined";
            throw std::runtime_error(ss.str());
        }
    }

    //Is this module framed?
    if (this->config["frame"]) {
        if (this->config["reducer"]) {
            std::ostringstream ss;
            ss << "Module " << this->getFullName() << " cannot define a "
                    "reducer as it has a frame defined";
            throw std::runtime_error(ss.str());
        }

        this->config["reducer"] = this->config["frame"];
        if (this->config["input"]) {
            this->config["reducer"]["recurTo"] = this->config["input"].as<
                    std::string>();
        }
        else {
            this->config["reducer"]["recurTo"] = "0";
        }

        this->config["input"] = "output";
        this->config.remove("frame");
    }

    if (this->config["jobs"].IsSequence()) {
        //Pipeline!  Since all of the code relies on named jobs, as they
        //are more flexible, we have to replace the jobs node with a named
        //version.
        YAML::Node newJobs;

        //If there is no input, then we need to set it to the first job in the
        //sequence.
        if (!this->config["input"]) {
            this->config["input"] = "0";
        }

        int jobId = 0;
        for (int i = 0, m = this->config["jobs"].size(); i < m; i++) {
            YAML::Node n = this->config["jobs"][i];
            if (n["to"]) {
                std::ostringstream ss;
                ss << "Job " << jobId << " under " << this->getFullName();
                ss << " cannot have a 'to' configured.  If you need to";
                ss << " use 'to', you'll need to use named jobs instead";
                ss << " of a list.";
                throw std::runtime_error(ss.str());
            }

            if (i < m - 1) {
                n["to"] = boost::lexical_cast<std::string>(jobId + 1);
            }
            else {
                n["to"] = "output";
            }
            newJobs[boost::lexical_cast<std::string>(jobId)] = n;
            jobId += 1;
        }

        this->config["jobs"] = newJobs;
    }

    //Assign our level
    if (this->parent) {
        this->level = this->parent->level + 1;
        if (!this->config["to"]) {
            std::ostringstream ss;
            ss << "Module " << this->getFullName() << " needs a 'to'";
            throw std::runtime_error(ss.str());
        }
    }

    //Set up reducer, unless we've started from a checkpoint
    if (this->config["reducer"] && !this->reducer) {
        this->reducer.reset(this->processor->allocateReducer(this,
                this->config["reducer"]));
    }
}

void Module::dispatchWork(message::WorkRecord& work) {
    this->currentRecord = &work;
    //If we end up assigning this work to a new reduction, we need to decrement
    //the placeholder childTagCount put on it in dispatchInit (after this work
    //is handled, of course)
    //Also make sure it's us that changed the ring, not some other reducer
    uint64_t startedReduceTag = 0;
    bool startedNewRing = false;

    if (processor::JOB_STREAM_DEBUG >= 2) {
        std::ostringstream ss;
        ss << "Dispatching: " << this->getFullName();
        fprintf(stderr, "%s\n", ss.str().c_str());
    }

    const std::vector<std::string>& target = work.getTarget();
    if (this->level == target.size()) {
        //We're the end goal (this work just started living in our module).
        //If we have a reducer, we have to tag this work and create a new
        //reduction context
        if (this->reducer && this->reducer->dispatchInit(work)) {
            startedNewRing = true;
            startedReduceTag = work.getReduceTag();
        }

        //Then, pass to our input job.
        std::string firstJob = this->config["input"].as<std::string>();
        work.redirectTo(firstJob);
    }

    //Now we're looking at the input job.
    std::string curTarget = target[this->level];
    if (curTarget == "output") {
        //Reduce, or do 1 job step on output...
        bool isReduced = false;
        if (target.size() == this->level + 2) {
            if (target[this->level + 1] != "reduced") {
                throw std::runtime_error("Extended output not reduced?");
            }
            isReduced = true;
        }

        if (!this->reducer || isReduced) {
            //This is finalized output.
            if (!this->config["to"]) {
                if (this->level != 0) {
                    std::ostringstream ss;
                    ss << "Module '" << this->id << "' needs 'to' configured";
                    throw std::runtime_error(ss.str());
                }
                else {
                    //Print as str to stdout for root module by default
                    printf("%s\n", work.getWorkAsString().c_str());
                }
            }
            else {
                throw std::runtime_error("shouldn't be reached; implemented in "
                        "sendModuleOutput.");
            }
        }
        else {
            //When a reducer is active, output is just a JobBase that is the
            //reducer.
            if (processor::JOB_STREAM_DEBUG >= 2) {
                std::ostringstream ss;
                ss << "Passing to " << this->reducer->getFullName()
                        << ", tag " << work.getReduceTag();
                fprintf(stderr, "%s\n", ss.str().c_str());
            }
            this->reducer->dispatchAdd(work);
        }
    }
    else {
        //Process the work under the appropriate job (or forward to next module)
        if (processor::JOB_STREAM_DEBUG >= 2) {
            std::ostringstream ss;
            ss << "Passing to " << this->getJob(curTarget)->getFullName();
            fprintf(stderr, "%s\n", ss.str().c_str());
        }
        this->getJob(curTarget)->dispatchWork(work);
    }

    if (startedNewRing) {
        this->processor->decrReduceChildTag(startedReduceTag, true);
    }

    this->currentRecord = 0;

    if (processor::JOB_STREAM_DEBUG >= 2) {
        std::ostringstream ss;
        ss << "Completed dispatch " << this->getFullName();
        fprintf(stderr, "%s\n", ss.str().c_str());
    }
}

bool Module::wouldReduce(message::WorkRecord& work) {
    const std::vector<std::string>& target = work.getTarget();
    std::string curTarget;
    if (this->level >= target.size()) {
        if (this->reducer) {
            return true;
        }
        curTarget = this->config["input"].as<std::string>();
    }
    else {
        curTarget = target[this->level];
    }

    return this->getJob(curTarget)->wouldReduce(work);
}

job::JobBase* Module::getJob(const std::string& id) {
    Lock lock(this->mutex);

    auto jobIter = this->jobMap.find(id);
    if (jobIter != this->jobMap.end()) {
        return jobIter->second.get();
    }

    //Make the job
    if (id == "output") {
        std::ostringstream ss;
        ss << "getJob() called for output? " << this->getFullName();
        throw std::runtime_error(ss.str());
    }
    else if (!this->config["jobs"][id]) {
        std::ostringstream msg;
        msg << "Unrecognized job id: '" << this->getFullName() << "::" << id
                << "'";
        throw std::runtime_error(msg.str());
    }

    const YAML::Node& config = this->config["jobs"][id];
    job::JobBase* job = this->processor->allocateJob(this, id,
            config);
    this->jobMap[id].reset(job);
    return job;
}

std::string Module::getInputTypeName() {
    if (this->config["input"].as<std::string>() == "output") {
        return this->reducer->getInputTypeName();
    }
    return this->getJob(this->config["input"].as<std::string>())
            ->getInputTypeName();
}

} //module
} //job_stream
<commit_msg>Trimming some newlines in module.cpp<commit_after>
#include "module.h"
#include "processor.h"

#include <boost/lexical_cast.hpp>

namespace job_stream {
namespace module {

Module* Module::make() {
    return new Module();
}

Module::Module() : level(0) {
}

void Module::populateAfterRestore(const YAML::Node& globalConfig,
        const YAML::Node& config) {
    job::JobBase::populateAfterRestore(globalConfig, config);

    for (auto it = this->jobMap.begin(); it != this->jobMap.end(); it++) {
        it->second->processor = this->processor;
        it->second->populateAfterRestore(globalConfig,
                config["jobs"][it->second->id]);
    }

    if (this->reducer) {
        this->reducer->processor = this->processor;
        this->reducer->populateAfterRestore(globalConfig, config["reducer"]);
    }
}

void Module::postSetup() {
    //Sanity checks - jobs cannot be a sequence if input is defined.
    if (this->config["jobs"].IsSequence()) {
        if (this->config["input"]) {
            std::ostringstream ss;
            ss << "Module " << this->getFullName() << " has input defined but "
                    "jobs is a list";
            throw std::runtime_error(ss.str());
        }
    }
    else if (!this->config["input"]) {
        if (!this->config["jobs"].IsSequence()) {
            std::ostringstream ss;
            ss << "Module " << this->getFullName() << " has no input defined";
            throw std::runtime_error(ss.str());
        }
    }

    //Is this module framed?
    if (this->config["frame"]) {
        if (this->config["reducer"]) {
            std::ostringstream ss;
            ss << "Module " << this->getFullName() << " cannot define a "
                    "reducer as it has a frame defined";
            throw std::runtime_error(ss.str());
        }

        this->config["reducer"] = this->config["frame"];
        if (this->config["input"]) {
            this->config["reducer"]["recurTo"] = this->config["input"].as<
                    std::string>();
        }
        else {
            this->config["reducer"]["recurTo"] = "0";
        }

        this->config["input"] = "output";
        this->config.remove("frame");
    }

    if (this->config["jobs"].IsSequence()) {
        //Pipeline!  Since all of the code relies on named jobs, as they
        //are more flexible, we have to replace the jobs node with a named
        //version.
        YAML::Node newJobs;

        //If there is no input, then we need to set it to the first job in the
        //sequence.
        if (!this->config["input"]) {
            this->config["input"] = "0";
        }

        int jobId = 0;
        for (int i = 0, m = this->config["jobs"].size(); i < m; i++) {
            YAML::Node n = this->config["jobs"][i];
            if (n["to"]) {
                std::ostringstream ss;
                ss << "Job " << jobId << " under " << this->getFullName();
                ss << " cannot have a 'to' configured.  If you need to";
                ss << " use 'to', you'll need to use named jobs instead";
                ss << " of a list.";
                throw std::runtime_error(ss.str());
            }

            if (i < m - 1) {
                n["to"] = boost::lexical_cast<std::string>(jobId + 1);
            }
            else {
                n["to"] = "output";
            }
            newJobs[boost::lexical_cast<std::string>(jobId)] = n;
            jobId += 1;
        }

        this->config["jobs"] = newJobs;
    }

    //Assign our level
    if (this->parent) {
        this->level = this->parent->level + 1;
        if (!this->config["to"]) {
            std::ostringstream ss;
            ss << "Module " << this->getFullName() << " needs a 'to'";
            throw std::runtime_error(ss.str());
        }
    }

    //Set up reducer, unless we've started from a checkpoint
    if (this->config["reducer"] && !this->reducer) {
        this->reducer.reset(this->processor->allocateReducer(this,
                this->config["reducer"]));
    }
}

void Module::dispatchWork(message::WorkRecord& work) {
    this->currentRecord = &work;
    //If we end up assigning this work to a new reduction, we need to decrement
    //the placeholder childTagCount put on it in dispatchInit (after this work
    //is handled, of course)
    //Also make sure it's us that changed the ring, not some other reducer
    uint64_t startedReduceTag = 0;
    bool startedNewRing = false;

    if (processor::JOB_STREAM_DEBUG >= 2) {
        std::ostringstream ss;
        ss << "Dispatching: " << this->getFullName();
        fprintf(stderr, "%s\n", ss.str().c_str());
    }

    const std::vector<std::string>& target = work.getTarget();
    if (this->level == target.size()) {
        //We're the end goal (this work just started living in our module).
        //If we have a reducer, we have to tag this work and create a new
        //reduction context
        if (this->reducer && this->reducer->dispatchInit(work)) {
            startedNewRing = true;
            startedReduceTag = work.getReduceTag();
        }

        //Then, pass to our input job.
        std::string firstJob = this->config["input"].as<std::string>();
        work.redirectTo(firstJob);
    }

    //Now we're looking at the input job.
    std::string curTarget = target[this->level];
    if (curTarget == "output") {
        //Reduce, or do 1 job step on output...
        bool isReduced = false;
        if (target.size() == this->level + 2) {
            if (target[this->level + 1] != "reduced") {
                throw std::runtime_error("Extended output not reduced?");
            }
            isReduced = true;
        }

        if (!this->reducer || isReduced) {
            //This is finalized output.
            if (!this->config["to"]) {
                if (this->level != 0) {
                    std::ostringstream ss;
                    ss << "Module '" << this->id << "' needs 'to' configured";
                    throw std::runtime_error(ss.str());
                }
                else {
                    //Print as str to stdout for root module by default
                    printf("%s\n", work.getWorkAsString().c_str());
                }
            }
            else {
                throw std::runtime_error("shouldn't be reached; implemented in "
                        "sendModuleOutput.");
            }
        }
        else {
            //When a reducer is active, output is just a JobBase that is the
            //reducer.
            if (processor::JOB_STREAM_DEBUG >= 2) {
                std::ostringstream ss;
                ss << "Passing to " << this->reducer->getFullName()
                        << ", tag " << work.getReduceTag();
                fprintf(stderr, "%s\n", ss.str().c_str());
            }
            this->reducer->dispatchAdd(work);
        }
    }
    else {
        //Process the work under the appropriate job (or forward to next module)
        if (processor::JOB_STREAM_DEBUG >= 2) {
            std::ostringstream ss;
            ss << "Passing to " << this->getJob(curTarget)->getFullName();
            fprintf(stderr, "%s\n", ss.str().c_str());
        }
        this->getJob(curTarget)->dispatchWork(work);
    }

    if (startedNewRing) {
        this->processor->decrReduceChildTag(startedReduceTag, true);
    }

    this->currentRecord = 0;

    if (processor::JOB_STREAM_DEBUG >= 2) {
        std::ostringstream ss;
        ss << "Completed dispatch " << this->getFullName();
        fprintf(stderr, "%s\n", ss.str().c_str());
    }
}

bool Module::wouldReduce(message::WorkRecord& work) {
    const std::vector<std::string>& target = work.getTarget();
    std::string curTarget;
    if (this->level >= target.size()) {
        if (this->reducer) {
            return true;
        }
        curTarget = this->config["input"].as<std::string>();
    }
    else {
        curTarget = target[this->level];
    }

    return this->getJob(curTarget)->wouldReduce(work);
}

job::JobBase* Module::getJob(const std::string& id) {
    Lock lock(this->mutex);

    auto jobIter = this->jobMap.find(id);
    if (jobIter != this->jobMap.end()) {
        return jobIter->second.get();
    }

    //Make the job
    if (id == "output") {
        std::ostringstream ss;
        ss << "getJob() called for output? " << this->getFullName();
        throw std::runtime_error(ss.str());
    }
    else if (!this->config["jobs"][id]) {
        std::ostringstream msg;
        msg << "Unrecognized job id: '" << this->getFullName() << "::" << id
                << "'";
        throw std::runtime_error(msg.str());
    }

    const YAML::Node& config = this->config["jobs"][id];
    job::JobBase* job = this->processor->allocateJob(this, id,
            config);
    this->jobMap[id].reset(job);
    return job;
}

std::string Module::getInputTypeName() {
    if (this->config["input"].as<std::string>() == "output") {
        return this->reducer->getInputTypeName();
    }
    return this->getJob(this->config["input"].as<std::string>())
            ->getInputTypeName();
}

} //module
} //job_stream
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//-------------------------------------------------------------------------
//               Implementation of the V0 vertexer class
//                  reads tracks writes out V0 vertices
//                      fills the ESD with the V0s
//     Origin: Iouri Belikov, IReS, Strasbourg, Jouri.Belikov@cern.ch
//-------------------------------------------------------------------------
#include <TObjArray.h>
#include <TTree.h>

#include "AliESD.h"
#include "AliESDtrack.h"
#include "AliITStrackV2.h"
#include "AliV0vertex.h"
#include "AliV0vertexer.h"

ClassImp(AliV0vertexer)

Int_t AliV0vertexer::Tracks2V0vertices(AliESD *event) {
  //--------------------------------------------------------------------
  //This function reconstructs V0 vertices
  //--------------------------------------------------------------------

   Int_t nentr=event->GetNumberOfTracks();

   TObjArray negtrks(nentr/2);
   TObjArray postrks(nentr/2);

   Int_t nneg=0, npos=0, nvtx=0;

   Int_t i;
   for (i=0; i<nentr; i++) {
     AliESDtrack *esd=event->GetTrack(i);
     UInt_t status=esd->GetStatus();
     UInt_t flags=AliESDtrack::kITSin|AliESDtrack::kTPCin|
                  AliESDtrack::kTPCpid|AliESDtrack::kESDpid;

     if ((status&AliESDtrack::kITSrefit)==0)
        if (flags!=status) continue;

     AliITStrackV2 *iotrack=new AliITStrackV2(*esd);
     iotrack->SetLabel(i);  // now it is the index in array of ESD tracks
     if ((status&AliESDtrack::kITSrefit)==0)   //correction for the beam pipe
        if (!iotrack->PropagateTo(3.,0.0023,65.19)) {
	  delete iotrack;
	  continue;
	}
     if (!iotrack->PropagateTo(2.5,0.,0.)) {
       delete iotrack;
       continue;
     }

     if (iotrack->Get1Pt() < 0.) {nneg++; negtrks.AddLast(iotrack);}
     else {npos++; postrks.AddLast(iotrack);}
   }

   for (i=0; i<nneg; i++) {
      //if (i%10==0) cerr<<nneg-i<<'\r';
      AliITStrackV2 *ntrk=(AliITStrackV2 *)negtrks.UncheckedAt(i);

      if (TMath::Abs(ntrk->GetD(fX,fY))<fDPmin) continue;
      if (TMath::Abs(ntrk->GetD(fX,fY))>fRmax) continue;

      for (Int_t k=0; k<npos; k++) {
         AliITStrackV2 *ptrk=(AliITStrackV2 *)postrks.UncheckedAt(k);

         if (TMath::Abs(ptrk->GetD(fX,fY))<fDPmin) continue;
         if (TMath::Abs(ptrk->GetD(fX,fY))>fRmax) continue;

         if (TMath::Abs(ntrk->GetD(fX,fY))<fDNmin)
         if (TMath::Abs(ptrk->GetD(fX,fY))<fDNmin) continue;

         AliITStrackV2 nt(*ntrk), pt(*ptrk), *pnt=&nt, *ppt=&pt;

         Double_t dca=PropagateToDCA(pnt,ppt);
         if (dca > fDCAmax) continue;

         AliV0vertex vertex(*pnt,*ppt);
         if (vertex.GetChi2() > fChi2max) continue;

         /*  Think of something better here !
         nt.PropagateToVertex(); if (TMath::Abs(nt.GetZ())<0.04) continue;
         pt.PropagateToVertex(); if (TMath::Abs(pt.GetZ())<0.04) continue;
	 */

         Double_t x,y,z; vertex.GetXYZ(x,y,z);
         Double_t r2=x*x + y*y;
         if (r2 > fRmax*fRmax) continue;
         if (r2 < fRmin*fRmin) continue;

         Double_t px,py,pz; vertex.GetPxPyPz(px,py,pz);
         Double_t p2=px*px+py*py+pz*pz;
         Double_t cost=((x-fX)*px + (y-fY)*py + (z-fZ)*pz)/
               TMath::Sqrt(p2*((x-fX)*(x-fX) + (y-fY)*(y-fY) + (z-fZ)*(z-fZ)));

        //if (cost < (5*fCPAmax-0.9-TMath::Sqrt(r2)*(fCPAmax-1))/4.1) continue;
         if (cost < fCPAmax) continue;

         //vertex.ChangeMassHypothesis(); //default is Lambda0

         event->AddV0(&vertex);

         nvtx++;
      }
   }

   Info("Tracks2V0vertices","Number of reconstructed V0 vertices: %d",nvtx);

   negtrks.Delete();
   postrks.Delete();

   return 0;
}

Int_t AliV0vertexer::Tracks2V0vertices(TTree *tTree, TTree *vTree) {
  //--------------------------------------------------------------------
  //This function reconstructs V0 vertices
  //--------------------------------------------------------------------
  Warning("Tracks2V0vertices(TTree*,TTree*)",
	  "Will be removed soon !  Use Tracks2V0vertices(AliESD*) instead");

   TBranch *branch=tTree->GetBranch("tracks");
   if (!branch) {
      Error("Tracks2V0vertices","Can't get the branch !");
      return 1;
   }
   Int_t nentr=(Int_t)tTree->GetEntries();

   TObjArray negtrks(nentr/2);
   TObjArray postrks(nentr/2);

   Int_t nneg=0, npos=0, nvtx=0;

   Int_t i;
   for (i=0; i<nentr; i++) {
       AliITStrackV2 *iotrack=new AliITStrackV2;
       branch->SetAddress(&iotrack);
       tTree->GetEvent(i);

       if (!iotrack->PropagateTo(3.,0.0023,65.19)) {
	 delete iotrack;
	 continue;
       }
       if (!iotrack->PropagateTo(2.5,0.,0.)) {
	 delete iotrack;
	 continue;
       }

       if (iotrack->Get1Pt() > 0.) {nneg++; negtrks.AddLast(iotrack);}
       else {npos++; postrks.AddLast(iotrack);}
   }

   AliV0vertex *ioVertex=0;
   branch=vTree->GetBranch("vertices");
   if (!branch) vTree->Branch("vertices","AliV0vertex",&ioVertex,32000,3);
   else branch->SetAddress(&ioVertex);

   for (i=0; i<nneg; i++) {
      //if (i%10==0) cerr<<nneg-i<<'\r';
      AliITStrackV2 *ntrk=(AliITStrackV2 *)negtrks.UncheckedAt(i);

      if (TMath::Abs(ntrk->GetD(fX,fY))<fDPmin) continue;
      if (TMath::Abs(ntrk->GetD(fX,fY))>fRmax) continue;

      for (Int_t k=0; k<npos; k++) {
         AliITStrackV2 *ptrk=(AliITStrackV2 *)postrks.UncheckedAt(k);

         if (TMath::Abs(ptrk->GetD(fX,fY))<fDPmin) continue;
         if (TMath::Abs(ptrk->GetD(fX,fY))>fRmax) continue;

         if (TMath::Abs(ntrk->GetD(fX,fY))<fDNmin)
         if (TMath::Abs(ptrk->GetD(fX,fY))<fDNmin) continue;

         AliITStrackV2 nt(*ntrk), pt(*ptrk), *pnt=&nt, *ppt=&pt;

         Double_t dca=PropagateToDCA(pnt,ppt);
         if (dca > fDCAmax) continue;

         AliV0vertex vertex(*pnt,*ppt);
         if (vertex.GetChi2() > fChi2max) continue;

         /*  Think of something better here !
         nt.PropagateToVertex(); if (TMath::Abs(nt.GetZ())<0.04) continue;
         pt.PropagateToVertex(); if (TMath::Abs(pt.GetZ())<0.04) continue;
	 */

         Double_t x,y,z; vertex.GetXYZ(x,y,z);
         Double_t r2=x*x + y*y;
         if (r2 > fRmax*fRmax) continue;
         if (r2 < fRmin*fRmin) continue;

         Double_t px,py,pz; vertex.GetPxPyPz(px,py,pz);
         Double_t p2=px*px+py*py+pz*pz;
         Double_t cost=((x-fX)*px + (y-fY)*py + (z-fZ)*pz)/
               TMath::Sqrt(p2*((x-fX)*(x-fX) + (y-fY)*(y-fY) + (z-fZ)*(z-fZ)));

        //if (cost < (5*fCPAmax-0.9-TMath::Sqrt(r2)*(fCPAmax-1))/4.1) continue;
         if (cost < fCPAmax) continue;

         //vertex.ChangeMassHypothesis(); //default is Lambda0

         ioVertex=&vertex; vTree->Fill();

         nvtx++;
      }
   }

   Info("Tracks2V0vertices","Number of reconstructed V0 vertices: %d",nvtx);

   negtrks.Delete();
   postrks.Delete();

   return 0;
}

Double_t
AliV0vertexer::PropagateToDCA(AliITStrackV2 *n, AliITStrackV2 *p) const {
  //--------------------------------------------------------------------
  // This function returns the DCA between two tracks
  // The tracks will be moved to the point of DCA !
  //--------------------------------------------------------------------
  return n->PropagateToDCA(p);
}

<commit_msg>Adding DCA information (B.Hippolyte)<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//-------------------------------------------------------------------------
//               Implementation of the V0 vertexer class
//                  reads tracks writes out V0 vertices
//                      fills the ESD with the V0s
//     Origin: Iouri Belikov, IReS, Strasbourg, Jouri.Belikov@cern.ch
//-------------------------------------------------------------------------
#include <TObjArray.h>
#include <TTree.h>

#include "AliESD.h"
#include "AliESDtrack.h"
#include "AliITStrackV2.h"
#include "AliV0vertex.h"
#include "AliV0vertexer.h"

ClassImp(AliV0vertexer)

Int_t AliV0vertexer::Tracks2V0vertices(AliESD *event) {
  //--------------------------------------------------------------------
  //This function reconstructs V0 vertices
  //--------------------------------------------------------------------

   Int_t nentr=event->GetNumberOfTracks();

   TObjArray negtrks(nentr/2);
   TObjArray postrks(nentr/2);

   Int_t nneg=0, npos=0, nvtx=0;

   Int_t i;
   for (i=0; i<nentr; i++) {
     AliESDtrack *esd=event->GetTrack(i);
     UInt_t status=esd->GetStatus();
     UInt_t flags=AliESDtrack::kITSin|AliESDtrack::kTPCin|
                  AliESDtrack::kTPCpid|AliESDtrack::kESDpid;

     if ((status&AliESDtrack::kITSrefit)==0)
        if (flags!=status) continue;

     AliITStrackV2 *iotrack=new AliITStrackV2(*esd);
     iotrack->SetLabel(i);  // now it is the index in array of ESD tracks
     if ((status&AliESDtrack::kITSrefit)==0)   //correction for the beam pipe
        if (!iotrack->PropagateTo(3.,0.0023,65.19)) {
	  delete iotrack;
	  continue;
	}
     if (!iotrack->PropagateTo(2.5,0.,0.)) {
       delete iotrack;
       continue;
     }

     if (iotrack->Get1Pt() < 0.) {nneg++; negtrks.AddLast(iotrack);}
     else {npos++; postrks.AddLast(iotrack);}
   }

   for (i=0; i<nneg; i++) {
      //if (i%10==0) cerr<<nneg-i<<'\r';
      AliITStrackV2 *ntrk=(AliITStrackV2 *)negtrks.UncheckedAt(i);

      if (TMath::Abs(ntrk->GetD(fX,fY))<fDPmin) continue;
      if (TMath::Abs(ntrk->GetD(fX,fY))>fRmax) continue;

      for (Int_t k=0; k<npos; k++) {
         AliITStrackV2 *ptrk=(AliITStrackV2 *)postrks.UncheckedAt(k);

         if (TMath::Abs(ptrk->GetD(fX,fY))<fDPmin) continue;
         if (TMath::Abs(ptrk->GetD(fX,fY))>fRmax) continue;

         if (TMath::Abs(ntrk->GetD(fX,fY))<fDNmin)
         if (TMath::Abs(ptrk->GetD(fX,fY))<fDNmin) continue;

         AliITStrackV2 nt(*ntrk), pt(*ptrk), *pnt=&nt, *ppt=&pt;

         Double_t dca=PropagateToDCA(pnt,ppt);
         if (dca > fDCAmax) continue;

         AliV0vertex vertex(*pnt,*ppt);
         if (vertex.GetChi2() > fChi2max) continue;

         /*  Think of something better here !
         nt.PropagateToVertex(); if (TMath::Abs(nt.GetZ())<0.04) continue;
         pt.PropagateToVertex(); if (TMath::Abs(pt.GetZ())<0.04) continue;
	 */

         Double_t x,y,z; vertex.GetXYZ(x,y,z);
         Double_t r2=x*x + y*y;
         if (r2 > fRmax*fRmax) continue;
         if (r2 < fRmin*fRmin) continue;

         Double_t px,py,pz; vertex.GetPxPyPz(px,py,pz);
         Double_t p2=px*px+py*py+pz*pz;
         Double_t cost=((x-fX)*px + (y-fY)*py + (z-fZ)*pz)/
               TMath::Sqrt(p2*((x-fX)*(x-fX) + (y-fY)*(y-fY) + (z-fZ)*(z-fZ)));

        //if (cost < (5*fCPAmax-0.9-TMath::Sqrt(r2)*(fCPAmax-1))/4.1) continue;
         if (cost < fCPAmax) continue;
	 vertex.SetDcaDaughters(dca);
         //vertex.ChangeMassHypothesis(); //default is Lambda0

         event->AddV0(&vertex);

         nvtx++;
      }
   }

   Info("Tracks2V0vertices","Number of reconstructed V0 vertices: %d",nvtx);

   negtrks.Delete();
   postrks.Delete();

   return 0;
}

Int_t AliV0vertexer::Tracks2V0vertices(TTree *tTree, TTree *vTree) {
  //--------------------------------------------------------------------
  //This function reconstructs V0 vertices
  //--------------------------------------------------------------------
  Warning("Tracks2V0vertices(TTree*,TTree*)",
	  "Will be removed soon !  Use Tracks2V0vertices(AliESD*) instead");

   TBranch *branch=tTree->GetBranch("tracks");
   if (!branch) {
      Error("Tracks2V0vertices","Can't get the branch !");
      return 1;
   }
   Int_t nentr=(Int_t)tTree->GetEntries();

   TObjArray negtrks(nentr/2);
   TObjArray postrks(nentr/2);

   Int_t nneg=0, npos=0, nvtx=0;

   Int_t i;
   for (i=0; i<nentr; i++) {
       AliITStrackV2 *iotrack=new AliITStrackV2;
       branch->SetAddress(&iotrack);
       tTree->GetEvent(i);

       if (!iotrack->PropagateTo(3.,0.0023,65.19)) {
	 delete iotrack;
	 continue;
       }
       if (!iotrack->PropagateTo(2.5,0.,0.)) {
	 delete iotrack;
	 continue;
       }

       if (iotrack->Get1Pt() > 0.) {nneg++; negtrks.AddLast(iotrack);}
       else {npos++; postrks.AddLast(iotrack);}
   }

   AliV0vertex *ioVertex=0;
   branch=vTree->GetBranch("vertices");
   if (!branch) vTree->Branch("vertices","AliV0vertex",&ioVertex,32000,3);
   else branch->SetAddress(&ioVertex);

   for (i=0; i<nneg; i++) {
      //if (i%10==0) cerr<<nneg-i<<'\r';
      AliITStrackV2 *ntrk=(AliITStrackV2 *)negtrks.UncheckedAt(i);

      if (TMath::Abs(ntrk->GetD(fX,fY))<fDPmin) continue;
      if (TMath::Abs(ntrk->GetD(fX,fY))>fRmax) continue;

      for (Int_t k=0; k<npos; k++) {
         AliITStrackV2 *ptrk=(AliITStrackV2 *)postrks.UncheckedAt(k);

         if (TMath::Abs(ptrk->GetD(fX,fY))<fDPmin) continue;
         if (TMath::Abs(ptrk->GetD(fX,fY))>fRmax) continue;

         if (TMath::Abs(ntrk->GetD(fX,fY))<fDNmin)
         if (TMath::Abs(ptrk->GetD(fX,fY))<fDNmin) continue;

         AliITStrackV2 nt(*ntrk), pt(*ptrk), *pnt=&nt, *ppt=&pt;

         Double_t dca=PropagateToDCA(pnt,ppt);
         if (dca > fDCAmax) continue;

         AliV0vertex vertex(*pnt,*ppt);
         if (vertex.GetChi2() > fChi2max) continue;

         /*  Think of something better here !
         nt.PropagateToVertex(); if (TMath::Abs(nt.GetZ())<0.04) continue;
         pt.PropagateToVertex(); if (TMath::Abs(pt.GetZ())<0.04) continue;
	 */

         Double_t x,y,z; vertex.GetXYZ(x,y,z);
         Double_t r2=x*x + y*y;
         if (r2 > fRmax*fRmax) continue;
         if (r2 < fRmin*fRmin) continue;

         Double_t px,py,pz; vertex.GetPxPyPz(px,py,pz);
         Double_t p2=px*px+py*py+pz*pz;
         Double_t cost=((x-fX)*px + (y-fY)*py + (z-fZ)*pz)/
               TMath::Sqrt(p2*((x-fX)*(x-fX) + (y-fY)*(y-fY) + (z-fZ)*(z-fZ)));

        //if (cost < (5*fCPAmax-0.9-TMath::Sqrt(r2)*(fCPAmax-1))/4.1) continue;
         if (cost < fCPAmax) continue;
	 vertex.SetDcaDaughters(dca);
         //vertex.ChangeMassHypothesis(); //default is Lambda0

         ioVertex=&vertex; vTree->Fill();

         nvtx++;
      }
   }

   Info("Tracks2V0vertices","Number of reconstructed V0 vertices: %d",nvtx);

   negtrks.Delete();
   postrks.Delete();

   return 0;
}

Double_t
AliV0vertexer::PropagateToDCA(AliITStrackV2 *n, AliITStrackV2 *p) const {
  //--------------------------------------------------------------------
  // This function returns the DCA between two tracks
  // The tracks will be moved to the point of DCA !
  //--------------------------------------------------------------------
  return n->PropagateToDCA(p);
}

<|endoftext|>


<commit_before>/* @(#)main.cpp ---
 *
 * Author: Nicolas Niclausse
 * Copyright (C) 2012 - Nicolas Niclausse, Inria.
 * Created: 2012/04/03 14:41:29
 * Version: $Id$
 * Last-Updated: mar. avril 24 18:35:03 2012 (+0200)
 *           By: Nicolas Niclausse
 *     Update #: 10
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include <dtkCore>
#include <dtkDistributed>

#include <dtkLog/dtkLog.h>

#include <QtCore>

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

    if(!dtkApplicationArgumentsContain(&application, "--torque")
       && !dtkApplicationArgumentsContain(&application, "--oar")
       && !dtkApplicationArgumentsContain(&application, "--ssh")) {
        qDebug() << "Usage:" << argv[0] << " dtk://server:port [--oar || --torque || --ssh]";
        return DTK_SUCCEED;
    }

    application.setApplicationName("dtkDistributedServer");
    application.setApplicationVersion("0.0.1");
    application.setOrganizationName("inria");
    application.setOrganizationDomain("fr");

    QSettings settings("inria", "dtk");
    settings.beginGroup("server");

    if (settings.contains("log_level"))
        dtkLogger::instance().setLevel(settings.value("log_level").toString());
    else
        dtkLogger::instance().setLevel(dtkLog::Debug);

    dtkLogger::instance().attachFile(dtkLogPath(&application));

    dtkDistributedServer server(argc, argv);
    server.run();

    int status = application.exec();

    return DTK_SUCCEED;
}

<commit_msg>controller is expecting something from stdout from server<commit_after>/* @(#)main.cpp ---
 *
 * Author: Nicolas Niclausse
 * Copyright (C) 2012 - Nicolas Niclausse, Inria.
 * Created: 2012/04/03 14:41:29
 * Version: $Id$
 * Last-Updated: mer. avril 25 13:08:30 2012 (+0200)
 *           By: Nicolas Niclausse
 *     Update #: 13
 */

/* Commentary:
 *
 */

/* Change log:
 *
 */

#include <dtkCore>
#include <dtkDistributed>

#include <dtkLog/dtkLog.h>

#include <QtCore>

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

    if(!dtkApplicationArgumentsContain(&application, "--torque")
       && !dtkApplicationArgumentsContain(&application, "--oar")
       && !dtkApplicationArgumentsContain(&application, "--ssh")) {
        qDebug() << "Usage:" << argv[0] << " dtk://server:port [--oar || --torque || --ssh]";
        return DTK_SUCCEED;
    }

    application.setApplicationName("dtkDistributedServer");
    application.setApplicationVersion("0.0.1");
    application.setOrganizationName("inria");
    application.setOrganizationDomain("fr");

    QSettings settings("inria", "dtk");
    settings.beginGroup("server");

    if (settings.contains("log_level"))
        dtkLogger::instance().setLevel(settings.value("log_level").toString());
    else
        dtkLogger::instance().setLevel(dtkLog::Debug);

    dtkLogger::instance().attachFile(dtkLogPath(&application));

    dtkDistributedServer server(argc, argv);
    qDebug() << "server started";
    server.run();

    int status = application.exec();

    return DTK_SUCCEED;
}

<|endoftext|>


<commit_before>/** @file
 * @author Edouard DUPIN
 * @copyright 2014, Edouard DUPIN, all right reserved
 * @license APACHE v2.0 (see license file)
 */

#include <appl/debug.hpp>
#include <appl/GateWay.hpp>
#include <etk/etk.hpp>
#include <zeus/zeus.hpp>

#include <etk/stdTools.hpp>

int main(int _argc, const char *_argv[]) {
	etk::init(_argc, _argv);
	zeus::init(_argc, _argv);
	appl::GateWay basicGateway;
	for (int32_t iii=0; iii<_argc ; ++iii) {
		std::string data = _argv[iii];
		if (etk::start_with(data, "--user=") == true) {
			basicGateway.propertyUserName.set(std::string(&data[7]));
		} else if (data == "--no-router") {
			basicGateway.propertyRouterNo.set(true);
		} else if (etk::start_with(data, "--router-ip=") == true) {
			basicGateway.propertyRouterIp.set(std::string(&data[12]));
		} else if (etk::start_with(data, "--router-port=") == true) {
			basicGateway.propertyRouterPort.set(etk::string_to_uint16_t(std::string(&data[14])));
		} else if (etk::start_with(data, "--service-ip=") == true) {
			basicGateway.propertyServiceIp.set(std::string(&data[13]));
		} else if (etk::start_with(data, "--service-port=") == true) {
			basicGateway.propertyServicePort.set(etk::string_to_uint16_t(std::string(&data[15])));
		} else if (etk::start_with(data, "--service-max=") == true) {
			basicGateway.propertyServiceMax.set(etk::string_to_uint16_t(std::string(&data[14])));
		} else if (    data == "-h"
		            || data == "--help") {
			APPL_PRINT(etk::getApplicationName() << " - help : ");
			APPL_PRINT("    " << _argv[0] << " [options]");
			APPL_PRINT("        --user=XXX           Name of the user that we are connected.");
			APPL_PRINT("        --no-router          Router connection disable ==> this enable the direct donnection of external client like on the router");
			APPL_PRINT("        --router-ip=XXX      Router connection IP (default: 1.7.0.0.1)");
			APPL_PRINT("        --router-port=XXX    Router connection PORT (default: 1984)");
			APPL_PRINT("        --service-ip=XXX     Service connection IP (default: 1.7.0.0.1)");
			APPL_PRINT("        --service-port=XXX   Service connection PORT (default: 1985)");
			APPL_PRINT("        --service-max=XXX    Service Maximum IO (default: 15)");
			return -1;
		}
	}
	APPL_INFO("==================================");
	APPL_INFO("== ZEUS gateway start            ==");
	APPL_INFO("==================================");
	basicGateway.start();
	while (true) {
		std::this_thread::sleep_for(std::chrono::milliseconds(100));
		basicGateway.cleanIO();
	}
	basicGateway.stop();
	APPL_INFO("==================================");
	APPL_INFO("== ZEUS gateway stop             ==");
	APPL_INFO("==================================");
	return 0;
}
<commit_msg>[DEV] try to add launcher in gateway<commit_after>/** @file
 * @author Edouard DUPIN
 * @copyright 2014, Edouard DUPIN, all right reserved
 * @license APACHE v2.0 (see license file)
 */

#include <appl/debug.hpp>
#include <appl/GateWay.hpp>
#include <etk/etk.hpp>
#include <zeus/zeus.hpp>

#include <etk/stdTools.hpp>

#define GATEWAY_ENABLE_LAUNCHER

#ifdef GATEWAY_ENABLE_LAUNCHER
#include <mutex>
#include <etk/os/FSNode.hpp>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include <thread>
#include <etk/stdTools.hpp>
#include <zeus/Object.hpp>
#include <zeus/Client.hpp>
#include <zeus/zeus.hpp>

typedef bool (*SERVICE_IO_init_t)(int _argc, const char *_argv[], std::string _basePath);
typedef bool (*SERVICE_IO_uninit_t)();
typedef void (*SERVICE_IO_peridic_call_t)();
typedef zeus::Object* (*SERVICE_IO_instanciate_t)(uint32_t, ememory::SharedPtr<zeus::WebServer>&, uint32_t);

class PlugginAccess {
	private:
		std::string m_name;
		void* m_handle;
		SERVICE_IO_init_t m_SERVICE_IO_init;
		SERVICE_IO_uninit_t m_SERVICE_IO_uninit;
		SERVICE_IO_peridic_call_t m_SERVICE_IO_peridic_call;
		SERVICE_IO_instanciate_t m_SERVICE_IO_instanciate;
		zeus::Client m_client;
	public:
		PlugginAccess(const std::string& _name) :
		  m_name(_name),
		  m_handle(nullptr),
		  m_SERVICE_IO_init(nullptr),
		  m_SERVICE_IO_uninit(nullptr),
		  m_SERVICE_IO_instanciate(nullptr) {
			std::string srv = etk::FSNodeGetApplicationPath() + "/../lib/libzeus-service-" + m_name + "-impl.so";
			APPL_PRINT("Try to open service with name: '" << m_name << "' at position: '" << srv << "'");
			m_handle = dlopen(srv.c_str(), RTLD_LAZY);
			if (!m_handle) {
				APPL_ERROR("Can not load Lbrary:" << dlerror());
				return;
			}
			char *error = nullptr;
			m_SERVICE_IO_init = (SERVICE_IO_init_t)dlsym(m_handle, "SERVICE_IO_init");
			error = dlerror();
			if (error != nullptr) {
				m_SERVICE_IO_init = nullptr;
				APPL_WARNING("Can not function SERVICE_IO_init :" << error);
			}
			m_SERVICE_IO_uninit = (SERVICE_IO_uninit_t)dlsym(m_handle, "SERVICE_IO_uninit");
			error = dlerror();
			if (error != nullptr) {
				m_SERVICE_IO_uninit = nullptr;
				APPL_WARNING("Can not function SERVICE_IO_uninit :" << error);
			}
			m_SERVICE_IO_peridic_call = (SERVICE_IO_peridic_call_t)dlsym(m_handle, "SERVICE_IO_peridic_call");
			error = dlerror();
			if (error != nullptr) {
				m_SERVICE_IO_uninit = nullptr;
				APPL_WARNING("Can not function SERVICE_IO_uninit :" << error);
			}
			m_SERVICE_IO_instanciate = (SERVICE_IO_instanciate_t)dlsym(m_handle, "SERVICE_IO_instanciate");
			error = dlerror();
			if (error != nullptr) {
				m_SERVICE_IO_instanciate = nullptr;
				APPL_WARNING("Can not function SERVICE_IO_instanciate:" << error);
			}
		}
		~PlugginAccess() {

		}
		bool init(int _argc, const char *_argv[], std::string _basePath) {
			if (m_SERVICE_IO_init == nullptr) {
				return false;
			}

			if (_basePath.size() == 0) {
				_basePath = "USERDATA:" + m_name + "/";
				APPL_PRINT("Use base path: " << _basePath);
			}
			return (*m_SERVICE_IO_init)(_argc, _argv, _basePath);
		}
		bool publish(zeus::Client& _client) {
			if (m_SERVICE_IO_instanciate == nullptr) {
				return false;
			}
			_client.serviceAdd(m_name,  [=](uint32_t _transactionId, ememory::SharedPtr<zeus::WebServer>& _iface, uint32_t _destination) {
			                            	(*m_SERVICE_IO_instanciate)(_transactionId, _iface, _destination);
			                            });
			return true;
		}
		bool disconnect(zeus::Client& _client) {
			_client.serviceRemove(m_name);
			return true;
		}
		bool uninit() {
			if (m_SERVICE_IO_uninit == nullptr) {
				return false;
			}
			return (*m_SERVICE_IO_uninit)();
		}
		void peridic_call() {
			if (m_SERVICE_IO_peridic_call == nullptr) {
				return;
			}
			(*m_SERVICE_IO_peridic_call)();
		}
};
#endif

int main(int _argc, const char *_argv[]) {
	etk::init(_argc, _argv);
	zeus::init(_argc, _argv);
	appl::GateWay basicGateway;
	#ifdef GATEWAY_ENABLE_LAUNCHER
	std::string basePath;
	std::vector<std::string> services;
	zeus::Client m_client;
	#endif
	for (int32_t iii=0; iii<_argc ; ++iii) {
		std::string data = _argv[iii];
		if (etk::start_with(data, "--user=") == true) {
			basicGateway.propertyUserName.set(std::string(&data[7]));
		} else if (data == "--no-router") {
			basicGateway.propertyRouterNo.set(true);
		} else if (etk::start_with(data, "--router-ip=") == true) {
			basicGateway.propertyRouterIp.set(std::string(&data[12]));
		} else if (etk::start_with(data, "--router-port=") == true) {
			basicGateway.propertyRouterPort.set(etk::string_to_uint16_t(std::string(&data[14])));
		} else if (etk::start_with(data, "--service-ip=") == true) {
			basicGateway.propertyServiceIp.set(std::string(&data[13]));
			#ifdef GATEWAY_ENABLE_LAUNCHER
				m_client.propertyIp.set(std::string(&data[13]));
			#endif
		} else if (etk::start_with(data, "--service-port=") == true) {
			basicGateway.propertyServicePort.set(etk::string_to_uint16_t(std::string(&data[15])));
			#ifdef GATEWAY_ENABLE_LAUNCHER
				m_client.propertyPort.set(etk::string_to_uint16_t(std::string(&data[15])));
			#endif
		} else if (etk::start_with(data, "--service-max=") == true) {
			basicGateway.propertyServiceMax.set(etk::string_to_uint16_t(std::string(&data[14])));
		#ifdef GATEWAY_ENABLE_LAUNCHER
		} else if (etk::start_with(data, "--base-path=") == true) {
			basePath = std::string(&data[12]);
		} else if (etk::start_with(data, "--srv=") == true) {
			services.push_back(std::string(&data[6]));
		#endif
		} else if (    data == "-h"
		            || data == "--help") {
			APPL_PRINT(etk::getApplicationName() << " - help : ");
			APPL_PRINT("    " << _argv[0] << " [options]");
			APPL_PRINT("        --user=XXX           Name of the user that we are connected.");
			APPL_PRINT("        --no-router          Router connection disable ==> this enable the direct donnection of external client like on the router");
			APPL_PRINT("        --router-ip=XXX      Router connection IP (default: 1.7.0.0.1)");
			APPL_PRINT("        --router-port=XXX    Router connection PORT (default: 1984)");
			APPL_PRINT("        --service-ip=XXX     Service connection IP (default: 1.7.0.0.1)");
			APPL_PRINT("        --service-port=XXX   Service connection PORT (default: 1985)");
			APPL_PRINT("        --service-max=XXX    Service Maximum IO (default: 15)");
			#ifdef GATEWAY_ENABLE_LAUNCHER
			APPL_PRINT("        specific for internal launcher:");
			APPL_PRINT("        --base-path=XXX      base path to search data (default: 'USERDATA:')");
			APPL_PRINT("        --srv=XXX            service path (N)");
			#endif
			return -1;
		}
	}
	APPL_INFO("==================================");
	APPL_INFO("== ZEUS gateway start            ==");
	APPL_INFO("==================================");
	basicGateway.start();
	#ifdef GATEWAY_ENABLE_LAUNCHER
	if (services.size() == 0) {
	#endif
		while (true) {
			std::this_thread::sleep_for(std::chrono::milliseconds(100));
			basicGateway.cleanIO();
		}
	#ifdef GATEWAY_ENABLE_LAUNCHER
	} else {
		std::vector<ememory::SharedPtr<PlugginAccess>> listElements;
		for (auto &it: services) {
			ememory::SharedPtr<PlugginAccess> tmp = ememory::makeShared<PlugginAccess>(it);
			listElements.push_back(tmp);
		}
		for (auto &it: listElements) {
			it->init(_argc, _argv, basePath);
		}
		if (m_client.connect() == false) {
			return -1;
		}
		for (auto &it: listElements) {
			it->publish(m_client);
		}
		uint32_t iii = 0;
		while(m_client.isAlive() == true) {
			m_client.pingIsAlive();
			m_client.displayConnectedObject();
			m_client.cleanDeadObject();
			for (auto &it: listElements) {
				it->peridic_call();
			}
			basicGateway.cleanIO();
			std::this_thread::sleep_for(std::chrono::seconds(1));
			APPL_INFO("service in waiting ... " << iii << "/inf");
			iii++;
		}
		for (auto &it: listElements) {
			it->disconnect(m_client);
		}
		m_client.disconnect();
		APPL_INFO("Stop service*** ==> flush internal datas ...");
		for (auto &it: listElements) {
			it->uninit();
		}
	}
	#endif
	basicGateway.stop();
	APPL_INFO("==================================");
	APPL_INFO("== ZEUS gateway stop             ==");
	APPL_INFO("==================================");
	return 0;
}
<|endoftext|>


<commit_before>//===- llvm-pdbdump.cpp - Dump debug info from a PDB file -------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Dumps debug information present in PDB files.  This utility makes use of
// the Microsoft Windows SDK, so will not compile or run on non-Windows
// platforms.
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/DebugInfo/PDB/PDB.h"
#include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"
#include "llvm/DebugInfo/PDB/IPDBSession.h"
#include "llvm/DebugInfo/PDB/IPDBRawSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
#include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"

#include <Windows.h>

using namespace llvm;

namespace opts {
cl::list<std::string> InputFilenames(cl::Positional,
                                     cl::desc("<input PDB files>"),
                                     cl::OneOrMore);

cl::opt<bool> Compilands("compilands",
                         cl::desc("Display a list of compilands (e.g. object "
                                  "files) and symbols for each one."));
cl::alias CompilandsShort("c", cl::desc("Alias for --compilands"),
                          cl::aliasopt(Compilands));
}

static void dumpInput(StringRef Path) {
  std::unique_ptr<IPDBSession> Session(
      llvm::createPDBReader(PDB_ReaderType::DIA, Path));
  if (!Session) {
    outs() << "Unable to create PDB reader.  Check that a valid implementation";
    outs() << " is available for your platform.";
    return;
  }

  auto GlobalScope(Session->getGlobalScope());
  GlobalScope->dump(outs(), 0, PDB_DumpLevel::Normal);
  outs().flush();

  if (opts::Compilands) {
    auto Compilands = GlobalScope->findChildren(PDB_SymType::Compiland);
    if (Compilands) {
      while (auto Compiland = Compilands->getNext()) {
        Compiland->dump(outs(), 0, PDB_DumpLevel::Normal);
      }
    }
  }
  outs().flush();
}

int main(int argc_, const char *argv_[]) {
  // Print a stack trace if we signal out.
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc_, argv_);

  SmallVector<const char *, 256> argv;
  llvm::SpecificBumpPtrAllocator<char> ArgAllocator;
  std::error_code EC = llvm::sys::Process::GetArgumentVector(
      argv, llvm::makeArrayRef(argv_, argc_), ArgAllocator);
  if (EC) {
    llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n';
    return 1;
  }

  llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.

  cl::ParseCommandLineOptions(argv.size(), argv.data(), "LLVM PDB Dumper\n");

  CoInitializeEx(nullptr, COINIT_MULTITHREADED);

  std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),
                dumpInput);

  CoUninitialize();
  return 0;
}
<commit_msg>Oops.  Don't call Windows functions on non-windows.<commit_after>//===- llvm-pdbdump.cpp - Dump debug info from a PDB file -------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Dumps debug information present in PDB files.  This utility makes use of
// the Microsoft Windows SDK, so will not compile or run on non-Windows
// platforms.
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Config/config.h"
#include "llvm/DebugInfo/PDB/PDB.h"
#include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"
#include "llvm/DebugInfo/PDB/IPDBSession.h"
#include "llvm/DebugInfo/PDB/IPDBRawSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
#include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"

#if defined(HAVE_DIA_SDK)
#include <Windows.h>
#endif

using namespace llvm;

namespace opts {
cl::list<std::string> InputFilenames(cl::Positional,
                                     cl::desc("<input PDB files>"),
                                     cl::OneOrMore);

cl::opt<bool> Compilands("compilands",
                         cl::desc("Display a list of compilands (e.g. object "
                                  "files) and symbols for each one."));
cl::alias CompilandsShort("c", cl::desc("Alias for --compilands"),
                          cl::aliasopt(Compilands));
}

static void dumpInput(StringRef Path) {
  std::unique_ptr<IPDBSession> Session(
      llvm::createPDBReader(PDB_ReaderType::DIA, Path));
  if (!Session) {
    outs() << "Unable to create PDB reader.  Check that a valid implementation";
    outs() << " is available for your platform.";
    return;
  }

  auto GlobalScope(Session->getGlobalScope());
  GlobalScope->dump(outs(), 0, PDB_DumpLevel::Normal);
  outs().flush();

  if (opts::Compilands) {
    auto Compilands = GlobalScope->findChildren(PDB_SymType::Compiland);
    if (Compilands) {
      while (auto Compiland = Compilands->getNext()) {
        Compiland->dump(outs(), 0, PDB_DumpLevel::Normal);
      }
    }
  }
  outs().flush();
}

int main(int argc_, const char *argv_[]) {
  // Print a stack trace if we signal out.
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc_, argv_);

  SmallVector<const char *, 256> argv;
  llvm::SpecificBumpPtrAllocator<char> ArgAllocator;
  std::error_code EC = llvm::sys::Process::GetArgumentVector(
      argv, llvm::makeArrayRef(argv_, argc_), ArgAllocator);
  if (EC) {
    llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n';
    return 1;
  }

  llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.

  cl::ParseCommandLineOptions(argv.size(), argv.data(), "LLVM PDB Dumper\n");

#if defined(HAVE_DIA_SDK)
  CoInitializeEx(nullptr, COINIT_MULTITHREADED);
#endif

  std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),
                dumpInput);

#if defined(HAVE_DIA_SDK)
  CoUninitialize();
#endif

  return 0;
}
<|endoftext|>


<commit_before>// RUN: %clang_cc1 -verify -std=c++11 %s
// RUN: cp %s %t
// RUN: not %clang_cc1 -x c++ -std=c++11 -fixit %t
// RUN: %clang_cc1 -Wall -pedantic -x c++ -std=c++11 %t

/* This is a test of the various code modification hints that only
   apply in C++0x. */
struct A {
  explicit operator int(); // expected-note{{conversion to integral type}}
};

void x() {
  switch(A()) { // expected-error{{explicit conversion to}}
  }
}

using ::T = void; // expected-error {{name defined in alias declaration must be an identifier}}
using typename U = void; // expected-error {{name defined in alias declaration must be an identifier}}
using typename ::V = void; // expected-error {{name defined in alias declaration must be an identifier}}

namespace SemiCommaTypo {
  int m {},
  n [[]], // expected-error {{expected ';' at end of declaration}}
  int o;

  struct Base {
    virtual void f2(), f3();
  };
  struct MemberDeclarator : Base {
    int k : 4,
        //[[]] : 1, FIXME: test this once we support attributes here
        : 9, // expected-error {{expected ';' at end of declaration}}
    char c, // expected-error {{expected ';' at end of declaration}}
    typedef void F(), // expected-error {{expected ';' at end of declaration}}
    F f1,
      f2 final,
      f3 override, // expected-error {{expected ';' at end of declaration}}
  };
}

namespace ScopedEnum {
  enum class E { a };

  enum class E b = E::a; // expected-error {{must use 'enum' not 'enum class'}}
  struct S {
    friend enum class E; // expected-error {{must use 'enum' not 'enum class'}}
  };
}

struct S2 {
  void f(int i);
  void g(int i);
};

void S2::f(int i) {
  (void)[&, &i, &i]{}; // expected-error 2{{'&' cannot precede a capture when the capture default is '&'}}
  (void)[=, this]{ this->g(5); }; // expected-error{{'this' cannot be explicitly captured}}
  (void)[i, i]{ }; // expected-error{{'i' can appear only once in a capture list}}
  (void)[&, i, i]{ }; // expected-error{{'i' can appear only once in a capture list}}
}
<commit_msg>Tests for the fixits which Doug added in r150727.<commit_after>// RUN: %clang_cc1 -verify -std=c++11 %s
// RUN: cp %s %t
// RUN: not %clang_cc1 -x c++ -std=c++11 -fixit %t
// RUN: %clang_cc1 -Wall -pedantic -x c++ -std=c++11 %t

/* This is a test of the various code modification hints that only
   apply in C++0x. */
struct A {
  explicit operator int(); // expected-note{{conversion to integral type}}
};

void x() {
  switch(A()) { // expected-error{{explicit conversion to}}
  }
}

using ::T = void; // expected-error {{name defined in alias declaration must be an identifier}}
using typename U = void; // expected-error {{name defined in alias declaration must be an identifier}}
using typename ::V = void; // expected-error {{name defined in alias declaration must be an identifier}}

namespace SemiCommaTypo {
  int m {},
  n [[]], // expected-error {{expected ';' at end of declaration}}
  int o;

  struct Base {
    virtual void f2(), f3();
  };
  struct MemberDeclarator : Base {
    int k : 4,
        //[[]] : 1, FIXME: test this once we support attributes here
        : 9, // expected-error {{expected ';' at end of declaration}}
    char c, // expected-error {{expected ';' at end of declaration}}
    typedef void F(), // expected-error {{expected ';' at end of declaration}}
    F f1,
      f2 final,
      f3 override, // expected-error {{expected ';' at end of declaration}}
  };
}

namespace ScopedEnum {
  enum class E { a };

  enum class E b = E::a; // expected-error {{must use 'enum' not 'enum class'}}
  struct S {
    friend enum class E; // expected-error {{must use 'enum' not 'enum class'}}
  };
}

struct S2 {
  void f(int i);
  void g(int i);
};

void S2::f(int i) {
  (void)[&, &i, &i]{}; // expected-error 2{{'&' cannot precede a capture when the capture default is '&'}}
  (void)[=, this]{ this->g(5); }; // expected-error{{'this' cannot be explicitly captured}}
  (void)[i, i]{ }; // expected-error{{'i' can appear only once in a capture list}}
  (void)[&, i, i]{ }; // expected-error{{'i' can appear only once in a capture list}}
  (void)[] mutable { }; // expected-error{{lambda requires '()' before 'mutable'}}
  (void)[] -> int { }; // expected-error{{lambda requires '()' before return type}}
}
<|endoftext|>