Esempio n. 1
0
int DeclarationName::compare(DeclarationName LHS, DeclarationName RHS) {
  if (LHS.getNameKind() != RHS.getNameKind())
    return (LHS.getNameKind() < RHS.getNameKind() ? -1 : 1);
  
  switch (LHS.getNameKind()) {
  case DeclarationName::Identifier: {
    IdentifierInfo *LII = LHS.getAsIdentifierInfo();
    IdentifierInfo *RII = RHS.getAsIdentifierInfo();
    if (!LII) return RII ? -1 : 0;
    if (!RII) return 1;
    
    return LII->getName().compare(RII->getName());
  }

  case DeclarationName::ObjCZeroArgSelector:
  case DeclarationName::ObjCOneArgSelector:
  case DeclarationName::ObjCMultiArgSelector: {
    Selector LHSSelector = LHS.getObjCSelector();
    Selector RHSSelector = RHS.getObjCSelector();
    unsigned LN = LHSSelector.getNumArgs(), RN = RHSSelector.getNumArgs();
    for (unsigned I = 0, N = std::min(LN, RN); I != N; ++I) {
      switch (LHSSelector.getNameForSlot(I).compare(
                                               RHSSelector.getNameForSlot(I))) {
      case -1: return true;
      case 1: return false;
      default: break;
      }
    }

    return compareInt(LN, RN);
  }
  
  case DeclarationName::CXXConstructorName:
  case DeclarationName::CXXDestructorName:
  case DeclarationName::CXXConversionFunctionName:
    if (QualTypeOrdering()(LHS.getCXXNameType(), RHS.getCXXNameType()))
      return -1;
    if (QualTypeOrdering()(RHS.getCXXNameType(), LHS.getCXXNameType()))
      return 1;
    return 0;
              
  case DeclarationName::CXXOperatorName:
    return compareInt(LHS.getCXXOverloadedOperator(),
                      RHS.getCXXOverloadedOperator());

  case DeclarationName::CXXLiteralOperatorName:
    return LHS.getCXXLiteralIdentifier()->getName().compare(
                                   RHS.getCXXLiteralIdentifier()->getName());
              
  case DeclarationName::CXXUsingDirective:
    return 0;
  }

  llvm_unreachable("Invalid DeclarationName Kind!");
}
Esempio n. 2
0
// Selection test
void MD5Surface::testSelect(Selector& selector,
							SelectionTest& test,
							const Matrix4& localToWorld)
{
	test.BeginMesh(localToWorld);

	SelectionIntersection best;
	test.TestTriangles(
	  vertexpointer_arbitrarymeshvertex(_vertices.data()),
	  IndexPointer(_indices.data(), IndexPointer::index_type(_indices.size())),
	  best
	);

	if(best.valid()) {
		selector.addIntersection(best);
	}
}
Esempio n. 3
0
// ICI l'id du client correspond a l'id du client auquel on veut envoyer les bails
void		TCPWinServSocket::SendData(CircularBuff &circbuff, Selector &sel)
{
	std::vector<Message>		&to_send = circbuff.get_data();
	DWORD						sentbytes;
	WSABUF						databuf[3];
	char						first_buff[4];
	char						second_buff[4];
	char						third_buff[256];

	databuf[0].len = 4;
	databuf[0].buf = first_buff;
	databuf[1].len = 4;
	databuf[1].buf = second_buff;
	databuf[2].len = 256;
	databuf[2].buf = third_buff;

	//pour tous les messages
	for (size_t i = 0; i < to_send.size(); i++)
	if (sel.Is_writable(to_send.at(i).get_client().get_socket()))
	{
		//reset des buffers
		memset(&first_buff, '\0', 4);
		memset(&second_buff, '\0', 4);
		memset(&third_buff, '\0', 256);

		// on crée des variables parce qu'on a besoin d'une adresse pour memcpy (donc juste des getters ca suffit pas)
		int		rq_type = to_send.at(i).get_rq_type();
		int		data_length = to_send.at(i).get_data_length();

		//on rempli nos 3 buffers
		memcpy(&first_buff, (char *)&(rq_type), 4);
		memcpy(&second_buff, (char *)&(data_length), 4);
		memcpy(&third_buff, to_send.at(i).get_packet(), data_length);

		// et on les envoi
		WSASend(to_send.at(i).get_client().get_socket(), databuf, 3, &sentbytes, 0, NULL, NULL);
		delete[]	to_send.at(i).get_packet();
	}
	else
		std::cerr << "Corruption possible (1)" << std::endl;
	to_send.clear();
}
Esempio n. 4
0
// ICI l'id du client correspond a l'id du client auquel on veut envoyer les bails
void		TCPLinServSocket::SendData(CircularBuff &circbuff, Selector &sel)
{
	std::vector<Message>		&to_send = circbuff.get_data();
	struct iovec				databuf[3];
	char						first_buff[4];
	char						second_buff[4];
	char						third_buff[256];
	int							sentbytes = 0;
		
	databuf[0].iov_len = 4;
	databuf[0].iov_base = first_buff;
	databuf[1].iov_len = 4;
	databuf[1].iov_base = second_buff;
	databuf[2].iov_len = 256;
	databuf[2].iov_base = third_buff;

	//pour tous les messages
	for (size_t i = 0; i < to_send.size(); i++)
		if (sel.Is_writable(to_send.at(i).get_client().get_socket()))
		{
			//reset des buffers
			memset(&first_buff, '\0', 4);
			memset(&second_buff, '\0', 4);
			memset(&third_buff, '\0', 256);

			// on crée des variables parce qu'on a besoin d'une
			//adresse pour memcpy (donc juste des getters ca suffit pas)
			int		rq_type = to_send.at(i).get_rq_type();
			int		data_length = to_send.at(i).get_data_length();

			//on rempli nos 3 buffers
			memcpy(&first_buff, (char *)&(rq_type), 4);
			memcpy(&second_buff, (char *)&(data_length), 4);
			memcpy(&third_buff, to_send.at(i).get_packet(), data_length);

			// et on les envoi
			sentbytes = writev(to_send.at(i).get_client().get_socket(), databuf, 3);
			delete[]	to_send.at(i).get_packet();
		}
	to_send.clear();
}
Esempio n. 5
0
void ODRHash::AddDeclarationName(DeclarationName Name) {
  AddBoolean(Name.isEmpty());
  if (Name.isEmpty())
    return;

  auto Kind = Name.getNameKind();
  ID.AddInteger(Kind);
  switch (Kind) {
  case DeclarationName::Identifier:
    AddIdentifierInfo(Name.getAsIdentifierInfo());
    break;
  case DeclarationName::ObjCZeroArgSelector:
  case DeclarationName::ObjCOneArgSelector:
  case DeclarationName::ObjCMultiArgSelector: {
    Selector S = Name.getObjCSelector();
    AddBoolean(S.isNull());
    AddBoolean(S.isKeywordSelector());
    AddBoolean(S.isUnarySelector());
    unsigned NumArgs = S.getNumArgs();
    for (unsigned i = 0; i < NumArgs; ++i) {
      AddIdentifierInfo(S.getIdentifierInfoForSlot(i));
    }
    break;
  }
  case DeclarationName::CXXConstructorName:
  case DeclarationName::CXXDestructorName:
    AddQualType(Name.getCXXNameType());
    break;
  case DeclarationName::CXXOperatorName:
    ID.AddInteger(Name.getCXXOverloadedOperator());
    break;
  case DeclarationName::CXXLiteralOperatorName:
    AddIdentifierInfo(Name.getCXXLiteralIdentifier());
    break;
  case DeclarationName::CXXConversionFunctionName:
    AddQualType(Name.getCXXNameType());
    break;
  case DeclarationName::CXXUsingDirective:
    break;
  case DeclarationName::CXXDeductionGuideName: {
    auto *Template = Name.getCXXDeductionGuideTemplate();
    AddBoolean(Template);
    if (Template) {
      AddDecl(Template);
    }
  }
  }
}
Esempio n. 6
0
/// \brief Get a GlobalSelector for the ASTContext-specific selector.
GlobalSelector GlobalSelector::get(Selector Sel, Program &Prog) {
  if (Sel.isNull())
    return GlobalSelector();

  ProgramImpl &ProgImpl = *static_cast<ProgramImpl*>(Prog.Impl);

  llvm::SmallVector<IdentifierInfo *, 8> Ids;
  for (unsigned i = 0, e = Sel.isUnarySelector() ? 1 : Sel.getNumArgs();
         i != e; ++i) {
    IdentifierInfo *II = Sel.getIdentifierInfoForSlot(i);
    IdentifierInfo *GlobII = &ProgImpl.getIdents().get(II->getName(),
                                               II->getName() + II->getLength());
    Ids.push_back(GlobII);
  }

  Selector GlobSel = ProgImpl.getSelectors().getSelector(Sel.getNumArgs(),
                                                         Ids.data());
  return GlobalSelector(GlobSel.getAsOpaquePtr());
}
Esempio n. 7
0
cocoa::NamingConvention cocoa::deriveNamingConvention(Selector S) {
  switch (S.getMethodFamily()) {
  case OMF_None:
  case OMF_autorelease:
  case OMF_dealloc:
  case OMF_release:
  case OMF_retain:
  case OMF_retainCount:
    return NoConvention;

  case OMF_init:
    return InitRule;

  case OMF_alloc:
  case OMF_copy:
  case OMF_mutableCopy:
  case OMF_new:
    return CreateRule;
  }
  llvm_unreachable("unexpected naming convention");
  return NoConvention;
}
// Perform selection test for this surface
void RenderablePicoSurface::testSelect(Selector& selector,
									   SelectionTest& test,
									   const Matrix4& localToWorld) const
{
	if (!_vertices.empty() && !_indices.empty())
	{
		// Test for triangle selection
		test.BeginMesh(localToWorld);
		SelectionIntersection result;

		test.TestTriangles(
			VertexPointer(&_vertices[0].vertex, sizeof(ArbitraryMeshVertex)),
      		IndexPointer(&_indices[0],
      					 IndexPointer::index_type(_indices.size())),
			result
		);

		// Add the intersection to the selector if it is valid
		if(result.valid()) {
			selector.addIntersection(result);
		}
	}
}
  void BLSSS::draw_beta() {
    Selector g = m_->coef().inc();
    if(g.nvars() == 0) {
      m_->drop_all();
      return;
    }
    SpdMatrix ivar = g.select(pri_->siginv());
    Vector ivar_mu = ivar * g.select(pri_->mu());
    ivar += g.select(suf().xtx());
    ivar_mu += g.select(suf().xty());
    Vector b = ivar.solve(ivar_mu);
    b = rmvn_ivar_mt(rng(), b, ivar);

    // If model selection is turned off and some elements of beta
    // happen to be zero (because, e.g., of a failed MH step) we don't
    // want the dimension of beta to change.
    m_->set_included_coefficients(b, g);
  }
Esempio n. 10
0
  void BLSSS::draw_beta() {
    Selector g = model_->coef().inc();
    if (g.nvars() == 0) {
      model_->drop_all();
      return;
    }
    SpdMatrix precision = g.select(slab_->siginv());
    Vector scaled_mean = precision * g.select(slab_->mu());
    precision += g.select(suf().xtx());
    Cholesky precision_cholesky_factor(precision);
    scaled_mean += g.select(suf().xty());
    Vector posterior_mean = precision_cholesky_factor.solve(scaled_mean);
    Vector beta = rmvn_precision_upper_cholesky_mt(
        rng(), posterior_mean, precision_cholesky_factor.getLT());

    // If model selection is turned off and some elements of beta
    // happen to be zero (because, e.g., of a failed MH step) we don't
    // want the dimension of beta to change.
    model_->set_included_coefficients(beta, g);
  }
Esempio n. 11
0
Specificity Wt::Render::Match::isMatch(const Block* block, const Selector& selector)
{
  if(!selector.size())
    return Specificity(false);

  if(!isMatch(block, selector.at(selector.size()-1)))
    return Specificity(false);
  const Block* parent = block->parent();
  for(int i = selector.size()-2; i >= 0; --i)
  {
    bool matchFound;
    while(parent)
    {
      matchFound = isMatch(parent, selector.at(i));
      parent = parent->parent();
      if(matchFound)
        break;
    }

    if(!matchFound && !parent)
      return Specificity(false);
  }
  return selector.specificity();
}
Esempio n. 12
0
void EventTest::Func2( uint32_t p1, uint16_t p2 )
{
	TRACE_BEGIN( LOG_LVL_INFO );
	mSelector->sendEventSync( jh_new Event2( p1, p2 ) );
}
Esempio n. 13
0
void EventTest::Func1()
{
	TRACE_BEGIN( LOG_LVL_INFO );
	mSelector->sendEvent( jh_new Event1() );
}
Esempio n. 14
0
bool
VanillaProc::JobReaper(int pid, int status)
{
	dprintf(D_FULLDEBUG,"Inside VanillaProc::JobReaper()\n");

	//
	// Run all the reapers first, since some of them change the exit status.
	//
	if( m_pid_ns_status_filename.length() > 0 ) {
		status = pidNameSpaceReaper( status );
	}
	bool jobExited = OsProc::JobReaper( pid, status );
	if( pid != JobPid ) { return jobExited; }

#if defined(LINUX)
	// On newer kernels if memory.use_hierarchy==1, then we cannot disable
	// the OOM killer.  Hence, we have to be ready for a SIGKILL to be delivered
	// by the kernel at the same time we get the notification.  Hence, if we
	// see an exit signal, we must also check the event file descriptor.
	//
	// outOfMemoryEvent() is aware of checkpointing and will mention that
	// the OOM event happened during a checkpoint.
	int efd = -1;
	if( (m_oom_efd >= 0) && daemonCore->Get_Pipe_FD(m_oom_efd, &efd) && (efd != -1) ) {
		Selector selector;
		selector.add_fd(efd, Selector::IO_READ);
		selector.set_timeout(0);
		selector.execute();
		if( !selector.failed() && !selector.timed_out() && selector.has_ready() && selector.fd_ready(efd, Selector::IO_READ) ) {
			outOfMemoryEvent( m_oom_efd );
		}
	}
#endif

	//
	// We have three cases to consider:
	//   * if we're checkpointing; or
	//   * if we see a special checkpoint exit code; or
	//   * there's no special case to consider.
	//

	bool wantsFileTransferOnCheckpointExit = false;
	JobAd->LookupBool( ATTR_WANT_FT_ON_CHECKPOINT, wantsFileTransferOnCheckpointExit );

	int checkpointExitCode = 0;
	JobAd->LookupInteger( ATTR_CHECKPOINT_EXIT_CODE, checkpointExitCode );
	int checkpointExitSignal = 0;
	JobAd->LookupInteger( ATTR_CHECKPOINT_EXIT_SIGNAL, checkpointExitSignal );
	bool checkpointExitBySignal = 0;
	JobAd->LookupBool( ATTR_CHECKPOINT_EXIT_BY_SIGNAL, checkpointExitBySignal );

	int successfulCheckpointStatus = 0;
	if( checkpointExitBySignal ) {
		successfulCheckpointStatus = checkpointExitSignal;
	} else if( checkpointExitCode != 0 ) {
		successfulCheckpointStatus = checkpointExitCode << 8;
#if defined( WINDOWS )
		successfulCheckpointStatus = checkpointExitCode;
#endif
	}

	if( isCheckpointing ) {
		dprintf( D_FULLDEBUG, "Inside VanillaProc::JobReaper() during a checkpoint\n" );

		if( exit_status == successfulCheckpointStatus ) {
			if( isSoftKilling ) {
				notifySuccessfulEvictionCheckpoint();
				return true;
			}

			restartCheckpointedJob();
			isCheckpointing = false;
			return false;
		} else {
			// The job exited without taking a checkpoint.  If we don't do
			// anything, it will be reported as if the error code or signal
			// had happened naturally (and the job will usually exit the
			// queue).  This could confuse the users.
			//
			// Instead, we'll put the job on hold, figuring that if the job
			// requested that we (periodically) send it a signal, and we
			// did, that it's not our fault that the job failed.  This has
			// the convenient side-effect of not overwriting the job's
			// previous checkpoint(s), if any (since file transfer doesn't
			// occur when the job goes on hold).
			killFamilyIfWarranted();
			recordFinalUsage();

			std::string holdMessage;
			formatstr( holdMessage, "Job did not exit as promised when sent its checkpoint signal.  "
				"Promised exit was %s %u, actual exit status was %s %u.",
				checkpointExitBySignal ? "on signal" : "with exit code",
				checkpointExitBySignal ? checkpointExitSignal : checkpointExitCode,
				WIFSIGNALED( exit_status ) ? "on signal" : "with exit code",
				WIFSIGNALED( exit_status ) ? WTERMSIG( exit_status ) : WEXITSTATUS( exit_status ) );
			Starter->jic->holdJob( holdMessage.c_str(), CONDOR_HOLD_CODE_FailedToCheckpoint, exit_status );
			Starter->Hold();
			return true;
		}
	} else if( wantsFileTransferOnCheckpointExit && exit_status == successfulCheckpointStatus ) {
		dprintf( D_FULLDEBUG, "Inside VanillaProc::JobReaper() and the job self-checkpointed.\n" );

		if( isSoftKilling ) {
			notifySuccessfulEvictionCheckpoint();
			return true;
		} else {
			restartCheckpointedJob();
			return false;
		}
	} else {
		// If the parent job process died, clean up all of the job's processes.
		killFamilyIfWarranted();

		// Record final usage stats for this process family, since
		// once the reaper returns, the family is no longer
		// registered with DaemonCore and we'll never be able to
		// get this information again.
		recordFinalUsage();

		return jobExited;
	}
}
Esempio n. 15
0
int main(int argc, char** argv)
{
    LBCHECK(co::init(argc, argv));

    co::ConnectionDescriptionPtr description = new co::ConnectionDescription;
    description->type = co::CONNECTIONTYPE_TCPIP;
    description->port = 4242;

    bool isClient = true;
    bool useThreads = false;
    size_t packetSize = 1048576;
    size_t nPackets = 0xffffffffu;
    uint32_t waitTime = 0;

    try // command line parsing
    {
        po::options_description options(
            "netperf - Collage network benchmark tool " +
            co::Version::getString());

        std::string clientString("");
        std::string serverString("");
        bool showHelp(false);

        options.add_options()("help,h",
                              po::bool_switch(&showHelp)->default_value(false),
                              "show help message")(
            "client,c", po::value<std::string>(&clientString),
            "run as client, format IP[:port][:protocol]")(
            "server,s", po::value<std::string>(&serverString),
            "run as server, format IP[:port][:protocol]")(
            "threaded,t", po::bool_switch(&useThreads)->default_value(false),
            "Run each receive in a separate thread (server only)")(
            "packetSize,p", po::value<std::size_t>(&packetSize),
            "packet size")("numPackets,n", po::value<std::size_t>(&nPackets),
                           "number of packets to send, unsigned int")(
            "wait,w", po::value<uint32_t>(&waitTime),
            "wait time (ms) between sends (client only)")(
            "delay,d", po::value<uint32_t>(&_delay),
            "wait time (ms) between receives (server only");

        // parse program options
        po::variables_map variableMap;
        po::store(po::command_line_parser(argc, argv)
                      .options(options)
                      .allow_unregistered()
                      .run(),
                  variableMap);
        po::notify(variableMap);

        // evaluate parsed arguments
        if (showHelp)
        {
            std::cout << options << std::endl;
            co::exit();
            return EXIT_SUCCESS;
        }

        if (variableMap.count("client") == 1)
            description->fromString(clientString);
        else if (variableMap.count("server") == 1)
        {
            isClient = false;
            description->fromString(serverString);
        }
    }
    catch (std::exception& exception)
    {
        std::cerr << "Command line parse error: " << exception.what()
                  << std::endl;
        co::exit();
        return EXIT_FAILURE;
    }

    // run
    co::ConnectionPtr connection = co::Connection::create(description);
    if (!connection)
    {
        LBWARN << "Unsupported connection: " << description << std::endl;
        co::exit();
        return EXIT_FAILURE;
    }

    Selector* selector = 0;
    if (isClient)
    {
        if (description->type == co::CONNECTIONTYPE_RSP)
        {
            selector = new Selector(connection, packetSize, useThreads);
            selector->start();
        }
        else if (!connection->connect())
            ::exit(EXIT_FAILURE);

        lunchbox::Buffer<uint8_t> buffer;
        buffer.resize(packetSize);
        for (size_t i = 0; i < packetSize; ++i)
            buffer[i] = static_cast<uint8_t>(i);

        const float mBytesSec = buffer.getSize() / 1024.0f / 1024.0f * 1000.0f;
        lunchbox::Clock clock;
        size_t lastOutput = nPackets;

        clock.reset();
        while (nPackets--)
        {
            buffer[SEQUENCE] = uint8_t(nPackets);
            LBCHECK(connection->send(buffer.getData(), buffer.getSize()));
            const float time = clock.getTimef();
            if (time > 1000.f)
            {
                const lunchbox::ScopedWrite mutex(_mutexPrint);
                const size_t nSamples = lastOutput - nPackets;
                std::cerr << "Send perf: " << mBytesSec / time * nSamples
                          << "MB/s (" << nSamples / time * 1000.f << "pps)"
                          << std::endl;

                lastOutput = nPackets;
                clock.reset();
            }
            if (waitTime > 0)
                lunchbox::sleep(waitTime);
        }
        const float time = clock.getTimef();
        const size_t nSamples = lastOutput - nPackets;
        if (nSamples != 0)
        {
            const lunchbox::ScopedWrite mutex(_mutexPrint);
            std::cerr << "Send perf: " << mBytesSec / time * nSamples
                      << "MB/s (" << nSamples / time * 1000.f << "pps)"
                      << std::endl;
        }
        if (selector)
        {
            connection->close();
            selector->join();
        }
    }
    else
    {
        selector = new Selector(connection, packetSize, useThreads);
        selector->start();

        LBASSERTINFO(connection->getRefCount() >= 1, connection->getRefCount());

        if (selector)
            selector->join();
    }

    delete selector;
    LBASSERTINFO(connection->getRefCount() == 1, connection->getRefCount());
    connection = 0;
    LBCHECK(co::exit());
    return EXIT_SUCCESS;
}
void NilArgChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
                                        CheckerContext &C) const {
  const ObjCInterfaceDecl *ID = msg.getReceiverInterface();
  if (!ID)
    return;

  FoundationClass Class = findKnownClass(ID);

  static const unsigned InvalidArgIndex = UINT_MAX;
  unsigned Arg = InvalidArgIndex;
  bool CanBeSubscript = false;

  if (Class == FC_NSString) {
    Selector S = msg.getSelector();

    if (S.isUnarySelector())
      return;

    if (StringSelectors.empty()) {
      ASTContext &Ctx = C.getASTContext();
      Selector Sels[] = {
        getKeywordSelector(Ctx, "caseInsensitiveCompare", nullptr),
        getKeywordSelector(Ctx, "compare", nullptr),
        getKeywordSelector(Ctx, "compare", "options", nullptr),
        getKeywordSelector(Ctx, "compare", "options", "range", nullptr),
        getKeywordSelector(Ctx, "compare", "options", "range", "locale",
                           nullptr),
        getKeywordSelector(Ctx, "componentsSeparatedByCharactersInSet",
                           nullptr),
        getKeywordSelector(Ctx, "initWithFormat",
                           nullptr),
        getKeywordSelector(Ctx, "localizedCaseInsensitiveCompare", nullptr),
        getKeywordSelector(Ctx, "localizedCompare", nullptr),
        getKeywordSelector(Ctx, "localizedStandardCompare", nullptr),
      };
      for (Selector KnownSel : Sels)
        StringSelectors[KnownSel] = 0;
    }
    auto I = StringSelectors.find(S);
    if (I == StringSelectors.end())
      return;
    Arg = I->second;
  } else if (Class == FC_NSArray) {
    Selector S = msg.getSelector();

    if (S.isUnarySelector())
      return;

    if (ArrayWithObjectSel.isNull()) {
      ASTContext &Ctx = C.getASTContext();
      ArrayWithObjectSel = getKeywordSelector(Ctx, "arrayWithObject", nullptr);
      AddObjectSel = getKeywordSelector(Ctx, "addObject", nullptr);
      InsertObjectAtIndexSel =
        getKeywordSelector(Ctx, "insertObject", "atIndex", nullptr);
      ReplaceObjectAtIndexWithObjectSel =
        getKeywordSelector(Ctx, "replaceObjectAtIndex", "withObject", nullptr);
      SetObjectAtIndexedSubscriptSel =
        getKeywordSelector(Ctx, "setObject", "atIndexedSubscript", nullptr);
      ArrayByAddingObjectSel =
        getKeywordSelector(Ctx, "arrayByAddingObject", nullptr);
    }

    if (S == ArrayWithObjectSel || S == AddObjectSel ||
        S == InsertObjectAtIndexSel || S == ArrayByAddingObjectSel) {
      Arg = 0;
    } else if (S == SetObjectAtIndexedSubscriptSel) {
      Arg = 0;
      CanBeSubscript = true;
    } else if (S == ReplaceObjectAtIndexWithObjectSel) {
      Arg = 1;
    }
  } else if (Class == FC_NSDictionary) {
    Selector S = msg.getSelector();

    if (S.isUnarySelector())
      return;

    if (DictionaryWithObjectForKeySel.isNull()) {
      ASTContext &Ctx = C.getASTContext();
      DictionaryWithObjectForKeySel =
        getKeywordSelector(Ctx, "dictionaryWithObject", "forKey", nullptr);
      SetObjectForKeySel =
        getKeywordSelector(Ctx, "setObject", "forKey", nullptr);
      SetObjectForKeyedSubscriptSel =
        getKeywordSelector(Ctx, "setObject", "forKeyedSubscript", nullptr);
      RemoveObjectForKeySel =
        getKeywordSelector(Ctx, "removeObjectForKey", nullptr);
    }

    if (S == DictionaryWithObjectForKeySel || S == SetObjectForKeySel) {
      Arg = 0;
      warnIfNilArg(C, msg, /* Arg */1, Class);
    } else if (S == SetObjectForKeyedSubscriptSel) {
      CanBeSubscript = true;
      Arg = 0;
      warnIfNilArg(C, msg, /* Arg */1, Class, CanBeSubscript);
    } else if (S == RemoveObjectForKeySel) {
      Arg = 0;
    }
  }

  // If argument is '0', report a warning.
  if ((Arg != InvalidArgIndex))
    warnIfNilArg(C, msg, Arg, Class, CanBeSubscript);
}
Esempio n. 17
0
void run_bt(Agent* BT_AGENT, bool bt_seq, bool bt_prio)
{
    Action_right* action_right  = new Action_right(1);
    Action_down* action_down    = new Action_down(1);
    Action_left* action_left    = new Action_left(1);

    if(bt_seq)
    {
    // Structure
    Selector* root = new Selector;
    Sequence* sequence1 = new Sequence;
    Sequence* sequence2 = new Sequence;
    Sequence* sequence3 = new Sequence;

    Less_than* condition_1 = new Less_than(7, &BT_AGENT->pos.y);

    Less_than* condition_21 = new Less_than(4,&BT_AGENT->pos.x);
    Less_than* condition_22 = new Less_than(9,&BT_AGENT->pos.y);

    Equal_to* condition_31 = new Equal_to(9, &BT_AGENT->pos.y);
    Less_than* condition_32 = new Less_than(5, &BT_AGENT->pos.x);



    // Building the Tree
    root->addChild(sequence1);
    root->addChild(sequence2);
    root->addChild(sequence3);
    root->addChild(action_left);

    sequence1->addChild(condition_1);
    sequence1->addChild(action_right);

    sequence2->addChild(condition_21);
    sequence2->addChild(condition_22);
    sequence2->addChild(action_right);

    sequence3->addChild(condition_31);
    sequence3->addChild(condition_32);
    sequence3->addChild(action_down);

    // Initialisation Agent
    //BT_AGENT->setSteps(30);
    BT_AGENT->setTimeStep(30);
    BT_AGENT->initializeAgent(3,0);

   while(!BT_AGENT->madeIt())
       {

       root->update(BT_AGENT);

       BT_AGENT->performAction();
       }
    }

    if(bt_prio)
    {
        // Structure
        Selector* root = new Selector;
        Sequence* sequence1 = new Sequence;
        Sequence* sequence2 = new Sequence;

        Greater_than* condition_11 = new Greater_than(4, &BT_AGENT->pos.x);
        Greater_than* condition_12 = new Greater_than(6, &BT_AGENT->pos.y);

        Less_than* condition_21 = new Less_than(9, &BT_AGENT->pos.y);

        root->addChild(sequence1);
        root->addChild(sequence2);
        root->addChild(action_down);

        sequence1->addChild(condition_11);
        sequence1->addChild(condition_12);
        sequence1->addChild(action_left);

        sequence2->addChild(condition_21);
        sequence2->addChild(action_right);

        // Initialisation Agent
        //BT_AGENT->setSteps(30);
        BT_AGENT->setTimeStep(30);
        BT_AGENT->initializeAgent(3,0);

        while(!BT_AGENT->madeIt())
            {

            root->update(BT_AGENT);

            BT_AGENT->performAction();

            }

    }

}
Esempio n. 18
0
inline void debug_ast(AST_Node* node, std::string ind, Env* env)
{
  if (node == 0) return;
  if (ind == "") std::cerr << "####################################################################\n";
  if (dynamic_cast<Bubble*>(node)) {
    Bubble* bubble = dynamic_cast<Bubble*>(node);
    std::cerr << ind << "Bubble " << bubble;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << bubble->tabs();
    std::cerr << std::endl;
  } else if (dynamic_cast<At_Root_Block*>(node)) {
    At_Root_Block* root_block = dynamic_cast<At_Root_Block*>(node);
    std::cerr << ind << "At_Root_Block " << root_block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << root_block->tabs();
    std::cerr << std::endl;
    debug_ast(root_block->expression(), ind + ":", env);
    debug_ast(root_block->block(), ind + " ", env);
  } else if (dynamic_cast<Selector_List*>(node)) {
    Selector_List* selector = dynamic_cast<Selector_List*>(node);
    std::cerr << ind << "Selector_List " << selector;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " <" << selector->hash() << ">";
    std::cerr << " [@media:" << selector->media_block() << "]";
    std::cerr << (selector->is_optional() ? " [is_optional]": " -");
    std::cerr << (selector->has_parent_ref() ? " [has-parent]": " -");
    std::cerr << (selector->has_line_break() ? " [line-break]": " -");
    std::cerr << (selector->has_line_feed() ? " [line-feed]": " -");
    std::cerr << std::endl;

    for(auto i : selector->elements()) { debug_ast(i, ind + " ", env); }

//  } else if (dynamic_cast<Expression*>(node)) {
//    Expression* expression = dynamic_cast<Expression*>(node);
//    std::cerr << ind << "Expression " << expression << " " << expression->concrete_type() << std::endl;

  } else if (dynamic_cast<Parent_Selector*>(node)) {
    Parent_Selector* selector = dynamic_cast<Parent_Selector*>(node);
    std::cerr << ind << "Parent_Selector " << selector;
//    if (selector->not_selector()) cerr << " [in_declaration]";
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " <" << selector->hash() << ">";
    std::cerr << " <" << prettyprint(selector->pstate().token.ws_before()) << ">" << std::endl;
//    debug_ast(selector->selector(), ind + "->", env);

  } else if (dynamic_cast<Complex_Selector*>(node)) {
    Complex_Selector* selector = dynamic_cast<Complex_Selector*>(node);
    std::cerr << ind << "Complex_Selector " << selector
      << " (" << pstate_source_position(node) << ")"
      << " <" << selector->hash() << ">"
      << " [weight:" << longToHex(selector->specificity()) << "]"
      << " [@media:" << selector->media_block() << "]"
      << (selector->is_optional() ? " [is_optional]": " -")
      << (selector->has_parent_ref() ? " [has parent]": " -")
      << (selector->has_line_feed() ? " [line-feed]": " -")
      << (selector->has_line_break() ? " [line-break]": " -")
      << " -- ";
      std::string del;
      switch (selector->combinator()) {
        case Complex_Selector::PARENT_OF:   del = ">"; break;
        case Complex_Selector::PRECEDES:    del = "~"; break;
        case Complex_Selector::ADJACENT_TO: del = "+"; break;
        case Complex_Selector::ANCESTOR_OF: del = " "; break;
        case Complex_Selector::REFERENCE:   del = "//"; break;
      }
      // if (del = "/") del += selector->reference()->perform(&to_string) + "/";
    std::cerr << " <" << prettyprint(selector->pstate().token.ws_before()) << ">" << std::endl;
    debug_ast(selector->head(), ind + " " /* + "[" + del + "]" */, env);
    if (selector->tail()) {
      debug_ast(selector->tail(), ind + "{" + del + "}", env);
    } else if(del != " ") {
      std::cerr << ind << " |" << del << "| {trailing op}" << std::endl;
    }
    SourcesSet set = selector->sources();
    // debug_sources_set(set, ind + "  @--> ");
  } else if (dynamic_cast<Compound_Selector*>(node)) {
    Compound_Selector* selector = dynamic_cast<Compound_Selector*>(node);
    std::cerr << ind << "Compound_Selector " << selector;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " <" << selector->hash() << ">";
    std::cerr << " [weight:" << longToHex(selector->specificity()) << "]";
    std::cerr << " [@media:" << selector->media_block() << "]";
    std::cerr << (selector->extended() ? " [extended]": " -");
    std::cerr << (selector->is_optional() ? " [is_optional]": " -");
    std::cerr << (selector->has_parent_ref() ? " [has-parent]": " -");
    std::cerr << (selector->has_line_break() ? " [line-break]": " -");
    std::cerr << (selector->has_line_feed() ? " [line-feed]": " -");
    std::cerr << " <" << prettyprint(selector->pstate().token.ws_before()) << ">" << std::endl;
    for(auto i : selector->elements()) { debug_ast(i, ind + " ", env); }
  } else if (dynamic_cast<Propset*>(node)) {
    Propset* selector = dynamic_cast<Propset*>(node);
    std::cerr << ind << "Propset " << selector;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << selector->tabs() << std::endl;
    if (selector->block()) for(auto i : selector->block()->elements()) { debug_ast(i, ind + " ", env); }
  } else if (dynamic_cast<Wrapped_Selector*>(node)) {
    Wrapped_Selector* selector = dynamic_cast<Wrapped_Selector*>(node);
    std::cerr << ind << "Wrapped_Selector " << selector;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " <" << selector->hash() << ">";
    std::cerr << " <<" << selector->ns_name() << ">>";
    std::cerr << (selector->is_optional() ? " [is_optional]": " -");
    std::cerr << (selector->has_parent_ref() ? " [has-parent]": " -");
    std::cerr << (selector->has_line_break() ? " [line-break]": " -");
    std::cerr << (selector->has_line_feed() ? " [line-feed]": " -");
    std::cerr << std::endl;
    debug_ast(selector->selector(), ind + " () ", env);
  } else if (dynamic_cast<Pseudo_Selector*>(node)) {
    Pseudo_Selector* selector = dynamic_cast<Pseudo_Selector*>(node);
    std::cerr << ind << "Pseudo_Selector " << selector;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " <" << selector->hash() << ">";
    std::cerr << " <<" << selector->ns_name() << ">>";
    std::cerr << (selector->is_optional() ? " [is_optional]": " -");
    std::cerr << (selector->has_parent_ref() ? " [has-parent]": " -");
    std::cerr << (selector->has_line_break() ? " [line-break]": " -");
    std::cerr << (selector->has_line_feed() ? " [line-feed]": " -");
    std::cerr << std::endl;
    debug_ast(selector->expression(), ind + " <= ", env);
  } else if (dynamic_cast<Attribute_Selector*>(node)) {
    Attribute_Selector* selector = dynamic_cast<Attribute_Selector*>(node);
    std::cerr << ind << "Attribute_Selector " << selector;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " <" << selector->hash() << ">";
    std::cerr << " <<" << selector->ns_name() << ">>";
    std::cerr << (selector->is_optional() ? " [is_optional]": " -");
    std::cerr << (selector->has_parent_ref() ? " [has-parent]": " -");
    std::cerr << (selector->has_line_break() ? " [line-break]": " -");
    std::cerr << (selector->has_line_feed() ? " [line-feed]": " -");
    std::cerr << std::endl;
    debug_ast(selector->value(), ind + "[" + selector->matcher() + "] ", env);
  } else if (dynamic_cast<Selector_Qualifier*>(node)) {
    Selector_Qualifier* selector = dynamic_cast<Selector_Qualifier*>(node);
    std::cerr << ind << "Selector_Qualifier " << selector;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " <" << selector->hash() << ">";
    std::cerr << " <<" << selector->ns_name() << ">>";
    std::cerr << (selector->is_optional() ? " [is_optional]": " -");
    std::cerr << (selector->has_parent_ref() ? " [has-parent]": " -");
    std::cerr << (selector->has_line_break() ? " [line-break]": " -");
    std::cerr << (selector->has_line_feed() ? " [line-feed]": " -");
    std::cerr << std::endl;
  } else if (dynamic_cast<Type_Selector*>(node)) {
    Type_Selector* selector = dynamic_cast<Type_Selector*>(node);
    std::cerr << ind << "Type_Selector " << selector;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " <" << selector->hash() << ">";
    std::cerr << " <<" << selector->ns_name() << ">>";
    std::cerr << (selector->is_optional() ? " [is_optional]": " -");
    std::cerr << (selector->has_parent_ref() ? " [has-parent]": " -");
    std::cerr << (selector->has_line_break() ? " [line-break]": " -");
    std::cerr << (selector->has_line_feed() ? " [line-feed]": " -");
    std::cerr << " <" << prettyprint(selector->pstate().token.ws_before()) << ">";
    std::cerr << std::endl;
  } else if (dynamic_cast<Selector_Placeholder*>(node)) {

    Selector_Placeholder* selector = dynamic_cast<Selector_Placeholder*>(node);
    std::cerr << ind << "Selector_Placeholder [" << selector->ns_name() << "] " << selector
      << " <" << selector->hash() << ">"
      << " [@media:" << selector->media_block() << "]"
      << (selector->is_optional() ? " [is_optional]": " -")
      << (selector->has_line_break() ? " [line-break]": " -")
      << (selector->has_line_feed() ? " [line-feed]": " -")
    << std::endl;

  } else if (dynamic_cast<Simple_Selector*>(node)) {
    Simple_Selector* selector = dynamic_cast<Simple_Selector*>(node);
    std::cerr << ind << "Simple_Selector " << selector;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << (selector->has_line_break() ? " [line-break]": " -") << (selector->has_line_feed() ? " [line-feed]": " -") << std::endl;

  } else if (dynamic_cast<Selector_Schema*>(node)) {
    Selector_Schema* selector = dynamic_cast<Selector_Schema*>(node);
    std::cerr << ind << "Selector_Schema " << selector;
    std::cerr << " (" << pstate_source_position(node) << ")"
      << (selector->at_root() && selector->at_root() ? " [@ROOT]" : "")
      << " [@media:" << selector->media_block() << "]"
      << (selector->has_line_break() ? " [line-break]": " -")
      << (selector->has_line_feed() ? " [line-feed]": " -")
    << std::endl;

    debug_ast(selector->contents(), ind + " ");
    // for(auto i : selector->elements()) { debug_ast(i, ind + " ", env); }

  } else if (dynamic_cast<Selector*>(node)) {
    Selector* selector = dynamic_cast<Selector*>(node);
    std::cerr << ind << "Selector " << selector;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << (selector->has_line_break() ? " [line-break]": " -")
      << (selector->has_line_feed() ? " [line-feed]": " -")
    << std::endl;

  } else if (dynamic_cast<Media_Query_Expression*>(node)) {
    Media_Query_Expression* block = dynamic_cast<Media_Query_Expression*>(node);
    std::cerr << ind << "Media_Query_Expression " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << (block->is_interpolated() ? " [is_interpolated]": " -")
    << std::endl;
    debug_ast(block->feature(), ind + " feature) ");
    debug_ast(block->value(), ind + " value) ");

  } else if (dynamic_cast<Media_Query*>(node)) {
    Media_Query* block = dynamic_cast<Media_Query*>(node);
    std::cerr << ind << "Media_Query " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << (block->is_negated() ? " [is_negated]": " -")
      << (block->is_restricted() ? " [is_restricted]": " -")
    << std::endl;
    debug_ast(block->media_type(), ind + " ");
    for(auto i : block->elements()) { debug_ast(i, ind + " ", env); }

  } else if (dynamic_cast<Media_Block*>(node)) {
    Media_Block* block = dynamic_cast<Media_Block*>(node);
    std::cerr << ind << "Media_Block " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << block->tabs() << std::endl;
    debug_ast(block->media_queries(), ind + " =@ ");
    if (block->block()) for(auto i : block->block()->elements()) { debug_ast(i, ind + " ", env); }
  } else if (dynamic_cast<Supports_Block*>(node)) {
    Supports_Block* block = dynamic_cast<Supports_Block*>(node);
    std::cerr << ind << "Supports_Block " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << block->tabs() << std::endl;
    debug_ast(block->condition(), ind + " =@ ");
  } else if (dynamic_cast<Supports_Operator*>(node)) {
    Supports_Operator* block = dynamic_cast<Supports_Operator*>(node);
    std::cerr << ind << "Supports_Operator " << block;
    std::cerr << " (" << pstate_source_position(node) << ")"
    << std::endl;
    debug_ast(block->left(), ind + " left) ");
    debug_ast(block->right(), ind + " right) ");
  } else if (dynamic_cast<Supports_Negation*>(node)) {
    Supports_Negation* block = dynamic_cast<Supports_Negation*>(node);
    std::cerr << ind << "Supports_Negation " << block;
    std::cerr << " (" << pstate_source_position(node) << ")"
    << std::endl;
    debug_ast(block->condition(), ind + " condition) ");
  } else if (dynamic_cast<Supports_Declaration*>(node)) {
    Supports_Declaration* block = dynamic_cast<Supports_Declaration*>(node);
    std::cerr << ind << "Supports_Declaration " << block;
    std::cerr << " (" << pstate_source_position(node) << ")"
    << std::endl;
    debug_ast(block->feature(), ind + " feature) ");
    debug_ast(block->value(), ind + " value) ");
  } else if (dynamic_cast<Block*>(node)) {
    Block* root_block = dynamic_cast<Block*>(node);
    std::cerr << ind << "Block " << root_block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    if (root_block->is_root()) std::cerr << " [root]";
    std::cerr << " " << root_block->tabs() << std::endl;
    if (root_block->block()) for(auto i : root_block->block()->elements()) { debug_ast(i, ind + " ", env); }
  } else if (dynamic_cast<Warning*>(node)) {
    Warning* block = dynamic_cast<Warning*>(node);
    std::cerr << ind << "Warning " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << block->tabs() << std::endl;
  } else if (dynamic_cast<Error*>(node)) {
    Error* block = dynamic_cast<Error*>(node);
    std::cerr << ind << "Error " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << block->tabs() << std::endl;
  } else if (dynamic_cast<Debug*>(node)) {
    Debug* block = dynamic_cast<Debug*>(node);
    std::cerr << ind << "Debug " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << block->tabs() << std::endl;
  } else if (dynamic_cast<Comment*>(node)) {
    Comment* block = dynamic_cast<Comment*>(node);
    std::cerr << ind << "Comment " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << block->tabs() <<
      " <" << prettyprint(block->pstate().token.ws_before()) << ">" << std::endl;
    debug_ast(block->text(), ind + "// ", env);
  } else if (dynamic_cast<If*>(node)) {
    If* block = dynamic_cast<If*>(node);
    std::cerr << ind << "If " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << block->tabs() << std::endl;
    debug_ast(block->predicate(), ind + " = ");
    debug_ast(block->block(), ind + " <>");
    debug_ast(block->alternative(), ind + " ><");
  } else if (dynamic_cast<Return*>(node)) {
    Return* block = dynamic_cast<Return*>(node);
    std::cerr << ind << "Return " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << block->tabs() << std::endl;
  } else if (dynamic_cast<Extension*>(node)) {
    Extension* block = dynamic_cast<Extension*>(node);
    std::cerr << ind << "Extension " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << block->tabs() << std::endl;
    debug_ast(block->selector(), ind + "-> ", env);
  } else if (dynamic_cast<Content*>(node)) {
    Content* block = dynamic_cast<Content*>(node);
    std::cerr << ind << "Content " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << block->tabs() << std::endl;
  } else if (dynamic_cast<Import_Stub*>(node)) {
    Import_Stub* block = dynamic_cast<Import_Stub*>(node);
    std::cerr << ind << "Import_Stub " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << block->tabs() << std::endl;
  } else if (dynamic_cast<Import*>(node)) {
    Import* block = dynamic_cast<Import*>(node);
    std::cerr << ind << "Import " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << block->tabs() << std::endl;
    debug_ast(block->media_queries(), ind + " @ ");
    // std::vector<std::string>         files_;
    for (auto imp : block->urls()) debug_ast(imp, "@ ", env);
  } else if (dynamic_cast<Assignment*>(node)) {
    Assignment* block = dynamic_cast<Assignment*>(node);
    std::cerr << ind << "Assignment " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " <<" << block->variable() << ">> " << block->tabs() << std::endl;
    debug_ast(block->value(), ind + "=", env);
  } else if (dynamic_cast<Declaration*>(node)) {
    Declaration* block = dynamic_cast<Declaration*>(node);
    std::cerr << ind << "Declaration " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << block->tabs() << std::endl;
    debug_ast(block->property(), ind + " prop: ", env);
    debug_ast(block->value(), ind + " value: ", env);
  } else if (dynamic_cast<Keyframe_Rule*>(node)) {
    Keyframe_Rule* has_block = dynamic_cast<Keyframe_Rule*>(node);
    std::cerr << ind << "Keyframe_Rule " << has_block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << has_block->tabs() << std::endl;
    if (has_block->selector()) debug_ast(has_block->selector(), ind + "@");
    if (has_block->block()) for(auto i : has_block->block()->elements()) { debug_ast(i, ind + " ", env); }
  } else if (dynamic_cast<At_Rule*>(node)) {
    At_Rule* block = dynamic_cast<At_Rule*>(node);
    std::cerr << ind << "At_Rule " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [" << block->keyword() << "] " << block->tabs() << std::endl;
    debug_ast(block->selector(), ind + "~", env);
    debug_ast(block->value(), ind + "+", env);
    if (block->block()) for(auto i : block->block()->elements()) { debug_ast(i, ind + " ", env); }
  } else if (dynamic_cast<Each*>(node)) {
    Each* block = dynamic_cast<Each*>(node);
    std::cerr << ind << "Each " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << block->tabs() << std::endl;
    if (block->block()) for(auto i : block->block()->elements()) { debug_ast(i, ind + " ", env); }
  } else if (dynamic_cast<For*>(node)) {
    For* block = dynamic_cast<For*>(node);
    std::cerr << ind << "For " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << block->tabs() << std::endl;
    if (block->block()) for(auto i : block->block()->elements()) { debug_ast(i, ind + " ", env); }
  } else if (dynamic_cast<While*>(node)) {
    While* block = dynamic_cast<While*>(node);
    std::cerr << ind << "While " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << block->tabs() << std::endl;
    if (block->block()) for(auto i : block->block()->elements()) { debug_ast(i, ind + " ", env); }
  } else if (dynamic_cast<Definition*>(node)) {
    Definition* block = dynamic_cast<Definition*>(node);
    std::cerr << ind << "Definition " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [name: " << block->name() << "] ";
    std::cerr << " [type: " << (block->type() == Sass::Definition::Type::MIXIN ? "Mixin " : "Function ") << "] ";
    // this seems to lead to segfaults some times?
    // std::cerr << " [signature: " << block->signature() << "] ";
    std::cerr << " [native: " << block->native_function() << "] ";
    std::cerr << " " << block->tabs() << std::endl;
    debug_ast(block->parameters(), ind + " params: ", env);
    if (block->block()) for(auto i : block->block()->elements()) { debug_ast(i, ind + " ", env); }
  } else if (dynamic_cast<Mixin_Call*>(node)) {
    Mixin_Call* block = dynamic_cast<Mixin_Call*>(node);
    std::cerr << ind << "Mixin_Call " << block << " " << block->tabs();
    std::cerr << " [" <<  block->name() << "]";
    std::cerr << " [has_content: " << block->has_content() << "] " << std::endl;
    debug_ast(block->arguments(), ind + " args: ");
    if (block->block()) for(auto i : block->block()->elements()) { debug_ast(i, ind + " ", env); }
  } else if (Ruleset* ruleset = dynamic_cast<Ruleset*>(node)) {
    std::cerr << ind << "Ruleset " << ruleset;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [indent: " << ruleset->tabs() << "]";
    std::cerr << (ruleset->at_root() ? " [@ROOT]" : "");
    std::cerr << (ruleset->is_root() ? " [root]" : "");
    std::cerr << std::endl;
    debug_ast(ruleset->selector(), ind + ">");
    debug_ast(ruleset->block(), ind + " ");
  } else if (dynamic_cast<Block*>(node)) {
    Block* block = dynamic_cast<Block*>(node);
    std::cerr << ind << "Block " << block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [indent: " << block->tabs() << "]" << std::endl;
    for(auto i : block->elements()) { debug_ast(i, ind + " ", env); }
  } else if (dynamic_cast<Textual*>(node)) {
    Textual* expression = dynamic_cast<Textual*>(node);
    std::cerr << ind << "Textual ";
    if (expression->type() == Textual::NUMBER) std::cerr << " [NUMBER]";
    else if (expression->type() == Textual::PERCENTAGE) std::cerr << " [PERCENTAGE]";
    else if (expression->type() == Textual::DIMENSION) std::cerr << " [DIMENSION]";
    else if (expression->type() == Textual::HEX) std::cerr << " [HEX]";
    std::cerr << expression << " [" << expression->value() << "]";
    std::cerr << " [interpolant: " << expression->is_interpolant() << "] ";
    if (expression->is_delayed()) std::cerr << " [delayed]";
    std::cerr << std::endl;
  } else if (dynamic_cast<Variable*>(node)) {
    Variable* expression = dynamic_cast<Variable*>(node);
    std::cerr << ind << "Variable " << expression;
    std::cerr << " [interpolant: " << expression->is_interpolant() << "] ";
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [" << expression->name() << "]" << std::endl;
    std::string name(expression->name());
    if (env && env->has(name)) debug_ast(static_cast<Expression*>((*env)[name]), ind + " -> ", env);
  } else if (dynamic_cast<Function_Call_Schema*>(node)) {
    Function_Call_Schema* expression = dynamic_cast<Function_Call_Schema*>(node);
    std::cerr << ind << "Function_Call_Schema " << expression;
    std::cerr << " [interpolant: " << expression->is_interpolant() << "] ";
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << "" << std::endl;
    debug_ast(expression->name(), ind + "name: ", env);
    debug_ast(expression->arguments(), ind + " args: ", env);
  } else if (dynamic_cast<Function_Call*>(node)) {
    Function_Call* expression = dynamic_cast<Function_Call*>(node);
    std::cerr << ind << "Function_Call " << expression;
    std::cerr << " [interpolant: " << expression->is_interpolant() << "] ";
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [" << expression->name() << "]";
    if (expression->is_delayed()) std::cerr << " [delayed]";
    if (expression->is_interpolant()) std::cerr << " [interpolant]";
    std::cerr << std::endl;
    debug_ast(expression->arguments(), ind + " args: ", env);
  } else if (dynamic_cast<Arguments*>(node)) {
    Arguments* expression = dynamic_cast<Arguments*>(node);
    std::cerr << ind << "Arguments " << expression;
    if (expression->is_delayed()) std::cerr << " [delayed]";
    std::cerr << " (" << pstate_source_position(node) << ")";
    if (expression->has_named_arguments()) std::cerr << " [has_named_arguments]";
    if (expression->has_rest_argument()) std::cerr << " [has_rest_argument]";
    if (expression->has_keyword_argument()) std::cerr << " [has_keyword_argument]";
    std::cerr << std::endl;
    for(auto i : expression->elements()) { debug_ast(i, ind + " ", env); }
  } else if (dynamic_cast<Argument*>(node)) {
    Argument* expression = dynamic_cast<Argument*>(node);
    std::cerr << ind << "Argument " << expression;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [" << expression->value() << "]";
    std::cerr << " [name: " << expression->name() << "] ";
    std::cerr << " [rest: " << expression->is_rest_argument() << "] ";
    std::cerr << " [keyword: " << expression->is_keyword_argument() << "] " << std::endl;
    debug_ast(expression->value(), ind + " value: ", env);
  } else if (dynamic_cast<Parameters*>(node)) {
    Parameters* expression = dynamic_cast<Parameters*>(node);
    std::cerr << ind << "Parameters " << expression;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [has_optional: " << expression->has_optional_parameters() << "] ";
    std::cerr << " [has_rest: " << expression->has_rest_parameter() << "] ";
    std::cerr << std::endl;
    for(auto i : expression->elements()) { debug_ast(i, ind + " ", env); }
  } else if (dynamic_cast<Parameter*>(node)) {
    Parameter* expression = dynamic_cast<Parameter*>(node);
    std::cerr << ind << "Parameter " << expression;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [name: " << expression->name() << "] ";
    std::cerr << " [default: " << expression->default_value() << "] ";
    std::cerr << " [rest: " << expression->is_rest_parameter() << "] " << std::endl;
  } else if (dynamic_cast<Unary_Expression*>(node)) {
    Unary_Expression* expression = dynamic_cast<Unary_Expression*>(node);
    std::cerr << ind << "Unary_Expression " << expression;
    std::cerr << " [interpolant: " << expression->is_interpolant() << "] ";
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [" << expression->type() << "]" << std::endl;
    debug_ast(expression->operand(), ind + " operand: ", env);
  } else if (dynamic_cast<Binary_Expression*>(node)) {
    Binary_Expression* expression = dynamic_cast<Binary_Expression*>(node);
    std::cerr << ind << "Binary_Expression " << expression;
    if (expression->is_interpolant()) std::cerr << " [is interpolant] ";
    if (expression->is_left_interpolant()) std::cerr << " [left interpolant] ";
    if (expression->is_right_interpolant()) std::cerr << " [right interpolant] ";
    std::cerr << " [delayed: " << expression->is_delayed() << "] ";
    std::cerr << " [ws_before: " << expression->op().ws_before << "] ";
    std::cerr << " [ws_after: " << expression->op().ws_after << "] ";
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [" << expression->type_name() << "]" << std::endl;
    debug_ast(expression->left(), ind + " left:  ", env);
    debug_ast(expression->right(), ind + " right: ", env);
  } else if (dynamic_cast<Map*>(node)) {
    Map* expression = dynamic_cast<Map*>(node);
    std::cerr << ind << "Map " << expression;
    std::cerr << " [interpolant: " << expression->is_interpolant() << "] ";
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [Hashed]" << std::endl;
    for (auto i : expression->elements()) {
      debug_ast(i.first, ind + " key: ");
      debug_ast(i.second, ind + " val: ");
    }
  } else if (dynamic_cast<List*>(node)) {
    List* expression = dynamic_cast<List*>(node);
    std::cerr << ind << "List " << expression;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " (" << expression->length() << ") " <<
      (expression->separator() == SASS_COMMA ? "Comma " : expression->separator() == SASS_HASH ? "Map" : "Space ") <<
      " [delayed: " << expression->is_delayed() << "] " <<
      " [interpolant: " << expression->is_interpolant() << "] " <<
      " [arglist: " << expression->is_arglist() << "] " <<
      " [hash: " << expression->hash() << "] " <<
      std::endl;
    for(auto i : expression->elements()) { debug_ast(i, ind + " ", env); }
  } else if (dynamic_cast<Content*>(node)) {
    Content* expression = dynamic_cast<Content*>(node);
    std::cerr << ind << "Content " << expression;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [Statement]" << std::endl;
  } else if (dynamic_cast<Boolean*>(node)) {
    Boolean* expression = dynamic_cast<Boolean*>(node);
    std::cerr << ind << "Boolean " << expression;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [interpolant: " << expression->is_interpolant() << "] ";
    std::cerr << " [" << expression->value() << "]" << std::endl;
  } else if (dynamic_cast<Color*>(node)) {
    Color* expression = dynamic_cast<Color*>(node);
    std::cerr << ind << "Color " << expression;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [interpolant: " << expression->is_interpolant() << "] ";
    std::cerr << " [" << expression->r() << ":"  << expression->g() << ":" << expression->b() << "@" << expression->a() << "]" << std::endl;
  } else if (dynamic_cast<Number*>(node)) {
    Number* expression = dynamic_cast<Number*>(node);
    std::cerr << ind << "Number " << expression;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [interpolant: " << expression->is_interpolant() << "] ";
    std::cerr << " [" << expression->value() << expression->unit() << "]" <<
      " [hash: " << expression->hash() << "] " <<
      std::endl;
  } else if (dynamic_cast<String_Quoted*>(node)) {
    String_Quoted* expression = dynamic_cast<String_Quoted*>(node);
    std::cerr << ind << "String_Quoted " << expression;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [" << prettyprint(expression->value()) << "]";
    if (expression->is_delayed()) std::cerr << " [delayed]";
    if (expression->sass_fix_1291()) std::cerr << " [sass_fix_1291]";
    if (expression->is_interpolant()) std::cerr << " [interpolant]";
    if (expression->quote_mark()) std::cerr << " [quote_mark: " << expression->quote_mark() << "]";
    std::cerr << " <" << prettyprint(expression->pstate().token.ws_before()) << ">" << std::endl;
  } else if (dynamic_cast<String_Constant*>(node)) {
    String_Constant* expression = dynamic_cast<String_Constant*>(node);
    std::cerr << ind << "String_Constant " << expression;
    if (expression->concrete_type()) {
      std::cerr << " " << expression->concrete_type();
    }
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " [" << prettyprint(expression->value()) << "]";
    if (expression->is_delayed()) std::cerr << " [delayed]";
    if (expression->sass_fix_1291()) std::cerr << " [sass_fix_1291]";
    if (expression->is_interpolant()) std::cerr << " [interpolant]";
    std::cerr << " <" << prettyprint(expression->pstate().token.ws_before()) << ">" << std::endl;
  } else if (dynamic_cast<String_Schema*>(node)) {
    String_Schema* expression = dynamic_cast<String_Schema*>(node);
    std::cerr << ind << "String_Schema " << expression;
    std::cerr << " " << expression->concrete_type();
    if (expression->is_delayed()) std::cerr << " [delayed]";
    if (expression->is_interpolant()) std::cerr << " [is interpolant]";
    if (expression->has_interpolant()) std::cerr << " [has interpolant]";
    if (expression->is_left_interpolant()) std::cerr << " [left interpolant] ";
    if (expression->is_right_interpolant()) std::cerr << " [right interpolant] ";
    std::cerr << " <" << prettyprint(expression->pstate().token.ws_before()) << ">" << std::endl;
    for(auto i : expression->elements()) { debug_ast(i, ind + " ", env); }
  } else if (dynamic_cast<String*>(node)) {
    String* expression = dynamic_cast<String*>(node);
    std::cerr << ind << "String " << expression;
    std::cerr << " " << expression->concrete_type();
    std::cerr << " (" << pstate_source_position(node) << ")";
    if (expression->sass_fix_1291()) std::cerr << " [sass_fix_1291]";
    if (expression->is_interpolant()) std::cerr << " [interpolant]";
    std::cerr << " <" << prettyprint(expression->pstate().token.ws_before()) << ">" << std::endl;
  } else if (dynamic_cast<Expression*>(node)) {
    Expression* expression = dynamic_cast<Expression*>(node);
    std::cerr << ind << "Expression " << expression;
    std::cerr << " (" << pstate_source_position(node) << ")";
    switch (expression->concrete_type()) {
      case Expression::Concrete_Type::NONE: std::cerr << " [NONE]"; break;
      case Expression::Concrete_Type::BOOLEAN: std::cerr << " [BOOLEAN]"; break;
      case Expression::Concrete_Type::NUMBER: std::cerr << " [NUMBER]"; break;
      case Expression::Concrete_Type::COLOR: std::cerr << " [COLOR]"; break;
      case Expression::Concrete_Type::STRING: std::cerr << " [STRING]"; break;
      case Expression::Concrete_Type::LIST: std::cerr << " [LIST]"; break;
      case Expression::Concrete_Type::MAP: std::cerr << " [MAP]"; break;
      case Expression::Concrete_Type::SELECTOR: std::cerr << " [SELECTOR]"; break;
      case Expression::Concrete_Type::NULL_VAL: std::cerr << " [NULL_VAL]"; break;
      case Expression::Concrete_Type::C_WARNING: std::cerr << " [C_WARNING]"; break;
      case Expression::Concrete_Type::C_ERROR: std::cerr << " [C_ERROR]"; break;
      case Expression::Concrete_Type::NUM_TYPES: std::cerr << " [NUM_TYPES]"; break;
    }
    std::cerr << std::endl;
  } else if (dynamic_cast<Has_Block*>(node)) {
    Has_Block* has_block = dynamic_cast<Has_Block*>(node);
    std::cerr << ind << "Has_Block " << has_block;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << has_block->tabs() << std::endl;
    if (has_block->block()) for(auto i : has_block->block()->elements()) { debug_ast(i, ind + " ", env); }
  } else if (dynamic_cast<Statement*>(node)) {
    Statement* statement = dynamic_cast<Statement*>(node);
    std::cerr << ind << "Statement " << statement;
    std::cerr << " (" << pstate_source_position(node) << ")";
    std::cerr << " " << statement->tabs() << std::endl;
  }

  if (ind == "") std::cerr << "####################################################################\n";
}
Esempio n. 19
0
void Mixin::parseArguments(TokenList::const_iterator i, const Selector &selector) {
  TokenList::const_iterator j;
  string delimiter = ",";

  TokenList argument;
  size_t nestedParenthesis = 0;
  string argName;

  if (i != selector.end() &&
      (*i).type == Token::PAREN_OPEN) {
    i++;
  }
    
  // if a ';' token occurs then that is the delimiter instead of the ','.
  for(j = i; j != selector.end(); j++) {
    if (*j == ";") {
      delimiter = ";";
      break;
    }
  }

  while (i != selector.end() && (*i).type != Token::PAREN_CLOSED) {
    while (i != selector.end() &&
           (*i).type == Token::WHITESPACE) {
      i++;
    }

    if ((*i).type == Token::ATKEYWORD) {
      argName = (*i);
      i++;
      if (i != selector.end() &&
          (*i).type == Token::COLON) {
        i++;
      } else {
        argName = "";
        i--;
      }
    }

    while (i != selector.end() &&
           (nestedParenthesis > 0 ||
            ((*i) != delimiter &&
             (*i).type != Token::PAREN_CLOSED))) {
      
      if ((*i).type == Token::PAREN_OPEN)
        nestedParenthesis++;
      
      if ((*i).type == Token::PAREN_CLOSED)
        nestedParenthesis--;
      
      argument.push_back(*i);
      
      i++;
    }

    if (*i == delimiter)
      i++;

    if (argName == "")
      this->arguments.push_back(argument);
    else {
      this->namedArguments.insert(pair<string,
                                  TokenList>(argName,argument));
      argName = "";
    }
    argument.clear();
  }
}
Esempio n. 20
0
  void Output_Nested::operator()(Ruleset* r)
  {
    Selector* s     = r->selector();
    Block*    b     = r->block();
    bool      decls = false;

    if (s->has_placeholder()) return;

    if (b->has_non_hoistable()) {
      decls = true;
      indent();
      if (source_comments) {
        stringstream ss;
        ss << "/* line " << r->line() << ", " << r->path() << " */" << endl;
        buffer += ss.str();
        indent();
      }
      s->perform(this);
      buffer += " {\n";
      ++indentation;
      for (size_t i = 0, L = b->length(); i < L; ++i) {
        Statement* stm = (*b)[i];
        bool bPrintExpression = true;
        // Check print conditions
        if (typeid(*stm) == typeid(Declaration)) {
          Declaration* dec = static_cast<Declaration*>(stm);
          if (dec->value()->concrete_type() == Expression::STRING) {
            String_Constant* valConst = static_cast<String_Constant*>(dec->value());
            string val(valConst->value());
            if (val.empty()) {
              bPrintExpression = false;
            }
          }
          else if (dec->value()->concrete_type() == Expression::LIST) {
            List* list = static_cast<List*>(dec->value());
            bool all_invisible = true;
            for (size_t list_i = 0, list_L = list->length(); list_i < list_L; ++list_i) {
              Expression* item = (*list)[list_i];
              if (!item->is_invisible()) all_invisible = false;
            }
            if (all_invisible) bPrintExpression = false;
          }
        }
        // Print if OK
        if (!stm->is_hoistable() && bPrintExpression) {
          if (!stm->block()) indent();
          stm->perform(this);
          buffer += '\n';
        }
      }
      --indentation;
      buffer.erase(buffer.length()-1);
      buffer += " }\n";
    }

    if (b->has_hoistable()) {
      if (decls) ++indentation;
      // indent();
      for (size_t i = 0, L = b->length(); i < L; ++i) {
        Statement* stm = (*b)[i];
        if (stm->is_hoistable()) {
          stm->perform(this);
        }
      }
      if (decls) --indentation;
    }
  }
Esempio n. 21
0
bool CalculateCenter(typename TAAPosVRT::ValueType& centerOut,
					 Selector& sel, TAAPosVRT& aaPos)
{
	if(!sel.grid()){
		throw(UGError("No grid assigned to selector"));
	}
	
	Grid& grid = *sel.grid();
	
//	collect all vertices that are adjacent to selected elements
//	we have to make sure that each vertex is only counted once.
//	we do this by using grid::mark.
	grid.begin_marking();

//	std::vector<Vertex*> vrts;
//	vrts.assign(sel.vertices_begin(), sel.vertices_end());
//	grid.mark(sel.vertices_begin(), sel.vertices_end());

	VecSet(centerOut, 0);
	size_t n = 0;
	for(VertexIterator iter = sel.vertices_begin();
		iter != sel.vertices_end(); ++iter)
	{
		VecAdd(centerOut, centerOut, aaPos[*iter]);
		grid.mark(*iter);
		++n;
	}

	for(EdgeIterator iter = sel.edges_begin();
		iter != sel.edges_end(); ++iter)
	{
		Edge::ConstVertexArray vrts = (*iter)->vertices();
		for(size_t i = 0; i < (*iter)->num_vertices(); ++i){
			if(!grid.is_marked(vrts[i])){
				grid.mark(vrts[i]);
				VecAdd(centerOut, centerOut, aaPos[vrts[i]]);
				++n;
			}
		}
	}

	for(FaceIterator iter = sel.faces_begin();
		iter != sel.faces_end(); ++iter)
	{
		Face::ConstVertexArray vrts = (*iter)->vertices();
		for(size_t i = 0; i < (*iter)->num_vertices(); ++i){
			if(!grid.is_marked(vrts[i])){
				grid.mark(vrts[i]);
				VecAdd(centerOut, centerOut, aaPos[vrts[i]]);
				++n;
			}
		}
	}

	for(VolumeIterator iter = sel.volumes_begin();
		iter != sel.volumes_end(); ++iter)
	{
		Volume::ConstVertexArray vrts = (*iter)->vertices();
		for(size_t i = 0; i < (*iter)->num_vertices(); ++i){
			if(!grid.is_marked(vrts[i])){
				grid.mark(vrts[i]);
				VecAdd(centerOut, centerOut, aaPos[vrts[i]]);
				++n;
			}
		}
	}

	grid.end_marking();

	if(n > 0){
		VecScale(centerOut, centerOut, 1. / (number)n);
		return true;
	}
	return false;
}
Esempio n. 22
0
void ObjCSuperCallChecker::checkASTDecl(const ObjCImplementationDecl *D,
                                        AnalysisManager &Mgr,
                                        BugReporter &BR) const {
  ASTContext &Ctx = BR.getContext();

  if (!isUIViewControllerSubclass(Ctx, D))
    return;

  const char *SelectorNames[] = 
    {"addChildViewController", "viewDidAppear", "viewDidDisappear", 
     "viewWillAppear", "viewWillDisappear", "removeFromParentViewController",
     "didReceiveMemoryWarning", "viewDidUnload", "viewWillUnload",
     "viewDidLoad"};
  const unsigned SelectorArgumentCounts[] =
   {1, 1, 1, 1, 1, 0, 0, 0, 0, 0};
  const size_t SelectorCount = llvm::array_lengthof(SelectorNames);
  assert(llvm::array_lengthof(SelectorArgumentCounts) == SelectorCount);

  // Fill the Selectors SmallSet with all selectors we want to check.
  llvm::SmallSet<Selector, 16> Selectors;
  for (size_t i = 0; i < SelectorCount; i++) { 
    unsigned ArgumentCount = SelectorArgumentCounts[i];
    const char *SelectorCString = SelectorNames[i];

    // Get the selector.
    IdentifierInfo *II = &Ctx.Idents.get(SelectorCString);
    Selectors.insert(Ctx.Selectors.getSelector(ArgumentCount, &II));
  }

  // Iterate over all instance methods.
  for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(),
                                                 E = D->instmeth_end();
       I != E; ++I) {
    Selector S = (*I)->getSelector();
    // Find out whether this is a selector that we want to check.
    if (!Selectors.count(S))
      continue;

    ObjCMethodDecl *MD = *I;

    // Check if the method calls its superclass implementation.
    if (MD->getBody())
    {
      FindSuperCallVisitor Visitor(S);
      Visitor.TraverseDecl(MD);

      // It doesn't call super, emit a diagnostic.
      if (!Visitor.DoesCallSuper) {
        PathDiagnosticLocation DLoc =
          PathDiagnosticLocation::createEnd(MD->getBody(),
                                            BR.getSourceManager(),
                                            Mgr.getAnalysisDeclContext(D));

        const char *Name = "Missing call to superclass";
        SmallString<256> Buf;
        llvm::raw_svector_ostream os(Buf);

        os << "The '" << S.getAsString() 
           << "' instance method in UIViewController subclass '" << *D
           << "' is missing a [super " << S.getAsString() << "] call";

        BR.EmitBasicReport(MD, Name, categories::CoreFoundationObjectiveC,
                           os.str(), DLoc);
      }
    }
  }
}
Esempio n. 23
0
void parcefile(std::string filepath)
{
 xmlpp::DomParser parser;
 parser.parse_file(filepath);
 const xmlpp::Node* rootNode = parser.get_document()->get_root_node();
 xmlpp::Node::NodeList mainList = rootNode->get_children();
 char origLocale[1024];
 strcpy(origLocale, std::setlocale(LC_ALL, "")); //Store locale before changing
 std::setlocale(LC_ALL, "C"); // We use '.' as decimal-point separator

 int m_pos=-1; //For keeping track on the current module position
 for(xmlpp::Node::NodeList::iterator iter = mainList.begin(); iter != mainList.end(); ++iter)
 {
     std::string contName= (*iter)->get_name();
     if(contName=="modules")
     {
         xmlpp::Element::NodeList modulesList = (*iter)->get_children();
         for(xmlpp::Element::NodeList::iterator modIter = modulesList.begin(); modIter != modulesList.end(); ++modIter)
         {
             std::string nodeType=(*modIter)->get_name();
             if(nodeType=="module")
             {             
                  m_pos++; //First occurence will be 0, second 1 etc...
                  const xmlpp::Element* element1 = dynamic_cast<const xmlpp::Element*>(*modIter);
                  std::string moduleName = element1->get_attribute_value("name"); //Not actually used here
                  std::string moduleId   = element1->get_attribute_value("type_id");
                  int module_type_id = std::stoi(moduleId); 

                  create_and_append_module(module_type_id); //Append module to rack
                  Module* current_module = modules[m_pos];

                  //Check for aggregated knob, switch etc. data within module entry:
                  xmlpp::Element::NodeList moduleDataList = (*modIter)->get_children();
                  for(xmlpp::Element::NodeList::iterator modDataIter = moduleDataList.begin(); modDataIter != moduleDataList.end(); ++modDataIter)
                  {
                      std::string nodeDataType=(*modDataIter)->get_name();
                      if(nodeDataType=="knob")
                      {
                          const xmlpp::Element* element2m = dynamic_cast<const xmlpp::Element*>(*modDataIter);
                          int    knob_n = std::stoi(element2m->get_attribute_value("n"));
                          double value  = std::stof(element2m->get_attribute_value("value"));
                          //std::cerr << "Module:" << m_pos << "Knob#" << knob_n << "value:" << value <<"\n"; 
                          
                          if((dynamic_cast<Selector*>(current_module->knobs[knob_n])))
                          {
                              //This Knob is, in fact a Selector object, treat differently 
                              Selector* someSelector = (Selector*)current_module->knobs[knob_n]; 
                              someSelector->set_value(value);
                              //std::cerr << "Is selector\n";
                          }
                          else
                          {
                               //Treat as basic Knob object
                               current_module->knobs[knob_n]->set_value(value); 
                               //std::cerr << "Is knob\n";
                          }
                      }
                      if(nodeDataType=="switch")
                      {
                          const xmlpp::Element* element3m = dynamic_cast<const xmlpp::Element*>(*modDataIter);
                          int    switch_n = std::stoi(element3m->get_attribute_value("n"));
                          double value = std::stof(element3m->get_attribute_value("value"));
                          Switch* theSwitch = current_module->switches[switch_n];
                          theSwitch->set_value(value);
                      }
                  }
             }
         }
     }

     if(contName=="wires")
     {
         xmlpp::Element::NodeList wiresList = (*iter)->get_children();
         for(xmlpp::Element::NodeList::iterator wireIter = wiresList.begin(); wireIter != wiresList.end(); ++wireIter)
         {
             std::string nodeType=(*wireIter)->get_name();
             if(nodeType=="wire")
             {
                 const xmlpp::Element* element = dynamic_cast<const xmlpp::Element*>(*wireIter);
                 int src = std::stoi(element->get_attribute_value("src"));
                 int sj  = std::stoi(element->get_attribute_value("sj"));
                 int dst = std::stoi(element->get_attribute_value("dst"));
                 int dj  = std::stoi(element->get_attribute_value("dj"));
                 Module* srcMod = modules[src];
                 Module* dstMod = modules[dst];
                 connect(srcMod->outlets[sj], dstMod->inlets[dj]);
             }
         }
     }

     if(contName=="knobs")
     {
         xmlpp::Element::NodeList knobList = (*iter)->get_children();
         int i=0;
         for(xmlpp::Element::NodeList::iterator knobIter = knobList.begin(); knobIter != knobList.end(); ++knobIter)
         {
             std::string nodeType=(*knobIter)->get_name();
             if(nodeType=="knob")
             {
                 const xmlpp::Element* element2 = dynamic_cast<const xmlpp::Element*>(*knobIter);
                 double value = std::stof(element2->get_attribute_value("value"));
                 if(typeid(*knobs[i]) == typeid(Selector))
                 {
                     //This Knob is, in fact a Selector object, treat differently 
                     Selector* someSelector = (Selector*)knobs[i]; 
                     someSelector->set_value(value);
                 }
                 else
                 {
                     //Treat as basic Knob object
                     knobs[i]->set_value(value); 
                 }
                 i++;
             }
         }
     }

     if(contName=="switches")
     {
         xmlpp::Element::NodeList switchList = (*iter)->get_children();
         int i=0;
         for(xmlpp::Element::NodeList::iterator switchIter = switchList.begin(); switchIter != switchList.end(); ++switchIter)
         {
             std::string nodeType=(*switchIter)->get_name();
             if(nodeType=="switch")
             {
                 const xmlpp::Element* element3 = dynamic_cast<const xmlpp::Element*>(*switchIter);
                 double value = std::stof(element3->get_attribute_value("value"));
                 switches[i]->set_value(value);
                 i++;
             }
         }
     }
 }
 std::setlocale(LC_ALL, origLocale); //Restore locale to the original state
} //end parcefile()
    // Effects:
    // 4 things are set.
    // 1) prediction_error
    // 2) scaled_prediction_error
    // 3) forecast_precision_log_determinant
    // 4) kalman_gain
    void Marginal::high_dimensional_update(
        const Vector &observation,
        const Selector &observed,
        const SparseKalmanMatrix &transition,
        const SparseKalmanMatrix &observation_coefficient_subset) {
      Vector observed_subset = observed.select(observation);
      set_prediction_error(observed_subset
                           - observation_coefficient_subset * state_mean());

      // At this point the Kalman recursions compute the forecast precision Finv
      // and its log determinant.  However, we can get rid of the forecast
      // precision matrix, and replace it with the scaled error = Finv *
      // prediction_error.
      //
      // To evaluate the normal likelihood, we need the quadratic form:
      //   error * Finv * error == error.dot(scaled_error).
      // We also need the log determinant of Finv.
      //
      // The forecast_precision can be computed using a version of the binomial
      // inverse theorem:
      //
      //  (A + UBV).inv =
      //    A.inv - A.inv * U * (I + B * V * Ainv * U).inv * B * V * Ainv.
      //
      // When applied to F = H + Z P Z' the theorem gives
      //
      //   Finv = Hinv - Hinv * Z * (I + P Z' Hinv Z).inv * P * Z' * Hinv
      //
      // This helps because H is diagonal.  The only matrix that needs to be
      // inverted is (I + PZ'HinvZ), which is a state x state matrix.
      // 
      // We don't compute Finv directly, we compute Finv * prediction_error.

      // observation_precision refers to the precision of the observed subset.
      DiagonalMatrix observation_precision(observed.select(
          1.0 / model_->observation_variance(time_index()).diag()));

      // Set inner_matrix to I + P * Z' * Hinv * Z
      SpdMatrix ZTZ = observation_coefficient_subset.inner(
          observation_precision.diag());
      // Note: the product of two SPD matrices need not be symmetric.
      Matrix inner_matrix = state_variance() * ZTZ;
      inner_matrix.diag() += 1.0;
      LU inner_lu(inner_matrix);
      
      // inner_inv_P is inner.inv() * state_variance.  This matrix need not be
      // symmetric.
      Matrix inner_inv_P = inner_lu.solve(state_variance());
      
      Matrix HinvZ = observation_precision *
          observation_coefficient_subset.dense();
      set_scaled_prediction_error(
          observation_precision * prediction_error()
          - HinvZ * inner_inv_P * HinvZ.Tmult(prediction_error()));
      
      // The log determinant of F.inverse is the negative log of det(H + ZPZ').
      // That determinant can be computed using the "matrix determinant lemma,"
      // which says det(A + UV') = det(I + V' * A.inv * U) * det(A)
      //
      // https://en.wikipedia.org/wiki/Matrix_determinant_lemma#Generalization
      //
      // With F = H + ZPZ', and setting A = H, U = Z, V' = PZ'.
      // Then det(F) = det(I + PZ' * Hinv * Z) * det(H)
      set_forecast_precision_log_determinant(
          observation_precision.logdet() - inner_lu.logdet());

      // The Kalman gain is:  K = T * P * Z' * Finv.
      // Substituting the expression for Finv from above gives
      //
      // K = T * P * Z' *
      //   (Hinv - Hinv * Z * (I + P Z' Hinv Z).inv * P * Z' * Hinv)
      Matrix ZtHinv = HinvZ.transpose();
      set_kalman_gain(transition * state_variance() *
                      (ZtHinv - ZTZ * inner_inv_P * ZtHinv));
    }
Esempio n. 25
0
  void Output::operator()(Ruleset* r)
  {
    Selector* s     = r->selector();
    Block*    b     = r->block();
    bool      decls = false;

    // Filter out rulesets that aren't printable (process its children though)
    if (!Util::isPrintable(r, output_style())) {
      for (size_t i = 0, L = b->length(); i < L; ++i) {
        Statement* stm = (*b)[i];
        if (dynamic_cast<Has_Block*>(stm)) {
          stm->perform(this);
        }
      }
      return;
    }

    if (b->has_non_hoistable()) {
      decls = true;
      if (output_style() == NESTED) indentation += r->tabs();
      if (opt.source_comments) {
        std::stringstream ss;
        append_indentation();
        ss << "/* line " << r->pstate().line + 1 << ", " << r->pstate().path << " */";
        append_string(ss.str());
        append_optional_linefeed();
      }
      s->perform(this);
      append_scope_opener(b);
      for (size_t i = 0, L = b->length(); i < L; ++i) {
        Statement* stm = (*b)[i];
        bool bPrintExpression = true;
        // Check print conditions
        if (typeid(*stm) == typeid(Declaration)) {
          Declaration* dec = static_cast<Declaration*>(stm);
          if (dec->value()->concrete_type() == Expression::STRING) {
            String_Constant* valConst = static_cast<String_Constant*>(dec->value());
            std::string val(valConst->value());
            if (auto qstr = dynamic_cast<String_Quoted*>(valConst)) {
              if (!qstr->quote_mark() && val.empty()) {
                bPrintExpression = false;
              }
            }
          }
          else if (dec->value()->concrete_type() == Expression::LIST) {
            List* list = static_cast<List*>(dec->value());
            bool all_invisible = true;
            for (size_t list_i = 0, list_L = list->length(); list_i < list_L; ++list_i) {
              Expression* item = (*list)[list_i];
              if (!item->is_invisible()) all_invisible = false;
            }
            if (all_invisible) bPrintExpression = false;
          }
        }
        // Print if OK
        if (!stm->is_hoistable() && bPrintExpression) {
          stm->perform(this);
        }
      }
      if (output_style() == NESTED) indentation -= r->tabs();
      append_scope_closer(b);
    }

    if (b->has_hoistable()) {
      if (decls) ++indentation;
      for (size_t i = 0, L = b->length(); i < L; ++i) {
        Statement* stm = (*b)[i];
        if (stm->is_hoistable()) {
          stm->perform(this);
        }
      }
      if (decls) --indentation;
    }
  }
Esempio n. 26
0
bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
                                     Selector Sel, ObjCMethodDecl *Method,
                                     bool isClassMessage,
                                     SourceLocation lbrac, SourceLocation rbrac,
                                     QualType &ReturnType, ExprValueKind &VK) {
  if (!Method) {
    // Apply default argument promotion as for (C99 6.5.2.2p6).
    for (unsigned i = 0; i != NumArgs; i++) {
      if (Args[i]->isTypeDependent())
        continue;

      DefaultArgumentPromotion(Args[i]);
    }

    unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
                                       diag::warn_inst_method_not_found;
    Diag(lbrac, DiagID)
      << Sel << isClassMessage << SourceRange(lbrac, rbrac);
    ReturnType = Context.getObjCIdType();
    VK = VK_RValue;
    return false;
  }

  ReturnType = Method->getSendResultType();
  VK = Expr::getValueKindForType(Method->getResultType());

  unsigned NumNamedArgs = Sel.getNumArgs();
  // Method might have more arguments than selector indicates. This is due
  // to addition of c-style arguments in method.
  if (Method->param_size() > Sel.getNumArgs())
    NumNamedArgs = Method->param_size();
  // FIXME. This need be cleaned up.
  if (NumArgs < NumNamedArgs) {
    Diag(lbrac, diag::err_typecheck_call_too_few_args)
      << 2 << NumNamedArgs << NumArgs;
    return false;
  }

  bool IsError = false;
  for (unsigned i = 0; i < NumNamedArgs; i++) {
    // We can't do any type-checking on a type-dependent argument.
    if (Args[i]->isTypeDependent())
      continue;

    Expr *argExpr = Args[i];

    ParmVarDecl *Param = Method->param_begin()[i];
    assert(argExpr && "CheckMessageArgumentTypes(): missing expression");

    if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
                            Param->getType(),
                            PDiag(diag::err_call_incomplete_argument)
                              << argExpr->getSourceRange()))
      return true;

    InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
                                                                      Param);
    ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
    if (ArgE.isInvalid())
      IsError = true;
    else
      Args[i] = ArgE.takeAs<Expr>();
  }

  // Promote additional arguments to variadic methods.
  if (Method->isVariadic()) {
    for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
      if (Args[i]->isTypeDependent())
        continue;

      IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
    }
  } else {
    // Check for extra arguments to non-variadic methods.
    if (NumArgs != NumNamedArgs) {
      Diag(Args[NumNamedArgs]->getLocStart(),
           diag::err_typecheck_call_too_many_args)
        << 2 /*method*/ << NumNamedArgs << NumArgs
        << Method->getSourceRange()
        << SourceRange(Args[NumNamedArgs]->getLocStart(),
                       Args[NumArgs-1]->getLocEnd());
    }
  }

  DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
  return IsError;
}
void NilArgChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
                                        CheckerContext &C) const {
  const ObjCInterfaceDecl *ID = msg.getReceiverInterface();
  if (!ID)
    return;

  FoundationClass Class = findKnownClass(ID);

  static const unsigned InvalidArgIndex = UINT_MAX;
  unsigned Arg = InvalidArgIndex;
  bool CanBeSubscript = false;
  
  if (Class == FC_NSString) {
    Selector S = msg.getSelector();
    
    if (S.isUnarySelector())
      return;
    
    // FIXME: This is going to be really slow doing these checks with
    //  lexical comparisons.
    
    std::string NameStr = S.getAsString();
    StringRef Name(NameStr);
    assert(!Name.empty());
    
    // FIXME: Checking for initWithFormat: will not work in most cases
    //  yet because [NSString alloc] returns id, not NSString*.  We will
    //  need support for tracking expected-type information in the analyzer
    //  to find these errors.
    if (Name == "caseInsensitiveCompare:" ||
        Name == "compare:" ||
        Name == "compare:options:" ||
        Name == "compare:options:range:" ||
        Name == "compare:options:range:locale:" ||
        Name == "componentsSeparatedByCharactersInSet:" ||
        Name == "initWithFormat:") {
      Arg = 0;
    }
  } else if (Class == FC_NSArray) {
    Selector S = msg.getSelector();

    if (S.isUnarySelector())
      return;

    if (S.getNameForSlot(0).equals("addObject")) {
      Arg = 0;
    } else if (S.getNameForSlot(0).equals("insertObject") &&
               S.getNameForSlot(1).equals("atIndex")) {
      Arg = 0;
    } else if (S.getNameForSlot(0).equals("replaceObjectAtIndex") &&
               S.getNameForSlot(1).equals("withObject")) {
      Arg = 1;
    } else if (S.getNameForSlot(0).equals("setObject") &&
               S.getNameForSlot(1).equals("atIndexedSubscript")) {
      Arg = 0;
      CanBeSubscript = true;
    } else if (S.getNameForSlot(0).equals("arrayByAddingObject")) {
      Arg = 0;
    }
  } else if (Class == FC_NSDictionary) {
    Selector S = msg.getSelector();

    if (S.isUnarySelector())
      return;

    if (S.getNameForSlot(0).equals("dictionaryWithObject") &&
        S.getNameForSlot(1).equals("forKey")) {
      Arg = 0;
      WarnIfNilArg(C, msg, /* Arg */1, Class);
    } else if (S.getNameForSlot(0).equals("setObject") &&
               S.getNameForSlot(1).equals("forKey")) {
      Arg = 0;
      WarnIfNilArg(C, msg, /* Arg */1, Class);
    } else if (S.getNameForSlot(0).equals("setObject") &&
               S.getNameForSlot(1).equals("forKeyedSubscript")) {
      CanBeSubscript = true;
      Arg = 0;
      WarnIfNilArg(C, msg, /* Arg */1, Class, CanBeSubscript);
    } else if (S.getNameForSlot(0).equals("removeObjectForKey")) {
      Arg = 0;
    }
  }


  // If argument is '0', report a warning.
  if ((Arg != InvalidArgIndex))
    WarnIfNilArg(C, msg, Arg, Class, CanBeSubscript);

}
Esempio n. 28
0
void Selector::appendSelector(const Selector &selector) {
  insert(end(), selector.begin(), selector.end());
}
Esempio n. 29
0
void SocketProxy::execute()
{
	std::list<SocketProxyPair>::iterator it;
	Selector selector;

	while( true ) {
		selector.reset();

		bool has_active_sockets = false;
		for	( it=m_socket_pairs.begin(); it != m_socket_pairs.end(); ++it ) {
			if( it->shutdown ) {
				continue;
			}
			has_active_sockets = true;
			if( it->buf_end > 0 ) {
					// drain the buffer before reading more
				selector.add_fd(it->to_socket, Selector::IO_WRITE);
			}
			else {
				selector.add_fd(it->from_socket, Selector::IO_READ);
			}
		}

		if( !has_active_sockets ) {
			break;
		}

		selector.execute();

		for	( it=m_socket_pairs.begin(); it != m_socket_pairs.end(); ++it ) {
			if( it->shutdown ) {
				continue;
			}
			if( it->buf_end > 0 ) {
					// attempt to drain the buffer
				if( selector.fd_ready(it->to_socket, Selector::IO_WRITE) ) {
					int n = write(it->to_socket,&it->buf[it->buf_begin],it->buf_end-it->buf_begin);
					if( n > 0 ) {
						it->buf_begin += n;
						if( it->buf_begin >= it->buf_end ) {
							it->buf_begin = 0;
							it->buf_end = 0;
						}
					}
				}
			}
			else if( selector.fd_ready(it->from_socket, Selector::IO_READ) ) {
				int n = read(it->from_socket,it->buf,SOCKET_PROXY_BUFSIZE);
				if( n > 0 ) {
					it->buf_end = n;
				}
				else if( n == 0 ) {
						// the socket has closed
						// WIN32 lacks SHUT_RD=0 and SHUT_WR=1
					shutdown(it->from_socket,0);
					close(it->from_socket);
					shutdown(it->to_socket,1);
					close(it->to_socket);
					it->shutdown = true;
				}
				else if( n < 0 ) {
					MyString error_msg;
					error_msg.sprintf("Error reading from socket %d: %s\n",
									  it->from_socket, strerror(errno));
					setErrorMsg(error_msg.Value());
					break;
				}
			}
		}
	}
}
/// This callback is used to infer the types for Class variables. This info is
/// used later to validate messages that sent to classes. Class variables are
/// initialized with by invoking the 'class' method on a class.
/// This method is also used to infer the type information for the return
/// types.
// TODO: right now it only tracks generic types. Extend this to track every
// type in the DynamicTypeMap and diagnose type errors!
void DynamicTypePropagation::checkPostObjCMessage(const ObjCMethodCall &M,
                                                  CheckerContext &C) const {
  const ObjCMessageExpr *MessageExpr = M.getOriginExpr();

  SymbolRef RetSym = M.getReturnValue().getAsSymbol();
  if (!RetSym)
    return;

  Selector Sel = MessageExpr->getSelector();
  ProgramStateRef State = C.getState();
  // Inference for class variables.
  // We are only interested in cases where the class method is invoked on a
  // class. This method is provided by the runtime and available on all classes.
  if (MessageExpr->getReceiverKind() == ObjCMessageExpr::Class &&
      Sel.getAsString() == "class") {
    QualType ReceiverType = MessageExpr->getClassReceiver();
    const auto *ReceiverClassType = ReceiverType->getAs<ObjCObjectType>();
    QualType ReceiverClassPointerType =
        C.getASTContext().getObjCObjectPointerType(
            QualType(ReceiverClassType, 0));

    if (!ReceiverClassType->isSpecialized())
      return;
    const auto *InferredType =
        ReceiverClassPointerType->getAs<ObjCObjectPointerType>();
    assert(InferredType);

    State = State->set<MostSpecializedTypeArgsMap>(RetSym, InferredType);
    C.addTransition(State);
    return;
  }

  // Tracking for return types.
  SymbolRef RecSym = M.getReceiverSVal().getAsSymbol();
  if (!RecSym)
    return;

  const ObjCObjectPointerType *const *TrackedType =
      State->get<MostSpecializedTypeArgsMap>(RecSym);
  if (!TrackedType)
    return;

  ASTContext &ASTCtxt = C.getASTContext();
  const ObjCMethodDecl *Method =
      findMethodDecl(MessageExpr, *TrackedType, ASTCtxt);
  if (!Method)
    return;

  Optional<ArrayRef<QualType>> TypeArgs =
      (*TrackedType)->getObjCSubstitutions(Method->getDeclContext());
  if (!TypeArgs)
    return;

  QualType ResultType =
      getReturnTypeForMethod(Method, *TypeArgs, *TrackedType, ASTCtxt);
  // The static type is the same as the deduced type.
  if (ResultType.isNull())
    return;

  const MemRegion *RetRegion = M.getReturnValue().getAsRegion();
  ExplodedNode *Pred = C.getPredecessor();
  // When there is an entry available for the return symbol in DynamicTypeMap,
  // the call was inlined, and the information in the DynamicTypeMap is should
  // be precise.
  if (RetRegion && !State->get<DynamicTypeMap>(RetRegion)) {
    // TODO: we have duplicated information in DynamicTypeMap and
    // MostSpecializedTypeArgsMap. We should only store anything in the later if
    // the stored data differs from the one stored in the former.
    State = setDynamicTypeInfo(State, RetRegion, ResultType,
                               /*CanBeSubclass=*/true);
    Pred = C.addTransition(State);
  }

  const auto *ResultPtrType = ResultType->getAs<ObjCObjectPointerType>();

  if (!ResultPtrType || ResultPtrType->isUnspecialized())
    return;

  // When the result is a specialized type and it is not tracked yet, track it
  // for the result symbol.
  if (!State->get<MostSpecializedTypeArgsMap>(RetSym)) {
    State = State->set<MostSpecializedTypeArgsMap>(RetSym, ResultPtrType);
    C.addTransition(State, Pred);
  }
}