Exemple #1
0
int sis_init_context(struct drm_device *dev, int context)
{
	int i;

	for (i = 0; i < MAX_CONTEXT; i++) {
		if (global_ppriv[i].used &&
		    (global_ppriv[i].context == context))
			break;
	}

	if (i >= MAX_CONTEXT) {
		for (i = 0; i < MAX_CONTEXT; i++) {
			if (!global_ppriv[i].used) {
				global_ppriv[i].context = context;
				global_ppriv[i].used = 1;
				global_ppriv[i].sets[0] = setInit();
				global_ppriv[i].sets[1] = setInit();
				DRM_DEBUG("init allocation set, socket=%d, "
					  "context = %d\n", i, context);
				break;
			}
		}
		if ((i >= MAX_CONTEXT) || (global_ppriv[i].sets[0] == NULL) ||
		    (global_ppriv[i].sets[1] == NULL)) {
			return 0;
		}
	}

	return 1;
}
Exemple #2
0
CValve::CValve(string valveName, ubyte pos0Code, ubyte pos1Code) : CMyObject(valveName)
{
	setInit();

	m_pos0Code = pos0Code;
	m_pos1Code = pos1Code;
}
Exemple #3
0
// on "init" you need to initialize your instance
bool Problem::init()
{
	//////////////////////////////
	// 1. super init first
	if (!Layer::init())
	{
		return false;
	}
	this->setName("start");
	Size visibleSize = Director::getInstance()->getVisibleSize();
	Vec2 origin = Director::getInstance()->getVisibleOrigin();

	/////////////////////////////
	// 2. add a menu item with "X" image, which is clicked to quit the program
	//    you may modify it.

	// add a "close" icon to exit the progress. it's an autorelease object
	auto compileItem = MenuItemImage::create(
		"CloseNormal.png",
		"CloseSelected.png",
		CC_CALLBACK_1(Problem::compile, this));

	compileItem->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y + 100));

	// create menu, it's an autorelease object
	auto menu = Menu::create(compileItem, NULL);
	menu->setPosition(Vec2::ZERO);
	this->addChild(menu, 1);

	/////////////////////////////
	// 3. add your codes below...

	// add a label shows "Hello World"
	// create and initialize a label

	auto label = LabelTTF::create("Hello World", "Arial", 24);

	// position the label on the center of the screen
	label->setPosition(Vec2(origin.x + visibleSize.width / 2,
		origin.y + visibleSize.height - label->getContentSize().height));

	// add the label as a child to this layer
	this->addChild(label, 1);

	// add "HelloWorld" splash screen"
	auto sprite = Sprite::create("screen.png");

	// position the sprite on the center of the screen
	sprite->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
	sprite->setName("screen");
	// add the sprite as a child to this layer
	this->addChild(sprite, 0);
	setInit();
	listener = EventListenerKeyboard::create();
	listener->onKeyPressed = CC_CALLBACK_2(Problem::onKeyPress, this);
	listener->onKeyReleased = CC_CALLBACK_2(Problem::onKeyRelease, this);
	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);

	return true;
}
Exemple #4
0
Node<MemberNode>::Link TypeParser::member(Visibility vis, bool isStatic) {
  Trace mbTrace = current().trace;
  auto parsedAsDecl = declaration();
  auto mbNode = Node<MemberNode>::make(parsedAsDecl->getIdentifier(), parsedAsDecl->getTypeInfo().getEvalTypeList(), isStatic, vis == INVALID ? PRIVATE : vis);
  mbNode->setTrace(mbTrace);
  if (parsedAsDecl->getChildren().size() > 0) mbNode->setInit(Node<ExpressionNode>::staticPtrCast(parsedAsDecl->removeChild(0)));
  return mbNode;
}
Exemple #5
0
CValve::CValve(string valveName, ubyte pos0Code, ubyte pos1Code, double coeff) : CMyObject(valveName)
{
	setInit();

	m_pos0Code = pos0Code;
	m_pos1Code = pos1Code;
	m_flowRateCoeff = coeff;
}
Exemple #6
0
void fileObj::initFile(int initSZ) {
    objSize = 0;
    InitSize = 0;
    fileName = new string[initSZ];
    fileID = new int[initSZ];
    filePar = new int[initSZ];
    filePath = new string[initSZ];
    for(int i=0; i< initSZ; i++) {
        setInit(i, 0, 0, "-", "-");
    }
}
Exemple #7
0
Node<DeclarationNode>::Link DeclarationParser::declarationFromTypes(TypeList typeList) {
  Token identToken = current();
  skip();
  auto decl = Node<DeclarationNode>::make(identToken.data, typeList);
  decl->setTrace(identToken.trace);
  // Do initialization only if it exists
  if (accept("=")) {
    skip();
    decl->setInit(expression());
  }
  return decl;
}
Exemple #8
0
void DataStmtEngine::VisitVarExpr(VarExpr *E) {
  if(CheckVar(E))
    return;
  auto VD = E->getVarDecl();
  auto Type = VD->getType();
  if(auto ATy = Type->asArrayType()) {
    uint64_t ArraySize;
    if(!ATy->EvaluateSize(ArraySize, Context)) {
      VisitExpr(E);
      return;
    }

    // Construct an array constructor expression for initializer
    SmallVector<Expr*, 32> Items(ArraySize);
    bool IsUsable = true;
    SourceLocation Loc;
    auto ElementType = ATy->getElementType();
    for(uint64_t I = 0; I < ArraySize; ++I) {
      if(!HasValues(E)) return;
      auto Val = getAndCheckAnyValue(ElementType, E);
      if(Val.isUsable()) {
        Items[I] = Val.get();
        if(!Loc.isValid())
          Loc = Val.get()->getLocation();
      }
      else IsUsable = false;
    }

    if(IsUsable) {
      VD->setInit(ArrayConstructorExpr::Create(Context, Loc,
                                               Items, Type));
    }
    return;
  }

  // single item
  auto Val = getAndCheckAnyValue(Type, E);
  if(Val.isUsable())
    VD->setInit(Val.get());
}
void CoaxVisionControl::StateCallback(const coax_msgs::CoaxState::ConstPtr & msg) {
    static int initTime = 200;
    static int initCounter = 0;

    static Eigen::Vector3f init_acc(0,0,0);
    static Eigen::Vector3f init_gyr(0,0,0);

    battery_voltage = msg->battery;
    coax_nav_mode = msg->mode.navigation;

    //	rpy << msg->roll, msg->pitch, msg->yaw;
    //	std::cout << "RPY: \n" << rpy << std::endl;
    accel << msg->accel[0], msg->accel[1], msg->accel[2];
    gyro << msg->gyro[0], msg->gyro[1], msg->gyro[2];
    rpyt_rc << msg->rcChannel[4], msg->rcChannel[6], msg->rcChannel[2], msg->rcChannel[0];
    rpyt_rc_trim << msg->rcChannel[5], msg->rcChannel[7], msg->rcChannel[3], msg->rcChannel[1];
    range_al = msg->zfiltered;

    global_z = msg->zfiltered;
    if (FIRST_STATE) {
        last_state_time = ros::Time::now().toSec();
        FIRST_STATE = false;
        ROS_INFO("First Time Stamp: %f",last_state_time);
        return;
    }

    if ((battery_voltage < 10.50) && !LOW_POWER_DETECTED) {
        ROS_INFO("Battery Low!!! (%fV) Landing initialized",battery_voltage);
        LOW_POWER_DETECTED = true;
    }

    if (initCounter < initTime) {
        init_acc += accel;
        init_gyr += gyro;
        initCounter++;
    }
    else if (initCounter == initTime) {
        init_acc /= initTime;
        gravity = init_acc.norm();
        setGravity(gravity);
        ROS_INFO("IMU Calibration Done! Gravity: %f", gravity);
        initCounter++;

        setInit(msg->header.stamp);
    }
    else {
        processUpdate(accel, gyro, msg->header.stamp);
        measureUpdate(range_al);
    }
    return;
}
Exemple #10
0
/*******************************************************************************
    initScene
*******************************************************************************/
void SettingsScene::initScene()
{
    // create pages
    m_pages[SETTINGS::GENERAL]   = new PageGeneral(parentView());
    m_pages[SETTINGS::PLAYER]    = new PagePlayer(parentView());
    m_pages[SETTINGS::LIBRARY]   = new PageLibrary(parentView());
    m_pages[SETTINGS::SHORTCUT]  = new PageShortcut(parentView());
    m_pages[SETTINGS::SCROBBLER] = new PageScrobbler(parentView());
    m_pages[SETTINGS::SONGINFO]  = new PageSongInfo(parentView());

    /* first init => always restore settings */
    restore_settings();
    
    /*  layout */
    m_layout    = new QGraphicsLinearLayout(Qt::Vertical);
    m_layout->setSpacing(10);
    m_layout->addItem( m_pages.value(SETTINGS::GENERAL) );
    m_layout->addItem( m_pages.value(SETTINGS::PLAYER) );
    m_layout->addItem( m_pages.value(SETTINGS::LIBRARY) );
    m_layout->addItem( m_pages.value(SETTINGS::SHORTCUT) );
    m_layout->addItem( m_pages.value(SETTINGS::SONGINFO) );
    m_layout->addItem( m_pages.value(SETTINGS::SCROBBLER) );

    m_container = new QGraphicsWidget();
    m_container->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
    m_container->setLayout(m_layout);
    m_container->setPos(0,0);
    this->addItem(m_container);

    /* il faut interdire la modification des parametres de collection si un database builder est en cours */
    connect(ThreadManager::instance(), SIGNAL(dbBuildStart()), this, SLOT(slot_dbBuilder_stateChange()));
    connect(ThreadManager::instance(), SIGNAL(dbBuildFinished()), this, SLOT(slot_dbBuilder_stateChange()));

    connect(Database::instance(), SIGNAL(settingsChanged()), this, SLOT(slot_database_settingsChanged()));
    
    connect(MainLeftWidget::instance(), SIGNAL(dbNameChanged()), this, SLOT(slot_database_settingsChanged()));
    connect(MainLeftWidget::instance(), SIGNAL(settings_save_clicked()), this, SLOT(slot_apply_settings()));
    connect(MainLeftWidget::instance(), SIGNAL(settings_cancel_clicked()), this, SLOT(slot_cancel_settings()));
        
    
    connect(m_pages[SETTINGS::GENERAL], SIGNAL(layout_changed()), this, SLOT(populateScene()));
    connect(m_pages[SETTINGS::PLAYER], SIGNAL(layout_changed()), this, SLOT(populateScene()));
    connect(m_pages[SETTINGS::LIBRARY], SIGNAL(layout_changed()), this, SLOT(populateScene()));
    connect(m_pages[SETTINGS::SHORTCUT], SIGNAL(layout_changed()), this, SLOT(populateScene()));
    connect(m_pages[SETTINGS::SCROBBLER], SIGNAL(layout_changed()), this, SLOT(populateScene()));
    connect(m_pages[SETTINGS::SONGINFO], SIGNAL(layout_changed()), this, SLOT(populateScene()));    
    
    setInit(true);
}
Exemple #11
0
void DataStmtEngine::CreateArrayElementExprInitializer(ArrayElementExpr *E,
                                                       Expr *Parent) {
  auto Target = dyn_cast<VarExpr>(E->getTarget());
  if(!Target)
    return VisitExpr(E);
  if(CheckVar(Target))
    return;

  auto VD = Target->getVarDecl();
  auto ATy = VD->getType()->asArrayType();
  auto ElementType = ATy->getElementType();

  uint64_t ArraySize;
  if(!ATy->EvaluateSize(ArraySize, Context))
    return VisitExpr(E);

  SmallVector<Expr*, 32> Items(ArraySize);
  if(VD->hasInit()) {
    assert(isa<ArrayConstructorExpr>(VD->getInit()));
    auto InsertPoint = cast<ArrayConstructorExpr>(VD->getInit())->getItems();
    for(uint64_t I = 0; I < ArraySize; ++I)
      Items[I] = InsertPoint[I];
  } else {
    for(uint64_t I = 0; I < ArraySize; ++I)
      Items[I] = nullptr;
  }

  uint64_t Offset;
  if(!E->EvaluateOffset(Context, Offset, &ImpliedDoEvaluator))
    return VisitExpr(E);

  ExprResult Val;
  if(Parent) {
    if(auto SE = dyn_cast<SubstringExpr>(Parent)) {
       Val = CreateSubstringExprInitializer(SE, ElementType);
    } else if(auto ME = dyn_cast<MemberExpr>(Parent)) {
      if(Offset < Items.size()) {
        const TypeConstructorExpr *Init = Items[Offset]? cast<TypeConstructorExpr>(Items[Offset]) : nullptr;
        Val = CreateMemberExprInitializer(ME, Init);
      }
    } else llvm_unreachable("invalid expression");
  } else Val = getAndCheckAnyValue(ElementType, E);

  if(Val.isUsable() && Offset < Items.size()) {
    Items[Offset] = Val.get();
    VD->setInit(ArrayConstructorExpr::Create(Context, Val.get()->getLocation(),
                                             Items, VD->getType()));
  }
}
int main() {
	setInit();
	int cas = 0;
	while (init()) {
		if (cas) printf("\n\n\n");
		printf("Layout #%d:\n\n", ++cas);
		for (int i = 0; i < R; i++) {
			for (int j = 0; j < C; j++)
				printf("%4d", g[i][j]);
			printf("\n");
		}

		printf("\nMaps resulting from layout #%d are:\n\n", cas);
		dfs(0, 0, 0);
		printf("There are %d solution(s) for layout #%d.\n", ans, cas);
	}
	return 0;
}
Exemple #13
0
void DataStmtEngine::VisitMemberExpr(MemberExpr *E) {
  if(auto AE = dyn_cast<ArrayElementExpr>(E->getTarget())) {
    CreateArrayElementExprInitializer(AE, E);
    return;
  }

  auto Target = dyn_cast<VarExpr>(E->getTarget());
  if(!Target)
    return VisitExpr(E);
  if(CheckVar(Target))
    return;

  auto VD = Target->getVarDecl();
  const TypeConstructorExpr *Init = VD->hasInit()? cast<TypeConstructorExpr>(VD->getInit()) : nullptr;
  auto Val = CreateMemberExprInitializer(E, Init);
  if(Val.isUsable())
    VD->setInit(Val.get());
}
Exemple #14
0
void DataStmtEngine::VisitSubstringExpr(SubstringExpr *E) {
  if(auto AE = dyn_cast<ArrayElementExpr>(E->getTarget())) {
    CreateArrayElementExprInitializer(AE, E);
    return;
  }

  auto Target = dyn_cast<VarExpr>(E->getTarget());
  if(!Target)
    return VisitExpr(E);
  if(CheckVar(Target))
    return;

  auto VD = Target->getVarDecl();
  auto CharTy = VD->getType().getSelfOrArrayElementType();
  auto Val = CreateSubstringExprInitializer(E, CharTy);
  if(Val.isUsable())
    VD->setInit(Val.get());
}
Exemple #15
0
/*
 * Adds a thread to the HPReord list.
 * hpData - An HPData object created by initHPData
 */
void threadRegister(HPData hpData) {
	int i;
	//init record
	HPRecord* record = (HPRecord*) malloc(sizeof(HPRecord) + (sizeof(void*)
			* hpData->HP_COUNT));
	assert(record != NULL);
	record->next = NULL;
	for (i = 0; i < hpData->HP_COUNT; i++) {
		record->hp[i] = NULL;
	}

	//init thread local struct
	HPLocal res = (HPLocal) malloc(sizeof(HPLocalT));
	assert(res != NULL);

	res->localRecord = record;

	int
			stackSize = hpData->THREAD_COUNT * hpData->HP_COUNT
					> hpData->REC_COUNT ? hpData->THREAD_COUNT
					* hpData->HP_COUNT : hpData->REC_COUNT;

	res->rlist = stackInit(stackSize);
	res->temp = stackInit(stackSize);
	res->plist = setInit(stackSize);
	res->hpData = hpData;

	if (head == NULL && CAS((unsigned long*) ((void*) &head), 0,
			(unsigned long) ((void*) record))) {
		res->HPRecHead = record;
	} else {
		res->HPRecHead = head;
		//add record to list
		while (1) {
			HPRecord* last = head;
			while (last->next != NULL)
				last = last->next;
			if (CAS((unsigned long*) ((void*) &(last->next)), 0,
					(unsigned long) ((void*) record)))
				break;
		}
	}
	localHPData = res;
}
Exemple #16
0
/*******************************************************************************
    initScene
*******************************************************************************/
void SettingsScene::initScene()
{
    // create pages
    m_pages[SETTINGS::GENERAL]   = new PageGeneral(parentView());
    m_pages[SETTINGS::PLAYER]    = new PagePlayer(parentView());
    m_pages[SETTINGS::LIBRARY]   = new PageLibrary(parentView());
    m_pages[SETTINGS::SHORTCUT]  = new PageShortcut(parentView());
    m_pages[SETTINGS::SCROBBLER] = new PageScrobbler(parentView());
    m_pages[SETTINGS::SONGINFO]  = new PageSongInfo(parentView());

    connect(m_pages[SETTINGS::GENERAL], SIGNAL(layout_changed()), this, SLOT(populateScene()));
    connect(m_pages[SETTINGS::PLAYER], SIGNAL(layout_changed()), this, SLOT(populateScene()));
    connect(m_pages[SETTINGS::LIBRARY], SIGNAL(layout_changed()), this, SLOT(populateScene()));
    connect(m_pages[SETTINGS::SHORTCUT], SIGNAL(layout_changed()), this, SLOT(populateScene()));
    connect(m_pages[SETTINGS::SCROBBLER], SIGNAL(layout_changed()), this, SLOT(populateScene()));
    connect(m_pages[SETTINGS::SONGINFO], SIGNAL(layout_changed()), this, SLOT(populateScene()));

    m_header = new HeaderItem(qobject_cast<QGraphicsView*> (parentView())->viewport());
    m_header->setText( tr("Settings") );

    /* bottom widget */
    m_bottomWidget  = new BottomWidget();
    connect(m_bottomWidget, SIGNAL(save_clicked()), this, SLOT(slot_apply_settings()));
    connect(m_bottomWidget, SIGNAL(cancel_clicked()), this, SLOT(slot_cancel_settings()));
    
    
    this->addItem(m_header);
    this->addItem(m_pages.value(SETTINGS::GENERAL));
    this->addItem(m_pages.value(SETTINGS::PLAYER));
    this->addItem(m_pages.value(SETTINGS::LIBRARY));
    this->addItem(m_pages.value(SETTINGS::SHORTCUT));
    this->addItem(m_pages.value(SETTINGS::SCROBBLER));
    this->addItem(m_pages.value(SETTINGS::SONGINFO));

    /* first init => always restore settings */
    restore_settings();

    /* il faut interdire la modification des parametres de collection si un database builder est en cours */
    connect(ThreadManager::instance(), SIGNAL(dbBuildStart()), this, SLOT(slot_dbBuilder_stateChange()));
    connect(ThreadManager::instance(), SIGNAL(dbBuildFinished()), this, SLOT(slot_dbBuilder_stateChange()));
    
    setInit(true);
}
Exemple #17
0
/*******************************************************************************
    initScene
*******************************************************************************/
void FileScene::initScene()
{
    /* init model */
    m_model        = new FileModel(this);
    m_current_path = m_model->rootPath();
 
    /* get folder pixmap */
    QIcon icon = m_model->fileIcon(m_model->index(m_model->rootPath()));
    m_folder_pixmap = icon.pixmap ( QSize(90,90) ,QIcon::Normal, QIcon::On);    

    connect(m_model, SIGNAL(directoryLoaded ( const QString & )), this, SLOT(slot_on_directory_loaded()));

    ACTIONS()->insert(BROWSER_DIR_ITEM_MOUSE_MOVE, new QAction(this));
    connect(ACTIONS()->value(BROWSER_DIR_ITEM_MOUSE_MOVE), SIGNAL(triggered()), this, SLOT(slot_item_mouseMove()));
    
    connect(ACTIONS()->value(BROWSER_UP), SIGNAL(triggered()), this, SLOT(slot_on_go_up()));
    
    loading_directory = false;
    
    setInit(true);
}
Exemple #18
0
// Draw the stats (score and lives) on the screen.
void drawStats(){
	int startRow = STATS_START_ROW;
	int startCol = STATS_START_COL;
	int letterColor = WHITE;
	// Draw the Score
	drawLetter(false, letterColor, startRow, startCol, S_6x5); // Draw S
	startCol += KERNING;
	drawLetter(false, letterColor, startRow, startCol, C_6x5); // Draw C
	startCol += KERNING;
	drawLetter(false, letterColor, startRow, startCol, O_6x5); // Draw O
	startCol += KERNING;
	drawLetter(false, letterColor, startRow, startCol, R_6x5); // Draw R
	startCol += KERNING;
	drawLetter(false, letterColor, startRow, startCol, E_6x5); // Draw E
	startCol = startCol + KERNING + KERNING;
	updateScore();
	startCol += KERNING_CENTRE;

	// Draw the Lives
	drawLetter(false, letterColor, startRow, startCol, L_6x5); // Draw L
	startCol += KERNING;
	drawLetter(false, letterColor, startRow, startCol, I_6x5); // Draw I
	startCol += KERNING_SMALL;
	drawLetter(false, letterColor, startRow, startCol, V_6x5); // Draw V
	startCol += KERNING;
	drawLetter(false, letterColor, startRow, startCol, E_6x5); // Draw E
	startCol += KERNING;
	drawLetter(false, letterColor, startRow, startCol, S_6x5); // Draw S
	startCol = startCol + KERNING + KERNING;
	startRow -= KERNING_SMALL;
	drawTank(true, startRow, startCol);
	startCol += TANK_KERNING;
	drawTank(true, startRow, startCol);
	startCol += TANK_KERNING;
	drawTank(true, startRow, startCol);
	setInit(false);


}
YoonEncryptor::YoonEncryptor(double init, double param, int K){
    setInit(init);
    setParam(param);
    setK(K);
}
Exemple #20
0
ASTNode::Link StatementParser::statement() {
  if (accept(TT::TYPE)) {
    return type();
  } else if (accept(TT::IF)) {
    skip();
    return ifStatement();
  } else if (accept(TT::FOR)) {
    auto loop = Node<LoopNode>::make();
    loop->setTrace(current().trace);
    skip(); // Skip "for"
    loop->setInit(declaration(false));
    expectSemi();
    loop->setCondition(expression(false));
    expectSemi();
    loop->setUpdate(expression(false));
    loop->setCode(block(CODE_BLOCK));
    return loop;
  } if (accept(TT::WHILE)) {
    skip(); // Skip "while"
    auto loop = Node<LoopNode>::make();
    loop->setTrace(current().trace);
    loop->setCondition(expression());
    loop->setCode(block(CODE_BLOCK));
    return loop;
  } else if (accept(TT::DO)) {
    return block(CODE_BLOCK);
  } else if (accept(TT::DEFINE)) {
    auto decl = declaration();
    expectSemi();
    return decl;
  } else if (accept(TT::IDENTIFIER)) {
    skip();
    if (accept(TT::IDENTIFIER) || accept(",")) {
      skip(-1); // Go back to the prev identifier
      auto decl = declaration();
      expectSemi();
      return decl;
    } else {
      skip(-1); // Get the entire expression
      auto e = expression();
      expectSemi();
      return e;
    }
  } else if (accept(TT::BREAK)) {
    skip();
    return Node<BreakLoopNode>::make();
  } else if (accept(TT::CONTINUE)) {
    throw InternalError("Unimplemented", {METADATA_PAIRS, {"token", "loop continue"}});
  } else if (accept(TT::RETURN)) {
    auto trace = current().trace;
    skip(); // Skip "return"
    auto retValue = expression(false);
    expectSemi();
    auto retNode = Node<ReturnNode>::make();
    retNode->setTrace(trace);
    if (retValue != nullptr) retNode->setValue(retValue);
    return retNode;
  } else if (accept(TT::FUNCTION)) {
    return function();
  } else if (accept(TT::FOREIGN)) {
    return function(true);
  } else {
    auto e = expression();
    expectSemi();
    return e;
  }
}
Exemple #21
0
ASTNode::Link XMLParser::parseXMLNode(rapidxml::xml_node<>* node) {
  auto safeAttr = [node](std::string what, std::string defaultValue = "") -> std::string {
    auto attr = node->first_attribute(what.c_str());
    if (attr != nullptr) return attr->value();
    else return defaultValue;
  };
  auto requiredAttr = [node](std::string what) -> std::string {
    auto attr = node->first_attribute(what.c_str());
    if (attr != nullptr) return attr->value();
    else throw XMLParseError("Can't find required attribute", {
      METADATA_PAIRS,
      {"missing attribute", what}
    });
  };
  auto funArgs = [node, &safeAttr]() -> FunctionSignature::Arguments {
    FunctionSignature::Arguments args {};
    std::vector<std::string> stringArgs = split(safeAttr("args"), ',');
    for (auto& arg : stringArgs) {
      std::vector<std::string> namePlusTypes = split(arg, ':');
      std::vector<std::string> types = split(namePlusTypes[1], ' ');
      args.push_back(std::make_pair(namePlusTypes[0], TypeList(ALL(types))));
    }
    return args;
  };
  auto funRet = [node, &safeAttr]() -> TypeInfo {
    std::vector<std::string> returnTypes = split(safeAttr("return"), ' ');
    return returnTypes.size() == 0 ? nullptr : TypeInfo(TypeList(ALL(returnTypes)));
  };
  auto funBlock = [=](Node<FunctionNode>::Link f) {
    if (!f->isForeign()) {
      auto codeBlock = node->first_node("block");
      if (codeBlock == nullptr) throw XMLParseError("Method missing code block", {METADATA_PAIRS});
      f->setCode(Node<BlockNode>::staticPtrCast(parseXMLNode(codeBlock)));
    }
  };
  auto getVisibility = [node, &safeAttr]() -> Visibility {
    return fromString(safeAttr("visibility", "private"));
  };
  auto boolAttr = [node, &safeAttr](std::string what) -> bool {
    return safeAttr(what, "false") == "true";
  };

  if (node == nullptr) throw XMLParseError("Null node", {METADATA_PAIRS});
  std::string name = node->name();
  if (name == "block") {
    std::string type = safeAttr("type", "code");
    BlockType bt =
      type == "root" ? ROOT_BLOCK :
      type == "if" ? IF_BLOCK :
      type == "function" ? FUNCTION_BLOCK : CODE_BLOCK;
    auto block = Node<BlockNode>::make(bt);
    parseChildren(node, block);
    return block;
  } else if (name == "return") {
    auto retNode = Node<ReturnNode>::make();
    auto val = node->first_node("expr");
    if (val != nullptr) retNode->setValue(Node<ExpressionNode>::dynPtrCast(parseXMLNode(val)));
    return retNode;
  } else if (name == "expr") {
    TokenType tokenType = TT::findByPrettyName(requiredAttr("type"));
    std::string data = requiredAttr("value");
    std::unique_ptr<Token> content;
    if (tokenType == TT::OPERATOR) {
      content = std::make_unique<Token>(tokenType, Operator::find(data), defaultTrace);
    } else {
      content = std::make_unique<Token>(tokenType, data, defaultTrace);
    }
    auto expr = Node<ExpressionNode>::make(*content);
    parseChildren(node, expr);
    return expr;
  } else if (name == "decl") {
    Node<DeclarationNode>::Link decl;
    std::string ident = requiredAttr("ident");
    bool isDynamic = boolAttr("dynamic");
    if (isDynamic) {
      decl = Node<DeclarationNode>::make(ident, TypeList {});
    } else {
      std::string tlValue = requiredAttr("types");
      auto vec = split(tlValue, ' ');
      decl = Node<DeclarationNode>::make(ident, TypeList(ALL(vec)));
    }
    auto expr = node->first_node("expr");
    if (expr != nullptr) {
      decl->setInit(Node<ExpressionNode>::dynPtrCast(parseXMLNode(expr)));
    }
    return decl;
  } else if (name == "branch") {
    auto branch = Node<BranchNode>::make();
    auto cond = node->first_node();
    if (cond == nullptr) throw XMLParseError("Missing condition in branch", {METADATA_PAIRS});
    branch->setCondition(Node<ExpressionNode>::dynPtrCast(parseXMLNode(cond)));
    auto success = cond->next_sibling();
    if (success == nullptr) throw XMLParseError("Missing success node in branch", {METADATA_PAIRS});
    branch->setSuccessBlock(Node<BlockNode>::dynPtrCast(parseXMLNode(success)));
    auto blockFailiure = success->next_sibling("block");
    if (blockFailiure != nullptr) {
      branch->setFailiureBlock(Node<BlockNode>::dynPtrCast(parseXMLNode(blockFailiure)));
    }
    auto branchFailiure = success->next_sibling("branch");
    if (branchFailiure != nullptr) {
      branch->setFailiureBlock(Node<BranchNode>::dynPtrCast(parseXMLNode(branchFailiure)));
    }
    return branch;
  } else if (name == "loop") {
    auto loop = Node<LoopNode>::make();
    auto init = node->first_node("loop_init");
    if (init != nullptr) {
      loop->setInit(Node<DeclarationNode>::dynPtrCast(parseXMLNode(init)));
    }
    auto cond = node->first_node("loop_condition");
    if (cond != nullptr) {
      loop->setCondition(Node<ExpressionNode>::dynPtrCast(parseXMLNode(cond)));
    }
    auto update = node->first_node("loop_update");
    if (update != nullptr) {
      loop->setUpdate(Node<ExpressionNode>::dynPtrCast(parseXMLNode(update)));
    }
    auto code = node->first_node("block");
    if (code != nullptr) {
      loop->setCode(Node<BlockNode>::dynPtrCast(parseXMLNode(code)));
    }
    return loop;
  } else if (name == "loop_init" || name == "loop_condition" || name == "loop_update") {
    return parseXMLNode(node->first_node());
  } else if (name == "break") {
    return Node<BreakLoopNode>::make();
  } else if (name == "function") {
    std::string ident = safeAttr("ident");
    bool isForeign = boolAttr("foreign");
    auto n = Node<FunctionNode>::make(ident, FunctionSignature(funRet(), funArgs()), isForeign);
    funBlock(n);
    if (isForeign && ident.empty()) throw XMLParseError("Can't have anonymous foreign function", {METADATA_PAIRS});
    return n;
  } else if (name == "type") {
    std::string typeName = requiredAttr("name");
    std::vector<std::string> inheritTypes = split(safeAttr("inherits"), ' ');
    auto typeNode = Node<TypeNode>::make(typeName, TypeList(ALL(inheritTypes)));
    parseChildren(node, typeNode);
    return typeNode;
  } else if (name == "member") {
    std::string ident = requiredAttr("ident");
    std::vector<std::string> types = split(safeAttr("types"), ' ');
    auto member = Node<MemberNode>::make(ident, TypeList(ALL(types)), boolAttr("static"), getVisibility());
    auto init = node->first_node("expr");
    if (init != nullptr) {
      member->setInit(Node<ExpressionNode>::staticPtrCast(parseXMLNode(init)));
    }
    return member;
  } else if (name == "method") {
    std::string ident = safeAttr("ident");
    bool isForeign = boolAttr("foreign");
    auto method = Node<MethodNode>::make(ident, FunctionSignature(funRet(), funArgs()), getVisibility(), boolAttr("static"), isForeign);
    funBlock(method);
    if (isForeign && ident.empty()) throw XMLParseError("Can't have anonymous foreign method", {METADATA_PAIRS});
    return method;
  } else if (name == "constructor") {
    auto constructor = Node<ConstructorNode>::make(funArgs(), getVisibility());
    funBlock(constructor);
    return constructor;
  }
  throw XMLParseError("Unknown type of node", {METADATA_PAIRS, {"node name", name}});
}
Exemple #22
0
CValve::CValve() :CMyObject()
{
	setInit();
}
Exemple #23
0
CValve::CValve(string valveName) : CMyObject(valveName)
{
	setInit();
}