<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

class ExperimentalApiTest : public ExtensionApiTest {
public:
  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
  }
};

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {
  ASSERT_TRUE(RunExtensionTest("permissions/disabled")) << message_;

  // Since the experimental APIs require a flag, this will fail even though
  // It's enabled.
  // TODO(erikkay) This test is currently broken because LoadExtension in
  // ExtensionBrowserTest doesn't actually fail, it just times out.  To fix this
  // I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably
  // too much for the branch.  I'll enable this on trunk later.
  //ASSERT_FALSE(RunExtensionTest("permissions/enabled"))) << message_;
}

IN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {
  ASSERT_TRUE(RunExtensionTest("permissions/enabled")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {
  // At the time this test is being created, there is no experimental
  // function that will not be graduating soon, and does not require a
  // tab id as an argument.  So, we need the tab permission to get
  // a tab id.
  ASSERT_TRUE(RunExtensionTest("permissions/experimental_disabled"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FavIconPermission) {
  ASSERT_TRUE(RunExtensionTest("permissions/favicon")) << message_;
}
<commit_msg>Disable ExtensionApiTest.FavIconPermission on Linux<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

class ExperimentalApiTest : public ExtensionApiTest {
public:
  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
  }
};

// All kinds of crashes on Linux http://crbug.com/41027
#if defined(OS_LINUX)
#define FavIconPermission DISABLED_FavIconPermission
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {
  ASSERT_TRUE(RunExtensionTest("permissions/disabled")) << message_;

  // Since the experimental APIs require a flag, this will fail even though
  // It's enabled.
  // TODO(erikkay) This test is currently broken because LoadExtension in
  // ExtensionBrowserTest doesn't actually fail, it just times out.  To fix this
  // I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably
  // too much for the branch.  I'll enable this on trunk later.
  //ASSERT_FALSE(RunExtensionTest("permissions/enabled"))) << message_;
}

IN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {
  ASSERT_TRUE(RunExtensionTest("permissions/enabled")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {
  // At the time this test is being created, there is no experimental
  // function that will not be graduating soon, and does not require a
  // tab id as an argument.  So, we need the tab permission to get
  // a tab id.
  ASSERT_TRUE(RunExtensionTest("permissions/experimental_disabled"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FavIconPermission) {
  ASSERT_TRUE(RunExtensionTest("permissions/favicon")) << message_;
}
<|endoftext|>


<commit_before>//===--- ImplicitBoolCastCheck.cpp - clang-tidy----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "ImplicitBoolCastCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {

namespace {

const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;

AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
  return Node.getCastKind() == Kind;
}

AST_MATCHER(QualType, isBool) {
  return !Node.isNull() && Node->isBooleanType();
}

AST_MATCHER(Stmt, isMacroExpansion) {
  SourceManager &SM = Finder->getASTContext().getSourceManager();
  SourceLocation Loc = Node.getLocStart();
  return SM.isMacroBodyExpansion(Loc) || SM.isMacroArgExpansion(Loc);
}

bool isNULLMacroExpansion(const Stmt *Statement, ASTContext &Context) {
  SourceManager &SM = Context.getSourceManager();
  const LangOptions &LO = Context.getLangOpts();
  SourceLocation Loc = Statement->getLocStart();
  return SM.isMacroBodyExpansion(Loc) &&
         clang::Lexer::getImmediateMacroName(Loc, SM, LO) == "NULL";
}

AST_MATCHER(Stmt, isNULLMacroExpansion) {
  return isNULLMacroExpansion(&Node, Finder->getASTContext());
}

ast_matchers::internal::Matcher<Expr> createExceptionCasesMatcher() {
  return expr(anyOf(hasParent(explicitCastExpr()),
                    allOf(isMacroExpansion(), unless(isNULLMacroExpansion())),
                    isInTemplateInstantiation(),
                    hasAncestor(functionTemplateDecl())));
}

StatementMatcher createImplicitCastFromBoolMatcher() {
  return implicitCastExpr(
      unless(createExceptionCasesMatcher()),
      anyOf(hasCastKind(CK_IntegralCast), hasCastKind(CK_IntegralToFloating),
            // Prior to C++11 cast from bool literal to pointer was allowed.
            allOf(anyOf(hasCastKind(CK_NullToPointer),
                        hasCastKind(CK_NullToMemberPointer)),
                  hasSourceExpression(cxxBoolLiteral()))),
      hasSourceExpression(expr(hasType(qualType(isBool())))));
}

StringRef
getZeroLiteralToCompareWithForGivenType(CastKind CastExpressionKind,
                                        QualType CastSubExpressionType,
                                        ASTContext &Context) {
  switch (CastExpressionKind) {
  case CK_IntegralToBoolean:
    return CastSubExpressionType->isUnsignedIntegerType() ? "0u" : "0";

  case CK_FloatingToBoolean:
    return Context.hasSameType(CastSubExpressionType, Context.FloatTy) ? "0.0f"
                                                                       : "0.0";

  case CK_PointerToBoolean:
  case CK_MemberPointerToBoolean: // Fall-through on purpose.
    return Context.getLangOpts().CPlusPlus11 ? "nullptr" : "0";

  default:
    assert(false && "Unexpected cast kind");
  }
  return "";
}

bool isUnaryLogicalNotOperator(const Stmt *Statement) {
  const auto *UnaryOperatorExpression =
      llvm::dyn_cast<UnaryOperator>(Statement);
  return UnaryOperatorExpression != nullptr &&
         UnaryOperatorExpression->getOpcode() == UO_LNot;
}

bool areParensNeededForOverloadedOperator(OverloadedOperatorKind OperatorKind) {
  switch (OperatorKind) {
  case OO_New:
  case OO_Delete: // Fall-through on purpose.
  case OO_Array_New:
  case OO_Array_Delete:
  case OO_ArrowStar:
  case OO_Arrow:
  case OO_Call:
  case OO_Subscript:
    return false;

  default:
    return true;
  }
}

bool areParensNeededForStatement(const Stmt *Statement) {
  if (const CXXOperatorCallExpr *OverloadedOperatorCall =
          llvm::dyn_cast<CXXOperatorCallExpr>(Statement)) {
    return areParensNeededForOverloadedOperator(
        OverloadedOperatorCall->getOperator());
  }

  return llvm::isa<BinaryOperator>(Statement) ||
         llvm::isa<UnaryOperator>(Statement);
}

void addFixItHintsForGenericExpressionCastToBool(
    DiagnosticBuilder &Diagnostic, const ImplicitCastExpr *CastExpression,
    const Stmt *ParentStatement, ASTContext &Context) {
  // In case of expressions like (! integer), we should remove the redundant not
  // operator and use inverted comparison (integer == 0).
  bool InvertComparison =
      ParentStatement != nullptr && isUnaryLogicalNotOperator(ParentStatement);
  if (InvertComparison) {
    SourceLocation ParentStartLoc = ParentStatement->getLocStart();
    SourceLocation ParentEndLoc =
        llvm::cast<UnaryOperator>(ParentStatement)->getSubExpr()->getLocStart();
    Diagnostic.AddFixItHint(FixItHint::CreateRemoval(
        CharSourceRange::getCharRange(ParentStartLoc, ParentEndLoc)));

    auto FurtherParents = Context.getParents(*ParentStatement);
    ParentStatement = FurtherParents[0].get<Stmt>();
  }

  const Expr *SubExpression = CastExpression->getSubExpr();

  bool NeedInnerParens = areParensNeededForStatement(SubExpression);
  bool NeedOuterParens = ParentStatement != nullptr &&
                         areParensNeededForStatement(ParentStatement);

  std::string StartLocInsertion;

  if (NeedOuterParens) {
    StartLocInsertion += "(";
  }
  if (NeedInnerParens) {
    StartLocInsertion += "(";
  }

  if (!StartLocInsertion.empty()) {
    SourceLocation StartLoc = CastExpression->getLocStart();
    Diagnostic.AddFixItHint(
        FixItHint::CreateInsertion(StartLoc, StartLocInsertion));
  }

  std::string EndLocInsertion;

  if (NeedInnerParens) {
    EndLocInsertion += ")";
  }

  if (InvertComparison) {
    EndLocInsertion += " == ";
  } else {
    EndLocInsertion += " != ";
  }

  EndLocInsertion += getZeroLiteralToCompareWithForGivenType(
      CastExpression->getCastKind(), SubExpression->getType(), Context);

  if (NeedOuterParens) {
    EndLocInsertion += ")";
  }

  SourceLocation EndLoc = Lexer::getLocForEndOfToken(
      CastExpression->getLocEnd(), 0, Context.getSourceManager(),
      Context.getLangOpts());
  Diagnostic.AddFixItHint(FixItHint::CreateInsertion(EndLoc, EndLocInsertion));
}

StringRef getEquivalentBoolLiteralForExpression(const Expr *Expression,
                                                ASTContext &Context) {
  if (isNULLMacroExpansion(Expression, Context)) {
    return "false";
  }

  if (const auto *IntLit = llvm::dyn_cast<IntegerLiteral>(Expression)) {
    return (IntLit->getValue() == 0) ? "false" : "true";
  }

  if (const auto *FloatLit = llvm::dyn_cast<FloatingLiteral>(Expression)) {
    llvm::APFloat FloatLitAbsValue = FloatLit->getValue();
    FloatLitAbsValue.clearSign();
    return (FloatLitAbsValue.bitcastToAPInt() == 0) ? "false" : "true";
  }

  if (const auto *CharLit = llvm::dyn_cast<CharacterLiteral>(Expression)) {
    return (CharLit->getValue() == 0) ? "false" : "true";
  }

  if (llvm::isa<StringLiteral>(Expression->IgnoreCasts())) {
    return "true";
  }

  return StringRef();
}

void addFixItHintsForLiteralCastToBool(DiagnosticBuilder &Diagnostic,
                                       const ImplicitCastExpr *CastExpression,
                                       StringRef EquivalentLiteralExpression) {
  SourceLocation StartLoc = CastExpression->getLocStart();
  SourceLocation EndLoc = CastExpression->getLocEnd();

  Diagnostic.AddFixItHint(FixItHint::CreateReplacement(
      CharSourceRange::getTokenRange(StartLoc, EndLoc),
      EquivalentLiteralExpression));
}

void addFixItHintsForGenericExpressionCastFromBool(
    DiagnosticBuilder &Diagnostic, const ImplicitCastExpr *CastExpression,
    ASTContext &Context, StringRef OtherType) {
  const Expr *SubExpression = CastExpression->getSubExpr();
  bool NeedParens = !llvm::isa<ParenExpr>(SubExpression);

  std::string StartLocInsertion = "static_cast<";
  StartLocInsertion += OtherType.str();
  StartLocInsertion += ">";
  if (NeedParens) {
    StartLocInsertion += "(";
  }

  SourceLocation StartLoc = CastExpression->getLocStart();
  Diagnostic.AddFixItHint(
      FixItHint::CreateInsertion(StartLoc, StartLocInsertion));

  if (NeedParens) {
    SourceLocation EndLoc = Lexer::getLocForEndOfToken(
        CastExpression->getLocEnd(), 0, Context.getSourceManager(),
        Context.getLangOpts());

    Diagnostic.AddFixItHint(FixItHint::CreateInsertion(EndLoc, ")"));
  }
}

StringRef getEquivalentLiteralForBoolLiteral(
    const CXXBoolLiteralExpr *BoolLiteralExpression, QualType DestinationType,
    ASTContext &Context) {
  // Prior to C++11, false literal could be implicitly converted to pointer.
  if (!Context.getLangOpts().CPlusPlus11 &&
      (DestinationType->isPointerType() ||
       DestinationType->isMemberPointerType()) &&
      BoolLiteralExpression->getValue() == false) {
    return "0";
  }

  if (DestinationType->isFloatingType()) {
    if (BoolLiteralExpression->getValue() == true) {
      return Context.hasSameType(DestinationType, Context.FloatTy) ? "1.0f"
                                                                   : "1.0";
    }
    return Context.hasSameType(DestinationType, Context.FloatTy) ? "0.0f"
                                                                 : "0.0";
  }

  if (BoolLiteralExpression->getValue() == true) {
    return DestinationType->isUnsignedIntegerType() ? "1u" : "1";
  }
  return DestinationType->isUnsignedIntegerType() ? "0u" : "0";
}

void addFixItHintsForLiteralCastFromBool(DiagnosticBuilder &Diagnostic,
                                         const ImplicitCastExpr *CastExpression,
                                         ASTContext &Context,
                                         QualType DestinationType) {
  SourceLocation StartLoc = CastExpression->getLocStart();
  SourceLocation EndLoc = CastExpression->getLocEnd();
  const auto *BoolLiteralExpression =
      llvm::dyn_cast<CXXBoolLiteralExpr>(CastExpression->getSubExpr());

  Diagnostic.AddFixItHint(FixItHint::CreateReplacement(
      CharSourceRange::getTokenRange(StartLoc, EndLoc),
      getEquivalentLiteralForBoolLiteral(BoolLiteralExpression, DestinationType,
                                         Context)));
}

StatementMatcher createConditionalExpressionMatcher() {
  return stmt(anyOf(ifStmt(), conditionalOperator(),
                    parenExpr(hasParent(conditionalOperator()))));
}

bool isAllowedConditionalCast(const ImplicitCastExpr *CastExpression,
                              ASTContext &Context) {
  auto AllowedConditionalMatcher = stmt(hasParent(stmt(
      anyOf(createConditionalExpressionMatcher(),
            unaryOperator(hasOperatorName("!"),
                          hasParent(createConditionalExpressionMatcher()))))));

  auto MatchResult = match(AllowedConditionalMatcher, *CastExpression, Context);
  return !MatchResult.empty();
}

} // anonymous namespace

void ImplicitBoolCastCheck::registerMatchers(MatchFinder *Finder) {
  // This check doesn't make much sense if we run it on language without
  // built-in bool support.
  if (!getLangOpts().Bool) {
    return;
  }

  Finder->addMatcher(
      implicitCastExpr(
          // Exclude cases common to implicit cast to and from bool.
          unless(createExceptionCasesMatcher()),
          // Exclude case of using if or while statements with variable
          // declaration, e.g.:
          //   if (int var = functionCall()) {}
          unless(
              hasParent(stmt(anyOf(ifStmt(), whileStmt()), has(declStmt())))),
          anyOf(hasCastKind(CK_IntegralToBoolean),
                hasCastKind(CK_FloatingToBoolean),
                hasCastKind(CK_PointerToBoolean),
                hasCastKind(CK_MemberPointerToBoolean)),
          // Retrive also parent statement, to check if we need additional
          // parens in replacement.
          anyOf(hasParent(stmt().bind("parentStmt")), anything()))
          .bind("implicitCastToBool"),
      this);

  Finder->addMatcher(
      implicitCastExpr(
          createImplicitCastFromBoolMatcher(),
          // Exclude comparisons of bools, as they are always cast to integers
          // in such context:
          //   bool_expr_a == bool_expr_b
          //   bool_expr_a != bool_expr_b
          unless(hasParent(binaryOperator(
              anyOf(hasOperatorName("=="), hasOperatorName("!=")),
              hasLHS(createImplicitCastFromBoolMatcher()),
              hasRHS(createImplicitCastFromBoolMatcher())))),
          // Check also for nested casts, for example: bool -> int -> float.
          anyOf(hasParent(implicitCastExpr().bind("furtherImplicitCast")),
                anything()))
          .bind("implicitCastFromBool"),
      this);
}

void ImplicitBoolCastCheck::check(const MatchFinder::MatchResult &Result) {
  if (const auto *CastToBool =
          Result.Nodes.getNodeAs<ImplicitCastExpr>("implicitCastToBool")) {
    const auto *ParentStatement = Result.Nodes.getNodeAs<Stmt>("parentStmt");
    return handleCastToBool(CastToBool, ParentStatement, *Result.Context);
  }

  if (const auto *CastFromBool =
          Result.Nodes.getNodeAs<ImplicitCastExpr>("implicitCastFromBool")) {
    const auto *FurtherImplicitCastExpression =
        Result.Nodes.getNodeAs<ImplicitCastExpr>("furtherImplicitCast");
    return handleCastFromBool(CastFromBool, FurtherImplicitCastExpression,
                              *Result.Context);
  }
}

void ImplicitBoolCastCheck::handleCastToBool(
    const ImplicitCastExpr *CastExpression, const Stmt *ParentStatement,
    ASTContext &Context) {
  if (AllowConditionalPointerCasts &&
      (CastExpression->getCastKind() == CK_PointerToBoolean ||
       CastExpression->getCastKind() == CK_MemberPointerToBoolean) &&
      isAllowedConditionalCast(CastExpression, Context)) {
    return;
  }

  if (AllowConditionalIntegerCasts &&
      CastExpression->getCastKind() == CK_IntegralToBoolean &&
      isAllowedConditionalCast(CastExpression, Context)) {
    return;
  }

  std::string OtherType = CastExpression->getSubExpr()->getType().getAsString();
  DiagnosticBuilder Diagnostic =
      diag(CastExpression->getLocStart(), "implicit cast '%0' -> bool")
      << OtherType;

  StringRef EquivalentLiteralExpression = getEquivalentBoolLiteralForExpression(
      CastExpression->getSubExpr(), Context);
  if (!EquivalentLiteralExpression.empty()) {
    addFixItHintsForLiteralCastToBool(Diagnostic, CastExpression,
                                      EquivalentLiteralExpression);
  } else {
    addFixItHintsForGenericExpressionCastToBool(Diagnostic, CastExpression,
                                                ParentStatement, Context);
  }
}

void ImplicitBoolCastCheck::handleCastFromBool(
    const ImplicitCastExpr *CastExpression,
    const ImplicitCastExpr *FurtherImplicitCastExpression,
    ASTContext &Context) {
  QualType DestinationType = (FurtherImplicitCastExpression != nullptr)
                                 ? FurtherImplicitCastExpression->getType()
                                 : CastExpression->getType();
  std::string DestinationTypeString = DestinationType.getAsString();
  DiagnosticBuilder Diagnostic =
      diag(CastExpression->getLocStart(), "implicit cast bool -> '%0'")
      << DestinationTypeString;

  if (llvm::isa<CXXBoolLiteralExpr>(CastExpression->getSubExpr())) {
    addFixItHintsForLiteralCastFromBool(Diagnostic, CastExpression, Context,
                                        DestinationType);
  } else {
    addFixItHintsForGenericExpressionCastFromBool(
        Diagnostic, CastExpression, Context, DestinationTypeString);
  }
}

} // namespace tidy
} // namespace clang
<commit_msg>assert(false) -> llvm_unreachable.<commit_after>//===--- ImplicitBoolCastCheck.cpp - clang-tidy----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "ImplicitBoolCastCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {

namespace {

const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr;

AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) {
  return Node.getCastKind() == Kind;
}

AST_MATCHER(QualType, isBool) {
  return !Node.isNull() && Node->isBooleanType();
}

AST_MATCHER(Stmt, isMacroExpansion) {
  SourceManager &SM = Finder->getASTContext().getSourceManager();
  SourceLocation Loc = Node.getLocStart();
  return SM.isMacroBodyExpansion(Loc) || SM.isMacroArgExpansion(Loc);
}

bool isNULLMacroExpansion(const Stmt *Statement, ASTContext &Context) {
  SourceManager &SM = Context.getSourceManager();
  const LangOptions &LO = Context.getLangOpts();
  SourceLocation Loc = Statement->getLocStart();
  return SM.isMacroBodyExpansion(Loc) &&
         clang::Lexer::getImmediateMacroName(Loc, SM, LO) == "NULL";
}

AST_MATCHER(Stmt, isNULLMacroExpansion) {
  return isNULLMacroExpansion(&Node, Finder->getASTContext());
}

ast_matchers::internal::Matcher<Expr> createExceptionCasesMatcher() {
  return expr(anyOf(hasParent(explicitCastExpr()),
                    allOf(isMacroExpansion(), unless(isNULLMacroExpansion())),
                    isInTemplateInstantiation(),
                    hasAncestor(functionTemplateDecl())));
}

StatementMatcher createImplicitCastFromBoolMatcher() {
  return implicitCastExpr(
      unless(createExceptionCasesMatcher()),
      anyOf(hasCastKind(CK_IntegralCast), hasCastKind(CK_IntegralToFloating),
            // Prior to C++11 cast from bool literal to pointer was allowed.
            allOf(anyOf(hasCastKind(CK_NullToPointer),
                        hasCastKind(CK_NullToMemberPointer)),
                  hasSourceExpression(cxxBoolLiteral()))),
      hasSourceExpression(expr(hasType(qualType(isBool())))));
}

StringRef
getZeroLiteralToCompareWithForGivenType(CastKind CastExpressionKind,
                                        QualType CastSubExpressionType,
                                        ASTContext &Context) {
  switch (CastExpressionKind) {
  case CK_IntegralToBoolean:
    return CastSubExpressionType->isUnsignedIntegerType() ? "0u" : "0";

  case CK_FloatingToBoolean:
    return Context.hasSameType(CastSubExpressionType, Context.FloatTy) ? "0.0f"
                                                                       : "0.0";

  case CK_PointerToBoolean:
  case CK_MemberPointerToBoolean: // Fall-through on purpose.
    return Context.getLangOpts().CPlusPlus11 ? "nullptr" : "0";

  default:
    llvm_unreachable("Unexpected cast kind");
  }
  return "";
}

bool isUnaryLogicalNotOperator(const Stmt *Statement) {
  const auto *UnaryOperatorExpression =
      llvm::dyn_cast<UnaryOperator>(Statement);
  return UnaryOperatorExpression != nullptr &&
         UnaryOperatorExpression->getOpcode() == UO_LNot;
}

bool areParensNeededForOverloadedOperator(OverloadedOperatorKind OperatorKind) {
  switch (OperatorKind) {
  case OO_New:
  case OO_Delete: // Fall-through on purpose.
  case OO_Array_New:
  case OO_Array_Delete:
  case OO_ArrowStar:
  case OO_Arrow:
  case OO_Call:
  case OO_Subscript:
    return false;

  default:
    return true;
  }
}

bool areParensNeededForStatement(const Stmt *Statement) {
  if (const CXXOperatorCallExpr *OverloadedOperatorCall =
          llvm::dyn_cast<CXXOperatorCallExpr>(Statement)) {
    return areParensNeededForOverloadedOperator(
        OverloadedOperatorCall->getOperator());
  }

  return llvm::isa<BinaryOperator>(Statement) ||
         llvm::isa<UnaryOperator>(Statement);
}

void addFixItHintsForGenericExpressionCastToBool(
    DiagnosticBuilder &Diagnostic, const ImplicitCastExpr *CastExpression,
    const Stmt *ParentStatement, ASTContext &Context) {
  // In case of expressions like (! integer), we should remove the redundant not
  // operator and use inverted comparison (integer == 0).
  bool InvertComparison =
      ParentStatement != nullptr && isUnaryLogicalNotOperator(ParentStatement);
  if (InvertComparison) {
    SourceLocation ParentStartLoc = ParentStatement->getLocStart();
    SourceLocation ParentEndLoc =
        llvm::cast<UnaryOperator>(ParentStatement)->getSubExpr()->getLocStart();
    Diagnostic.AddFixItHint(FixItHint::CreateRemoval(
        CharSourceRange::getCharRange(ParentStartLoc, ParentEndLoc)));

    auto FurtherParents = Context.getParents(*ParentStatement);
    ParentStatement = FurtherParents[0].get<Stmt>();
  }

  const Expr *SubExpression = CastExpression->getSubExpr();

  bool NeedInnerParens = areParensNeededForStatement(SubExpression);
  bool NeedOuterParens = ParentStatement != nullptr &&
                         areParensNeededForStatement(ParentStatement);

  std::string StartLocInsertion;

  if (NeedOuterParens) {
    StartLocInsertion += "(";
  }
  if (NeedInnerParens) {
    StartLocInsertion += "(";
  }

  if (!StartLocInsertion.empty()) {
    SourceLocation StartLoc = CastExpression->getLocStart();
    Diagnostic.AddFixItHint(
        FixItHint::CreateInsertion(StartLoc, StartLocInsertion));
  }

  std::string EndLocInsertion;

  if (NeedInnerParens) {
    EndLocInsertion += ")";
  }

  if (InvertComparison) {
    EndLocInsertion += " == ";
  } else {
    EndLocInsertion += " != ";
  }

  EndLocInsertion += getZeroLiteralToCompareWithForGivenType(
      CastExpression->getCastKind(), SubExpression->getType(), Context);

  if (NeedOuterParens) {
    EndLocInsertion += ")";
  }

  SourceLocation EndLoc = Lexer::getLocForEndOfToken(
      CastExpression->getLocEnd(), 0, Context.getSourceManager(),
      Context.getLangOpts());
  Diagnostic.AddFixItHint(FixItHint::CreateInsertion(EndLoc, EndLocInsertion));
}

StringRef getEquivalentBoolLiteralForExpression(const Expr *Expression,
                                                ASTContext &Context) {
  if (isNULLMacroExpansion(Expression, Context)) {
    return "false";
  }

  if (const auto *IntLit = llvm::dyn_cast<IntegerLiteral>(Expression)) {
    return (IntLit->getValue() == 0) ? "false" : "true";
  }

  if (const auto *FloatLit = llvm::dyn_cast<FloatingLiteral>(Expression)) {
    llvm::APFloat FloatLitAbsValue = FloatLit->getValue();
    FloatLitAbsValue.clearSign();
    return (FloatLitAbsValue.bitcastToAPInt() == 0) ? "false" : "true";
  }

  if (const auto *CharLit = llvm::dyn_cast<CharacterLiteral>(Expression)) {
    return (CharLit->getValue() == 0) ? "false" : "true";
  }

  if (llvm::isa<StringLiteral>(Expression->IgnoreCasts())) {
    return "true";
  }

  return StringRef();
}

void addFixItHintsForLiteralCastToBool(DiagnosticBuilder &Diagnostic,
                                       const ImplicitCastExpr *CastExpression,
                                       StringRef EquivalentLiteralExpression) {
  SourceLocation StartLoc = CastExpression->getLocStart();
  SourceLocation EndLoc = CastExpression->getLocEnd();

  Diagnostic.AddFixItHint(FixItHint::CreateReplacement(
      CharSourceRange::getTokenRange(StartLoc, EndLoc),
      EquivalentLiteralExpression));
}

void addFixItHintsForGenericExpressionCastFromBool(
    DiagnosticBuilder &Diagnostic, const ImplicitCastExpr *CastExpression,
    ASTContext &Context, StringRef OtherType) {
  const Expr *SubExpression = CastExpression->getSubExpr();
  bool NeedParens = !llvm::isa<ParenExpr>(SubExpression);

  std::string StartLocInsertion = "static_cast<";
  StartLocInsertion += OtherType.str();
  StartLocInsertion += ">";
  if (NeedParens) {
    StartLocInsertion += "(";
  }

  SourceLocation StartLoc = CastExpression->getLocStart();
  Diagnostic.AddFixItHint(
      FixItHint::CreateInsertion(StartLoc, StartLocInsertion));

  if (NeedParens) {
    SourceLocation EndLoc = Lexer::getLocForEndOfToken(
        CastExpression->getLocEnd(), 0, Context.getSourceManager(),
        Context.getLangOpts());

    Diagnostic.AddFixItHint(FixItHint::CreateInsertion(EndLoc, ")"));
  }
}

StringRef getEquivalentLiteralForBoolLiteral(
    const CXXBoolLiteralExpr *BoolLiteralExpression, QualType DestinationType,
    ASTContext &Context) {
  // Prior to C++11, false literal could be implicitly converted to pointer.
  if (!Context.getLangOpts().CPlusPlus11 &&
      (DestinationType->isPointerType() ||
       DestinationType->isMemberPointerType()) &&
      BoolLiteralExpression->getValue() == false) {
    return "0";
  }

  if (DestinationType->isFloatingType()) {
    if (BoolLiteralExpression->getValue() == true) {
      return Context.hasSameType(DestinationType, Context.FloatTy) ? "1.0f"
                                                                   : "1.0";
    }
    return Context.hasSameType(DestinationType, Context.FloatTy) ? "0.0f"
                                                                 : "0.0";
  }

  if (BoolLiteralExpression->getValue() == true) {
    return DestinationType->isUnsignedIntegerType() ? "1u" : "1";
  }
  return DestinationType->isUnsignedIntegerType() ? "0u" : "0";
}

void addFixItHintsForLiteralCastFromBool(DiagnosticBuilder &Diagnostic,
                                         const ImplicitCastExpr *CastExpression,
                                         ASTContext &Context,
                                         QualType DestinationType) {
  SourceLocation StartLoc = CastExpression->getLocStart();
  SourceLocation EndLoc = CastExpression->getLocEnd();
  const auto *BoolLiteralExpression =
      llvm::dyn_cast<CXXBoolLiteralExpr>(CastExpression->getSubExpr());

  Diagnostic.AddFixItHint(FixItHint::CreateReplacement(
      CharSourceRange::getTokenRange(StartLoc, EndLoc),
      getEquivalentLiteralForBoolLiteral(BoolLiteralExpression, DestinationType,
                                         Context)));
}

StatementMatcher createConditionalExpressionMatcher() {
  return stmt(anyOf(ifStmt(), conditionalOperator(),
                    parenExpr(hasParent(conditionalOperator()))));
}

bool isAllowedConditionalCast(const ImplicitCastExpr *CastExpression,
                              ASTContext &Context) {
  auto AllowedConditionalMatcher = stmt(hasParent(stmt(
      anyOf(createConditionalExpressionMatcher(),
            unaryOperator(hasOperatorName("!"),
                          hasParent(createConditionalExpressionMatcher()))))));

  auto MatchResult = match(AllowedConditionalMatcher, *CastExpression, Context);
  return !MatchResult.empty();
}

} // anonymous namespace

void ImplicitBoolCastCheck::registerMatchers(MatchFinder *Finder) {
  // This check doesn't make much sense if we run it on language without
  // built-in bool support.
  if (!getLangOpts().Bool) {
    return;
  }

  Finder->addMatcher(
      implicitCastExpr(
          // Exclude cases common to implicit cast to and from bool.
          unless(createExceptionCasesMatcher()),
          // Exclude case of using if or while statements with variable
          // declaration, e.g.:
          //   if (int var = functionCall()) {}
          unless(
              hasParent(stmt(anyOf(ifStmt(), whileStmt()), has(declStmt())))),
          anyOf(hasCastKind(CK_IntegralToBoolean),
                hasCastKind(CK_FloatingToBoolean),
                hasCastKind(CK_PointerToBoolean),
                hasCastKind(CK_MemberPointerToBoolean)),
          // Retrive also parent statement, to check if we need additional
          // parens in replacement.
          anyOf(hasParent(stmt().bind("parentStmt")), anything()))
          .bind("implicitCastToBool"),
      this);

  Finder->addMatcher(
      implicitCastExpr(
          createImplicitCastFromBoolMatcher(),
          // Exclude comparisons of bools, as they are always cast to integers
          // in such context:
          //   bool_expr_a == bool_expr_b
          //   bool_expr_a != bool_expr_b
          unless(hasParent(binaryOperator(
              anyOf(hasOperatorName("=="), hasOperatorName("!=")),
              hasLHS(createImplicitCastFromBoolMatcher()),
              hasRHS(createImplicitCastFromBoolMatcher())))),
          // Check also for nested casts, for example: bool -> int -> float.
          anyOf(hasParent(implicitCastExpr().bind("furtherImplicitCast")),
                anything()))
          .bind("implicitCastFromBool"),
      this);
}

void ImplicitBoolCastCheck::check(const MatchFinder::MatchResult &Result) {
  if (const auto *CastToBool =
          Result.Nodes.getNodeAs<ImplicitCastExpr>("implicitCastToBool")) {
    const auto *ParentStatement = Result.Nodes.getNodeAs<Stmt>("parentStmt");
    return handleCastToBool(CastToBool, ParentStatement, *Result.Context);
  }

  if (const auto *CastFromBool =
          Result.Nodes.getNodeAs<ImplicitCastExpr>("implicitCastFromBool")) {
    const auto *FurtherImplicitCastExpression =
        Result.Nodes.getNodeAs<ImplicitCastExpr>("furtherImplicitCast");
    return handleCastFromBool(CastFromBool, FurtherImplicitCastExpression,
                              *Result.Context);
  }
}

void ImplicitBoolCastCheck::handleCastToBool(
    const ImplicitCastExpr *CastExpression, const Stmt *ParentStatement,
    ASTContext &Context) {
  if (AllowConditionalPointerCasts &&
      (CastExpression->getCastKind() == CK_PointerToBoolean ||
       CastExpression->getCastKind() == CK_MemberPointerToBoolean) &&
      isAllowedConditionalCast(CastExpression, Context)) {
    return;
  }

  if (AllowConditionalIntegerCasts &&
      CastExpression->getCastKind() == CK_IntegralToBoolean &&
      isAllowedConditionalCast(CastExpression, Context)) {
    return;
  }

  std::string OtherType = CastExpression->getSubExpr()->getType().getAsString();
  DiagnosticBuilder Diagnostic =
      diag(CastExpression->getLocStart(), "implicit cast '%0' -> bool")
      << OtherType;

  StringRef EquivalentLiteralExpression = getEquivalentBoolLiteralForExpression(
      CastExpression->getSubExpr(), Context);
  if (!EquivalentLiteralExpression.empty()) {
    addFixItHintsForLiteralCastToBool(Diagnostic, CastExpression,
                                      EquivalentLiteralExpression);
  } else {
    addFixItHintsForGenericExpressionCastToBool(Diagnostic, CastExpression,
                                                ParentStatement, Context);
  }
}

void ImplicitBoolCastCheck::handleCastFromBool(
    const ImplicitCastExpr *CastExpression,
    const ImplicitCastExpr *FurtherImplicitCastExpression,
    ASTContext &Context) {
  QualType DestinationType = (FurtherImplicitCastExpression != nullptr)
                                 ? FurtherImplicitCastExpression->getType()
                                 : CastExpression->getType();
  std::string DestinationTypeString = DestinationType.getAsString();
  DiagnosticBuilder Diagnostic =
      diag(CastExpression->getLocStart(), "implicit cast bool -> '%0'")
      << DestinationTypeString;

  if (llvm::isa<CXXBoolLiteralExpr>(CastExpression->getSubExpr())) {
    addFixItHintsForLiteralCastFromBool(Diagnostic, CastExpression, Context,
                                        DestinationType);
  } else {
    addFixItHintsForGenericExpressionCastFromBool(
        Diagnostic, CastExpression, Context, DestinationTypeString);
  }
}

} // namespace tidy
} // namespace clang
<|endoftext|>


<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#ifndef __BSE_PLATFORM_HH__
#define __BSE_PLATFORM_HH__

#include <sfi/cxxaux.hh>
#include <thread>

namespace Bse {

// == Timestamp Handling ==
uint64  timestamp_startup    ();        // µseconds
uint64  timestamp_realtime   ();        // µseconds
uint64  timestamp_benchmark  ();        // nseconds
uint64  timestamp_resolution ();        // nseconds
String  timestamp_format     (uint64 stamp, uint maxlength = 8);
uint64  monotonic_counter    ();

// == process names ==
String      program_alias         ();                   ///< Retrieve the program name as used for logging or debug messages.
void        program_alias_init    (String customname);  ///< Set program_alias to a non-localized alias other than program_argv0 if desired.
String      application_name      ();                   ///< Retrieve the localized program name intended for user display.
void        application_name_init (String desktopname); ///< Set the application_name to a name other than program_alias if desired.
String      program_cwd           ();                   ///< The current working directory during startup.
std::string executable_name       ();                   ///< Retrieve the name part of executable_path().
std::string executable_path       ();                   ///< Retrieve the path to the currently running executable.
std::string cpu_info              ();                   ///< Retrieve string identifying the runtime CPU type.

// == Thread Status ==
/// Acquire information about a task (process or thread) at runtime.
struct TaskStatus {
  enum State { UNKNOWN = '?', RUNNING = 'R', SLEEPING = 'S', DISKWAIT = 'D', STOPPED = 'T', PAGING = 'W', ZOMBIE = 'Z', DEBUG = 'X', };
  int           process_id;     ///< Process ID.
  int           task_id;        ///< Process ID or thread ID.
  String        name;           ///< Thread name (set by user).
  State         state;          ///< Thread state.
  int           processor;      ///< Rrunning processor number.
  int           priority;       ///< Priority or nice value.
  uint64        utime;          ///< Userspace time.
  uint64        stime;          ///< System time.
  uint64        cutime;         ///< Userspace time of dead children.
  uint64        cstime;         ///< System time of dead children.
  uint64        ac_stamp;       ///< Accounting stamp.
  uint64        ac_utime, ac_stime, ac_cutime, ac_cstime;
  explicit      TaskStatus (int pid, int tid = -1); ///< Construct from process ID and optionally thread ID.
  bool          update     ();  ///< Update status information, might return false if called too frequently.
  String        string     ();  ///< Retrieve string representation of the status information.
};

// == Thread Info ==
using ThreadId = std::thread::id;
ThreadId this_thread_self        ();
void     this_thread_set_name    (const String &name16chars);
String   this_thread_get_name    ();
int      this_thread_getpid      ();
int      this_thread_gettid      ();
int      this_thread_online_cpus ();

// == Debugging Aids ==
extern inline void breakpoint               () BSE_ALWAYS_INLINE;       ///< Cause a debugging breakpoint, for development only.
extern int       (*backtrace_pointers)      (void **buffer, int size);  ///< Capture stack frames for a backtrace (on __GLIBC__).
String             pretty_backtrace         (void **ptrs, ssize_t nptrs, const char *file, int line, const char *func);
StringVector       pretty_backtrace_symbols (void **pointers, const int nptrs);
#define BSE_BACKTRACE_MAXDEPTH   1024                   ///< Maximum depth for runtime backtrace generation.
/// Print backtrace of the current line to stderr.
#define BSE_BACKTRACE()          ({ ::Bse::printerr ("%s", BSE_BACKTRACE_STRING()); })
/// Generate a string that contains a backtrace of the current line.
#define BSE_BACKTRACE_STRING()   ({ void *__p_[BSE_BACKTRACE_MAXDEPTH]; \
      const String __s_ = ::Bse::pretty_backtrace (__p_, ::Bse::backtrace_pointers (__p_, sizeof (__p_) / sizeof (__p_[0])), \
                                                   __FILE__, __LINE__, __func__); __s_; })

// == Implementation Details ==
#if (defined __i386__ || defined __x86_64__)
inline void breakpoint() { __asm__ __volatile__ ("int $03"); }
#elif defined __alpha__ && !defined __osf__
inline void breakpoint() { __asm__ __volatile__ ("bpt"); }
#else   // !__i386__ && !__alpha__
inline void breakpoint() { __builtin_trap(); }
#endif

} // Bse

#endif // __BSE_PLATFORM_HH__
<commit_msg>SFI: provide BSE_CACHE_LINE_ALIGNMENT and BSE_?FENCE directives<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#ifndef __BSE_PLATFORM_HH__
#define __BSE_PLATFORM_HH__

#include <sfi/cxxaux.hh>
#include <thread>

namespace Bse {

// == Timestamp Handling ==
uint64  timestamp_startup    ();        // µseconds
uint64  timestamp_realtime   ();        // µseconds
uint64  timestamp_benchmark  ();        // nseconds
uint64  timestamp_resolution ();        // nseconds
String  timestamp_format     (uint64 stamp, uint maxlength = 8);
uint64  monotonic_counter    ();

// == process names ==
String      program_alias         ();                   ///< Retrieve the program name as used for logging or debug messages.
void        program_alias_init    (String customname);  ///< Set program_alias to a non-localized alias other than program_argv0 if desired.
String      application_name      ();                   ///< Retrieve the localized program name intended for user display.
void        application_name_init (String desktopname); ///< Set the application_name to a name other than program_alias if desired.
String      program_cwd           ();                   ///< The current working directory during startup.
std::string executable_name       ();                   ///< Retrieve the name part of executable_path().
std::string executable_path       ();                   ///< Retrieve the path to the currently running executable.
std::string cpu_info              ();                   ///< Retrieve string identifying the runtime CPU type.

// == Thread Status ==
/// Acquire information about a task (process or thread) at runtime.
struct TaskStatus {
  enum State { UNKNOWN = '?', RUNNING = 'R', SLEEPING = 'S', DISKWAIT = 'D', STOPPED = 'T', PAGING = 'W', ZOMBIE = 'Z', DEBUG = 'X', };
  int           process_id;     ///< Process ID.
  int           task_id;        ///< Process ID or thread ID.
  String        name;           ///< Thread name (set by user).
  State         state;          ///< Thread state.
  int           processor;      ///< Rrunning processor number.
  int           priority;       ///< Priority or nice value.
  uint64        utime;          ///< Userspace time.
  uint64        stime;          ///< System time.
  uint64        cutime;         ///< Userspace time of dead children.
  uint64        cstime;         ///< System time of dead children.
  uint64        ac_stamp;       ///< Accounting stamp.
  uint64        ac_utime, ac_stime, ac_cutime, ac_cstime;
  explicit      TaskStatus (int pid, int tid = -1); ///< Construct from process ID and optionally thread ID.
  bool          update     ();  ///< Update status information, might return false if called too frequently.
  String        string     ();  ///< Retrieve string representation of the status information.
};

// == Thread Info ==
using ThreadId = std::thread::id;
ThreadId this_thread_self        ();
void     this_thread_set_name    (const String &name16chars);
String   this_thread_get_name    ();
int      this_thread_getpid      ();
int      this_thread_gettid      ();
int      this_thread_online_cpus ();

// == Debugging Aids ==
extern inline void breakpoint               () BSE_ALWAYS_INLINE;       ///< Cause a debugging breakpoint, for development only.
extern int       (*backtrace_pointers)      (void **buffer, int size);  ///< Capture stack frames for a backtrace (on __GLIBC__).
String             pretty_backtrace         (void **ptrs, ssize_t nptrs, const char *file, int line, const char *func);
StringVector       pretty_backtrace_symbols (void **pointers, const int nptrs);
#define BSE_BACKTRACE_MAXDEPTH   1024                   ///< Maximum depth for runtime backtrace generation.
/// Print backtrace of the current line to stderr.
#define BSE_BACKTRACE()          ({ ::Bse::printerr ("%s", BSE_BACKTRACE_STRING()); })
/// Generate a string that contains a backtrace of the current line.
#define BSE_BACKTRACE_STRING()   ({ void *__p_[BSE_BACKTRACE_MAXDEPTH]; \
      const String __s_ = ::Bse::pretty_backtrace (__p_, ::Bse::backtrace_pointers (__p_, sizeof (__p_) / sizeof (__p_[0])), \
                                                   __FILE__, __LINE__, __func__); __s_; })

// == Memory Barriers ==
#define  BSE_CACHE_LINE_ALIGNMENT       64      // generally enough on x86, see getconf LEVEL1_DCACHE_LINESIZE
#if defined __x86_64__ || defined __amd64__
#define  BSE_MFENCE __sync_synchronize()
#define  BSE_SFENCE __asm__ __volatile__ ("sfence" ::: "memory")
#define  BSE_LFENCE __asm__ __volatile__ ("lfence" ::: "memory")
#else // !x86/64
#define  BSE_SFENCE __sync_synchronize() ///< Store Fence - prevent processor (and compiler) from reordering stores (write barrier).
#define  BSE_LFENCE __sync_synchronize() ///< Load Fence  - prevent processor (and compiler) from reordering loads (read barrier).
/// Memory Fence - prevent processor (and compiler) from reordering loads/stores (read/write barrier), see also std::atomic_thread_fence().
#define  BSE_MFENCE __sync_synchronize()
#endif
/// Compiler Fence, prevent compiler from reordering non-volatile loads/stores, see also std::atomic_signal_fence().
#define  BSE_CFENCE __asm__ __volatile__ ("" ::: "memory")

// == Implementation Details ==
#if (defined __i386__ || defined __x86_64__)
inline void breakpoint() { __asm__ __volatile__ ("int $03"); }
#elif defined __alpha__ && !defined __osf__
inline void breakpoint() { __asm__ __volatile__ ("bpt"); }
#else   // !__i386__ && !__alpha__
inline void breakpoint() { __builtin_trap(); }
#endif

} // Bse

#endif // __BSE_PLATFORM_HH__
<|endoftext|>


<commit_before>#include "ping.h"

#include <QProcess>
#include <QTextStream>
#include <QRegExp>

class Ping::Private : public QObject
{
    Q_OBJECT

public:
    Private(Ping* q)
    : q(q)
    , status(Ping::NotRunning)
    , amount(10)
    , timeout(1)
    , stream(&process)
    {
        connect(&process, SIGNAL(started()), this, SLOT(started()));
        connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(finished(int,QProcess::ExitStatus)));
        connect(&process, SIGNAL(readyRead()), this, SLOT(readyRead()));
    }

    Ping* q;

    // Properties
    Ping::Status status;
    QString host;
    int amount;
    int timeout;

    QList<int> pingTime;

    QProcess process;
    QTextStream stream;

    // Functions
    void setStatus(Ping::Status status);

public slots:
    void started();
    void finished(int exitCode, QProcess::ExitStatus exitStatus);
    void readyRead();
};

void Ping::Private::setStatus(Ping::Status status)
{
    if (this->status != status) {
        this->status = status;
        emit q->statusChanged(status);
    }
}

void Ping::Private::started()
{
    pingTime.clear();

    setStatus(Ping::Running);
    emit q->started();
}

void Ping::Private::finished(int exitCode, QProcess::ExitStatus exitStatus)
{
    Q_UNUSED(exitCode);
    Q_UNUSED(exitStatus);

    setStatus(Ping::NotRunning);
    emit q->stopped();
}

void Ping::Private::readyRead()
{
    QRegExp re;
#if defined(Q_OS_WIN)
    // Antwort von 193.99.144.80: Bytes=32 Zeit=32ms TTL=245
    re.setPattern("=(\\d+)ms");
#elif defined(Q_OS_MAC) || defined(Q_OS_LINUX)
    // 64 bytes from 193.99.144.80: icmp_seq=0 ttl=245 time=32.031 ms
    re.setPattern("time=(\\d+).*ms");
#else
#error Platform code not implemented
#endif

    for(QString line = stream.readLine(); !line.isNull(); line = stream.readLine()) {
        if ( re.indexIn(line) == -1 )
            continue;

        int time = re.cap(1).toInt();
        pingTime.append(time);

        emit q->ping(time);
    }
}

Ping::Ping(QObject *parent)
: QObject(parent)
, d(new Private(this))
{
}

Ping::~Ping()
{
    d->process.kill();
    d->process.waitForFinished(500);
    delete d;
}

Ping::Status Ping::status() const
{
    return d->status;
}

Ping::ExitStatus Ping::exitStatus() const
{
    return (Ping::ExitStatus)d->process.exitStatus();
}

void Ping::setHost(const QString &host)
{
    if (d->host != host) {
        d->host = host;
        emit hostChanged(host);
    }
}

QString Ping::host() const
{
    return d->host;
}

void Ping::setAmount(int amount)
{
    if (d->amount != amount) {
        d->amount = amount;
        emit amountChanged(amount);
    }
}

int Ping::amount() const
{
    return d->amount;
}

void Ping::setTimeout(int timeout)
{
    if (d->timeout != timeout) {
        d->timeout = timeout;
        emit timeoutChanged(timeout);
    }
}

int Ping::timeout() const
{
    return d->timeout;
}

QList<int> Ping::pingTime() const
{
    return d->pingTime;
}

int Ping::averagePingTime() const
{
    int time = 0;
    foreach(int t, d->pingTime)
        time += t;

    return qRound( time / (double)d->pingTime.size() );
}

void Ping::start()
{
    QStringList args;
#ifdef Q_OS_LINUX
    args << "-c" << QString::number(d->amount)
         << "-n" // Don't resolve hostnames
#ifndef Q_OS_ANDROID
         << "-W" << QString::number(d->timeout);
#else
         /*<< "-w" << QString::number(d->timeout)*/;
#endif
#elif defined(Q_OS_MAC)
    args << "-c" << QString::number(d->amount)
         << "-t" << QString::number(d->timeout);
#elif defined(Q_OS_WIN)
    args << "-n" << QString::number(d->amount)
         << "-4" // ipv4
         << "-w" << QString::number(d->timeout * 1000);
#else
#error Platform ping code missing!
#endif

    args << d->host;

    d->process.start("ping", args);
}

void Ping::stop()
{
    d->process.kill();
}

void Ping::waitForFinished()
{
    d->process.waitForFinished(1000);
}

#include "ping.moc"
<commit_msg>kill ping before we start it again.<commit_after>#include "ping.h"

#include <QProcess>
#include <QTextStream>
#include <QRegExp>

class Ping::Private : public QObject
{
    Q_OBJECT

public:
    Private(Ping* q)
    : q(q)
    , status(Ping::NotRunning)
    , amount(10)
    , timeout(1)
    , stream(&process)
    {
        connect(&process, SIGNAL(started()), this, SLOT(started()));
        connect(&process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(finished(int,QProcess::ExitStatus)));
        connect(&process, SIGNAL(readyRead()), this, SLOT(readyRead()));
    }

    Ping* q;

    // Properties
    Ping::Status status;
    QString host;
    int amount;
    int timeout;

    QList<int> pingTime;

    QProcess process;
    QTextStream stream;

    // Functions
    void setStatus(Ping::Status status);

public slots:
    void started();
    void finished(int exitCode, QProcess::ExitStatus exitStatus);
    void readyRead();
};

void Ping::Private::setStatus(Ping::Status status)
{
    if (this->status != status) {
        this->status = status;
        emit q->statusChanged(status);
    }
}

void Ping::Private::started()
{
    pingTime.clear();

    setStatus(Ping::Running);
    emit q->started();
}

void Ping::Private::finished(int exitCode, QProcess::ExitStatus exitStatus)
{
    Q_UNUSED(exitCode);
    Q_UNUSED(exitStatus);

    setStatus(Ping::NotRunning);
    emit q->stopped();
}

void Ping::Private::readyRead()
{
    QRegExp re;
#if defined(Q_OS_WIN)
    // Antwort von 193.99.144.80: Bytes=32 Zeit=32ms TTL=245
    re.setPattern("=(\\d+)ms");
#elif defined(Q_OS_MAC) || defined(Q_OS_LINUX)
    // 64 bytes from 193.99.144.80: icmp_seq=0 ttl=245 time=32.031 ms
    re.setPattern("time=(\\d+).*ms");
#else
#error Platform code not implemented
#endif

    for(QString line = stream.readLine(); !line.isNull(); line = stream.readLine()) {
        if ( re.indexIn(line) == -1 )
            continue;

        int time = re.cap(1).toInt();
        pingTime.append(time);

        emit q->ping(time);
    }
}

Ping::Ping(QObject *parent)
: QObject(parent)
, d(new Private(this))
{
}

Ping::~Ping()
{
    d->process.kill();
    d->process.waitForFinished(500);
    delete d;
}

Ping::Status Ping::status() const
{
    return d->status;
}

Ping::ExitStatus Ping::exitStatus() const
{
    return (Ping::ExitStatus)d->process.exitStatus();
}

void Ping::setHost(const QString &host)
{
    if (d->host != host) {
        d->host = host;
        emit hostChanged(host);
    }
}

QString Ping::host() const
{
    return d->host;
}

void Ping::setAmount(int amount)
{
    if (d->amount != amount) {
        d->amount = amount;
        emit amountChanged(amount);
    }
}

int Ping::amount() const
{
    return d->amount;
}

void Ping::setTimeout(int timeout)
{
    if (d->timeout != timeout) {
        d->timeout = timeout;
        emit timeoutChanged(timeout);
    }
}

int Ping::timeout() const
{
    return d->timeout;
}

QList<int> Ping::pingTime() const
{
    return d->pingTime;
}

int Ping::averagePingTime() const
{
    int time = 0;
    foreach(int t, d->pingTime)
        time += t;

    return qRound( time / (double)d->pingTime.size() );
}

void Ping::start()
{
    QStringList args;
#ifdef Q_OS_LINUX
    args << "-c" << QString::number(d->amount)
         << "-n" // Don't resolve hostnames
#ifndef Q_OS_ANDROID
         << "-W" << QString::number(d->timeout);
#else
         /*<< "-w" << QString::number(d->timeout)*/;
#endif
#elif defined(Q_OS_MAC)
    args << "-c" << QString::number(d->amount)
         << "-t" << QString::number(d->timeout);
#elif defined(Q_OS_WIN)
    args << "-n" << QString::number(d->amount)
         << "-4" // ipv4
         << "-w" << QString::number(d->timeout * 1000);
#else
#error Platform ping code missing!
#endif

    args << d->host;

    d->process.kill();
    d->process.start("ping", args);
}

void Ping::stop()
{
    d->process.kill();
}

void Ping::waitForFinished()
{
    d->process.waitForFinished(1000);
}

#include "ping.moc"
<|endoftext|>


<commit_before>#ifndef _SDD_MEM_REF_COUNTED_HH_
#define _SDD_MEM_REF_COUNTED_HH_

#include <cassert>
#include <cstdint>     // uint32_t
#include <functional>  // hash
#include <limits>      // numeric_limits
#include <type_traits> // is_nothrow_constructible
#include <utility>     // forward

#include <boost/intrusive/unordered_set.hpp>

#include "sdd/util/packed.hh"

namespace sdd { namespace mem {

/*------------------------------------------------------------------------------------------------*/

/// @internal
/// @brief A wrapper to associate a reference counter to a unified data.
///
/// This type is meant to be used by ptr, which takes care of incrementing and decrementing
/// the reference counter, as well as the deletion of the held data.
template <typename T, typename Hash = std::hash<T>>
class
#ifdef __clang__
LIBSDD_ATTRIBUTE_PACKED
#endif
ref_counted
{
  // Can't copy a ref_counted.
  ref_counted(const ref_counted&) = delete;
  ref_counted& operator=(const ref_counted&) = delete;

  // Can't move a ref_counted.
  ref_counted(ref_counted&&) = delete;
  ref_counted& operator=(ref_counted&&) = delete;

private:

  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  // The order is important here: data_ MUST be the last of all fields. This is necessary
  // because, for SDD, we allocate the alpha function directly behind the node, without any
  // indirection, to avoid a pointer. Thus, the address of the alpha function is computed
  // knowing this is right after the node.

  /// We choose a faster, unsafe mode.
  typedef boost::intrusive::link_mode<boost::intrusive::normal_link> link_mode;
  /// Used by Boost.Intrusive to manage the unicity table.
  boost::intrusive::unordered_set_member_hook<link_mode> member_hook_;

  /// The number of time the encapsulated data is referenced (reference-counting garbage collection)
  mutable uint32_t ref_count_;

  /// @brief The garbage collected data.
  ///
  /// The ptr class is responsible for the detection of dereferenced data and for
  /// instructing the unicity table to erase it.
  const T data_;

public:

  template <typename... Args>
  ref_counted(Args&&... args)
  noexcept(std::is_nothrow_constructible<T, Args...>::value)
		: member_hook_()
    , ref_count_(0)
    , data_(std::forward<Args>(args)...)
  {
  }

  /// @brief Get a reference of the unified data.
  const T&
  data()
  const noexcept
  {
    return data_;
  }

  /// @brief Get the number of extra bytes that may be used by the contained type.
  ///
  /// This information is needed when a data of variable length is allocated.
  std::size_t
  extra_bytes()
  const noexcept
  {
    // Static dispatch.
    return extra_bytes_impl(data_, 0);
  }

  /// @brief Called when the contained type defines extra_bytes.
  template <typename U>
  static auto
  extra_bytes_impl(const U& x, int)
  noexcept
  -> decltype(x.extra_bytes())
  {
    return x.extra_bytes();
  }

  /// @brief Called when the contained type doesn't define extra_bytes.
  template <typename U>
  static constexpr auto
  extra_bytes_impl(const U&, long)
  noexcept
  -> decltype(0)
  {
    return 0;
  }

private:

  /// A ptr should be able to access and modify the reference counter.
  template <typename U> friend class ptr;

  /// The unicity table needs to access member_hook_.
  template <typename U> friend class unique_table;

  /// @brief A ptr references that unified data.
  void
  increment_reference_counter()
  const noexcept
  {
    assert(ref_count_ < std::numeric_limits<uint32_t>::max());
    ++ref_count_;
  }

  /// @brief A ptr no longer references that unified data.
  void
  decrement_reference_counter()
  const noexcept
  {
    assert(ref_count_ > 0);
    --ref_count_;
  }

  /// @brief Tell if the unified data is no longer referenced.
  bool
  is_not_referenced()
  const noexcept
  {
    return ref_count_ == 0;
  }
};

/*------------------------------------------------------------------------------------------------*/

/// @internal
/// @related ref_counted
template <typename T, typename Hash>
inline
bool
operator==(const ref_counted<T, Hash>& lhs, const ref_counted<T, Hash>& rhs)
noexcept
{
  return lhs.data() == rhs.data();
}

/*------------------------------------------------------------------------------------------------*/

}} // namespace sdd::mem

namespace std {

/*------------------------------------------------------------------------------------------------*/

/// @internal
/// @brief Hash specialization for sdd::mem::ref_counted
template <typename T, typename Hash>
struct hash<sdd::mem::ref_counted<T,Hash>>
{
  std::size_t
  operator()(const sdd::mem::ref_counted<T, Hash>& x)
  const noexcept
  {
    return Hash()(x.data());
  }
};

/*------------------------------------------------------------------------------------------------*/

} // namespace std

#endif // _SDD_MEM_REF_COUNTED_HH_
<commit_msg>Documentation.<commit_after>#ifndef _SDD_MEM_REF_COUNTED_HH_
#define _SDD_MEM_REF_COUNTED_HH_

#include <cassert>
#include <cstdint>     // uint32_t
#include <functional>  // hash
#include <limits>      // numeric_limits
#include <type_traits> // is_nothrow_constructible
#include <utility>     // forward

#include <boost/intrusive/unordered_set.hpp>

#include "sdd/util/packed.hh"

namespace sdd { namespace mem {

/*------------------------------------------------------------------------------------------------*/

/// @internal
/// @brief A wrapper to associate a reference counter to a unified data.
///
/// This type is meant to be used by ptr, which takes care of incrementing and decrementing
/// the reference counter, as well as the deletion of the held data.
template <typename T, typename Hash = std::hash<T>>
class
#ifdef __clang__
LIBSDD_ATTRIBUTE_PACKED
#endif
ref_counted
{
  // Can't copy a ref_counted.
  ref_counted(const ref_counted&) = delete;
  ref_counted& operator=(const ref_counted&) = delete;

  // Can't move a ref_counted.
  ref_counted(ref_counted&&) = delete;
  ref_counted& operator=(ref_counted&&) = delete;

private:

  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  // The order is important here: data_ MUST be the last of all fields. This is necessary
  // because, for SDD, we allocate the alpha function directly behind the node, without any
  // indirection, to avoid a pointer. Thus, the address of the alpha function is computed
  // knowing this is right after the node.

  /// We choose a faster, unsafe mode.
  typedef boost::intrusive::link_mode<boost::intrusive::normal_link> link_mode;
  /// Used by Boost.Intrusive to manage the unicity table.
  boost::intrusive::unordered_set_member_hook<link_mode> member_hook_;

  /// @brief The number of time the encapsulated data is referenced
  ///
  /// Implements a reference-counting garbage collection.
  mutable std::uint32_t ref_count_;

  /// @brief The garbage collected data.
  ///
  /// The ptr class is responsible for the detection of dereferenced data and for
  /// instructing the unicity table to erase it.
  const T data_;

public:

  template <typename... Args>
  ref_counted(Args&&... args)
  noexcept(std::is_nothrow_constructible<T, Args...>::value)
		: member_hook_()
    , ref_count_(0)
    , data_(std::forward<Args>(args)...)
  {
  }

  /// @brief Get a reference of the unified data.
  const T&
  data()
  const noexcept
  {
    return data_;
  }

  /// @brief Get the number of extra bytes that may be used by the contained type.
  ///
  /// This information is needed when a data of variable length is allocated.
  std::size_t
  extra_bytes()
  const noexcept
  {
    // Static dispatch.
    return extra_bytes_impl(data_, 0);
  }

  /// @brief Called when the contained type defines extra_bytes.
  template <typename U>
  static auto
  extra_bytes_impl(const U& x, int)
  noexcept
  -> decltype(x.extra_bytes())
  {
    return x.extra_bytes();
  }

  /// @brief Called when the contained type doesn't define extra_bytes.
  template <typename U>
  static constexpr auto
  extra_bytes_impl(const U&, long)
  noexcept
  -> decltype(0)
  {
    return 0;
  }

private:

  /// A ptr should be able to access and modify the reference counter.
  template <typename U> friend class ptr;

  /// The unicity table needs to access member_hook_.
  template <typename U> friend class unique_table;

  /// @brief A ptr references that unified data.
  void
  increment_reference_counter()
  const noexcept
  {
    assert(ref_count_ < std::numeric_limits<uint32_t>::max());
    ++ref_count_;
  }

  /// @brief A ptr no longer references that unified data.
  void
  decrement_reference_counter()
  const noexcept
  {
    assert(ref_count_ > 0);
    --ref_count_;
  }

  /// @brief Tell if the unified data is no longer referenced.
  bool
  is_not_referenced()
  const noexcept
  {
    return ref_count_ == 0;
  }
};

/*------------------------------------------------------------------------------------------------*/

/// @internal
/// @related ref_counted
template <typename T, typename Hash>
inline
bool
operator==(const ref_counted<T, Hash>& lhs, const ref_counted<T, Hash>& rhs)
noexcept
{
  return lhs.data() == rhs.data();
}

/*------------------------------------------------------------------------------------------------*/

}} // namespace sdd::mem

namespace std {

/*------------------------------------------------------------------------------------------------*/

/// @internal
/// @brief Hash specialization for sdd::mem::ref_counted
template <typename T, typename Hash>
struct hash<sdd::mem::ref_counted<T,Hash>>
{
  std::size_t
  operator()(const sdd::mem::ref_counted<T, Hash>& x)
  const noexcept
  {
    return Hash()(x.data());
  }
};

/*------------------------------------------------------------------------------------------------*/

} // namespace std

#endif // _SDD_MEM_REF_COUNTED_HH_
<|endoftext|>


<commit_before>#include "include/Entity.h"

Entity::Entity(bool isSolid, int x, int y, double dir, std::string fileName)
{
    isSolid = isSolid;
    m_xPosition = x;
    m_yPosition = y;
    m_direction = dir;
    if (!m_tex.loadFromFile("media/" + fileName))
        std::cout << "Failed to load texture " + fileName;
    m_sprite.setTexture(m_tex);
    m_health = 100;
}

void Entity::stepForward()
{
    int a = 0;
    if (rand() % 2)a++;
    else a--;
    if (m_direction == 45)
        m_direction += a;
    if (m_direction == 135)
        m_direction += a;
    if (m_direction == 225)
        m_direction += a;
    if (m_direction == 315)
        m_direction += a; //Just some stupid tiebreaker code for 45 degree angle decisions.
    m_direction = (int) m_direction % 360;
    if (m_direction <= 45 || m_direction > 315)
        m_xPosition++;
    else if (m_direction <= 135)
        m_yPosition--;
    else if (m_direction <= 225)
        m_xPosition--;
    else
        m_yPosition++;
    adjustSprite();
}

void Entity::stepBackward()
{
    fixDirection();
    if (m_direction <= 45 || m_direction > 315)
        m_xPosition--;
    else if (m_direction <= 135)
        m_yPosition++;
    else if (m_direction <= 225)
        m_xPosition++;
    else if (m_direction <= 315)
        m_yPosition--;
    adjustSprite();
}

void Entity::fixDirection()
{
    if (m_direction < 0)
        m_direction *= -1.0; //Must be positive direction.
    m_direction = (double) ((int) m_direction % 360); //Must be between 0 and 360
    int a = 0;
    if (rand() % 2)
        a++;
    else
        a--; //Add or subract 1 if it's 45 degrees to a right angle.
    if (m_direction == 45)
        m_direction += a;
    if (m_direction == 135)
        m_direction += a;
    if (m_direction == 225)
        m_direction += a;
    if (m_direction == 315)
        m_direction += a; //Just some stupid tiebreaker code for 45 degree angle decisions.
}

void Entity::up()
{
    m_direction = 90.0;
    m_yPosition--;
    keepOnGrid();
    adjustSprite();
}

void Entity::down()
{
    m_direction = 270.0;
    m_yPosition++;
    keepOnGrid();
    adjustSprite();
}

void Entity::left()
{
    m_direction = 180.0;
    m_xPosition--;
    keepOnGrid();
    adjustSprite();
}

void Entity::right()
{
    m_direction = 0.0;
    m_xPosition++;
    keepOnGrid();
    adjustSprite();
}

void Entity::keepOnGrid()
{
    if (m_xPosition < 4)
        m_xPosition = 4;
    if (m_xPosition > 796)
        m_xPosition = 796;
    if (m_yPosition < 10)
        m_yPosition = 10;
    if (m_yPosition > 590)
        m_yPosition = 590;
}
<commit_msg>Delete Entity.cpp<commit_after><|endoftext|>


<commit_before>#include "ota.hpp"

// -----------------------------------------------------------------------------
// OTA
// -----------------------------------------------------------------------------

void otaSetup(uint16_t port, const char *password) {

    ArduinoOTA.setPort(port);
    ArduinoOTA.setHostname(WiFi.hostname().c_str());    // Hostname defaults to esp8266-[ChipID]

    if (password != "") {
      ArduinoOTA.setPassword(password);
    }

    ArduinoOTA.onStart([]() {
      Homie.getLogger() << "[OTA] Start" << endl ;
    });

    ArduinoOTA.onEnd([]() {
      Homie.getLogger() << "[OTA] End" << endl ;
    });

    ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
        Homie.getLogger() << "[OTA] Progress:" << (progress / (total / 100)) << "%" << endl;
        //DEBUG_MSG("[OTA] Progress: %u%%\r", (progress / (total / 100)));
    });

    ArduinoOTA.onError([](ota_error_t error) {
            Homie.getLogger() << "[OTA] Error " << error << " : " << endl;
            //DEBUG_MSG("\n[OTA] Error[%u]: ", error);
            if (error == OTA_AUTH_ERROR) Homie.getLogger() << "Auth Failed" << endl;
            else if (error == OTA_BEGIN_ERROR)Homie.getLogger() << "Begin Failed" << endl;
            else if (error == OTA_CONNECT_ERROR) Homie.getLogger() << "Connect Failed" << endl;
            else if (error == OTA_RECEIVE_ERROR) Homie.getLogger() << "Receive Failed" << endl;
            else if (error == OTA_END_ERROR) Homie.getLogger() << "End Failed" << endl;

    });

    ArduinoOTA.begin();
    Homie.getLogger() << "[OTA] setup finished\n\n" << endl;

}

void otaLoop() {
    ArduinoOTA.handle();
}
<commit_msg>Beautify OTA output on serial<commit_after>#include "ota.hpp"

// -----------------------------------------------------------------------------
// OTA
// -----------------------------------------------------------------------------

void otaSetup(uint16_t port, const char *password) {
  unsigned int lastprogress = -1;

  ArduinoOTA.setPort(port);
  ArduinoOTA.setHostname(WiFi.hostname().c_str());    // Hostname defaults to esp8266-[ChipID]

  if (password != "") {
    ArduinoOTA.setPassword(password);
  }

  ArduinoOTA.onStart([]() {
    Homie.getLogger() << "[OTA] Start" << endl ;
  });

  ArduinoOTA.onEnd([]() {
    Homie.getLogger() << endl << "[OTA] End" << endl ;
  });

  ArduinoOTA.onProgress([lastprogress](unsigned int progress, unsigned int total) mutable {
    unsigned int curprogress = (progress / (total / 100));
    if (lastprogress != curprogress) {
      lastprogress = curprogress;
      if ((curprogress > 0) && (curprogress % 10 == 0)) {
        Homie.getLogger() << curprogress << "%";
      }
      else {
        Homie.getLogger() << ".";
      }
    }
  });

  ArduinoOTA.onError([](ota_error_t error) {
    Homie.getLogger() << "[OTA] Error " << error << " : " << endl;
    //DEBUG_MSG("\n[OTA] Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) Homie.getLogger() << "Auth Failed" << endl;
    else if (error == OTA_BEGIN_ERROR)Homie.getLogger() << "Begin Failed" << endl;
    else if (error == OTA_CONNECT_ERROR) Homie.getLogger() << "Connect Failed" << endl;
    else if (error == OTA_RECEIVE_ERROR) Homie.getLogger() << "Receive Failed" << endl;
    else if (error == OTA_END_ERROR) Homie.getLogger() << "End Failed" << endl;
  });

  ArduinoOTA.begin();
  Homie.getLogger() << "[OTA] setup finished\n\n" << endl;
}

void otaLoop() {
    ArduinoOTA.handle();
}
<|endoftext|>


<commit_before>/* Copyright 2013-present Facebook, Inc.
 * Licensed under the Apache License, Version 2.0 */

#include "watchman.h"

// log-level "debug"
// log-level "error"
// log-level "off"
static void cmd_loglevel(struct watchman_client* client, const json_ref& args) {
  if (json_array_size(args) != 2) {
    send_error_response(client, "wrong number of arguments to 'log-level'");
    return;
  }

  watchman::LogLevel level;
  try {
    level = watchman::logLabelToLevel(json_to_w_string(args.at(1)));
  } catch (std::out_of_range& e) {
    send_error_response(client, "invalid log level for 'log-level'");
    return;
  }

  auto clientRef = client->shared_from_this();
  auto notify = [clientRef]() { clientRef->ping->notify(); };
  auto& log = watchman::getLog();

  switch (level) {
    case watchman::OFF:
      client->debugSub.reset();
      client->errorSub.reset();
      break;
    case watchman::DBG:
      client->debugSub = log.subscribe(watchman::DBG, notify);
      client->errorSub = log.subscribe(watchman::ERR, notify);
      break;
    case watchman::ERR:
    default:
      client->debugSub.reset();
      client->errorSub = log.subscribe(watchman::ERR, notify);
  }

  auto resp = make_response();
  resp.set("log_level", json_ref(args.at(1)));
  send_and_dispose_response(client, std::move(resp));
}
W_CMD_REG("log-level", cmd_loglevel, CMD_DAEMON, NULL)

// log "debug" "text to log"
static void cmd_log(struct watchman_client* client, const json_ref& args) {
  if (json_array_size(args) != 3) {
    send_error_response(client, "wrong number of arguments to 'log'");
    return;
  }

  watchman::LogLevel level;
  try {
    level = watchman::logLabelToLevel(json_to_w_string(args.at(1)));
  } catch (std::out_of_range& e) {
    send_error_response(client, "invalid log level for 'log'");
    return;
  }

  auto text = json_to_w_string(args.at(2));

  watchman::log(level, text, "\n");

  auto resp = make_response();
  resp.set("logged", json_true());
  send_and_dispose_response(client, std::move(resp));
}
W_CMD_REG("log", cmd_log, CMD_DAEMON, NULL)

/* vim:ts=2:sw=2:et:
 */
<commit_msg>watchman: allow logging from any user that has access rights<commit_after>/* Copyright 2013-present Facebook, Inc.
 * Licensed under the Apache License, Version 2.0 */

#include "watchman.h"

// log-level "debug"
// log-level "error"
// log-level "off"
static void cmd_loglevel(struct watchman_client* client, const json_ref& args) {
  if (json_array_size(args) != 2) {
    send_error_response(client, "wrong number of arguments to 'log-level'");
    return;
  }

  watchman::LogLevel level;
  try {
    level = watchman::logLabelToLevel(json_to_w_string(args.at(1)));
  } catch (std::out_of_range& e) {
    send_error_response(client, "invalid log level for 'log-level'");
    return;
  }

  auto clientRef = client->shared_from_this();
  auto notify = [clientRef]() { clientRef->ping->notify(); };
  auto& log = watchman::getLog();

  switch (level) {
    case watchman::OFF:
      client->debugSub.reset();
      client->errorSub.reset();
      break;
    case watchman::DBG:
      client->debugSub = log.subscribe(watchman::DBG, notify);
      client->errorSub = log.subscribe(watchman::ERR, notify);
      break;
    case watchman::ERR:
    default:
      client->debugSub.reset();
      client->errorSub = log.subscribe(watchman::ERR, notify);
  }

  auto resp = make_response();
  resp.set("log_level", json_ref(args.at(1)));
  send_and_dispose_response(client, std::move(resp));
}
W_CMD_REG("log-level", cmd_loglevel, CMD_DAEMON, NULL)

// log "debug" "text to log"
static void cmd_log(struct watchman_client* client, const json_ref& args) {
  if (json_array_size(args) != 3) {
    send_error_response(client, "wrong number of arguments to 'log'");
    return;
  }

  watchman::LogLevel level;
  try {
    level = watchman::logLabelToLevel(json_to_w_string(args.at(1)));
  } catch (std::out_of_range& e) {
    send_error_response(client, "invalid log level for 'log'");
    return;
  }

  auto text = json_to_w_string(args.at(2));

  watchman::log(level, text, "\n");

  auto resp = make_response();
  resp.set("logged", json_true());
  send_and_dispose_response(client, std::move(resp));
}
W_CMD_REG("log", cmd_log, CMD_DAEMON | CMD_ALLOW_ANY_USER, NULL)

/* vim:ts=2:sw=2:et:
 */
<|endoftext|>


<commit_before>/*
 * fMBT, free Model Based Testing tool
 * Copyright (c) 2011, Intel Corporation.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU Lesser General Public License,
 * version 2.1, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */

#include "log.hh"
#include "model.hh"
#include "null.hh"
#include "conf.hh"
#include "helper.hh"
#include <cstring>

namespace {

  std::vector<void*> mods;

  void mods_atexit() {
    for(unsigned i=0;i<mods.size();i++) {
      dlclose(mods[i]);
    }
  }

  Model* lib_creator(Log& l, std::string params) {
    Model* m;
    std::string model_name,model_param,model_filename;
    std::string s(unescape_string(strdup(params.c_str())));

    split(s, model_name, model_param);
    split(model_name,model_name,model_filename,",");

    m = ModelFactory::create(l, model_name, model_param);

    if (!m) {
      void* handle=load_lib(model_name,model_filename);

      if (handle) {
	m = ModelFactory::create(l, model_name, model_param);
	if (mods.empty()) {
	  atexit(mods_atexit);
	}
	mods.push_back(handle);
      } else {
	m = new Null(l);
	if (m) {
	  m->status   = false;
	  m->errormsg = std::string("lib:Can't load model ") + params;
	}
      }
    }
    return m;
  }
  static ModelFactory::Register me("lib", lib_creator);
}
<commit_msg>remember to save and test compile before git commit<commit_after>/*
 * fMBT, free Model Based Testing tool
 * Copyright (c) 2011, Intel Corporation.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU Lesser General Public License,
 * version 2.1, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
 * more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */

#include "log.hh"
#include "model.hh"
#include "null.hh"
#include "conf.hh"
#include "helper.hh"
#include <dlfcn.h>
#include <cstring>

namespace {

  std::vector<void*> mods;

  void mods_atexit() {
    for(unsigned i=0;i<mods.size();i++) {
      dlclose(mods[i]);
    }
  }

  Model* lib_creator(Log& l, std::string params) {
    Model* m;
    std::string model_name,model_param,model_filename;
    std::string s(unescape_string(strdup(params.c_str())));

    split(s, model_name, model_param);
    split(model_name,model_name,model_filename,",");

    m = ModelFactory::create(l, model_name, model_param);

    if (!m) {
      void* handle=load_lib(model_name,model_filename);

      if (handle) {
	m = ModelFactory::create(l, model_name, model_param);
	if (mods.empty()) {
	  atexit(mods_atexit);
	}
	mods.push_back(handle);
      } else {
	m = new Null(l);
	if (m) {
	  m->status   = false;
	  m->errormsg = std::string("lib:Can't load model ") + params;
	}
      }
    }
    return m;
  }
  static ModelFactory::Register me("lib", lib_creator);
}
<|endoftext|>


<commit_before>#include <chrono>
#include <iostream>
#include <thread>

#include "AHRS.h"
#include "WPILib.h"

/*
 * This program is used to measure the frequency of NavX errors.
 *
 * It prints a stream of millisecond timestamps corresponding to the last good
 * sensor read. Any errors noted by the NavX library are printed to standard
 * output and are interleaved with the timestamps.
 *
 * Excessive SPI errors have been noted while running this when
 * /etc/init.d/nilvrt is running so run `/etc/init.d/nilvrt stop` first.
 *
 * TIMESTAMP_PERIOD_MS = how often a timestamp is printed to standard output
 * LOOP_SLEEP_MS = run loop wait period
 */

static constexpr double TIMESTAMP_PERIOD_MS = 10 / 1000;
static constexpr auto LOOP_SLEEP_MS = std::chrono::milliseconds(1);

class Robot : public SampleRobot {
 public:
  void OperatorControl() {
    AHRS gyro{SPI::Port::kMXP};
    frc::Timer timer;
    timer.Start();
    while (IsEnabled()) {
      if (timer.HasPeriodPassed(TIMESTAMP_PERIOD_MS)) {
        std::cout << gyro.GetLastSensorTimestamp() << std::endl;
      }
      std::this_thread::sleep_for(LOOP_SLEEP_MS);
    }
  }

  void RobotInit() {}
  void Disabled() {}
};

START_ROBOT_CLASS(Robot)
<commit_msg>Busy loop in disabled.<commit_after>#include <chrono>
#include <iostream>
#include <thread>

#include "AHRS.h"
#include "WPILib.h"

/*
 * This program is used to measure the frequency of NavX errors.
 *
 * It prints a stream of millisecond timestamps corresponding to the last good
 * sensor read. Any errors noted by the NavX library are printed to standard
 * output and are interleaved with the timestamps.
 *
 * Excessive SPI errors have been noted while running this when
 * /etc/init.d/nilvrt is running so run `/etc/init.d/nilvrt stop` first.
 *
 * TIMESTAMP_PERIOD_MS = how often a timestamp is printed to standard output
 * LOOP_SLEEP_MS = run loop wait period
 */

static constexpr double TIMESTAMP_PERIOD_MS = 10 / 1000;
static constexpr auto LOOP_SLEEP_MS = std::chrono::milliseconds(1);

class Robot : public SampleRobot {
 public:
  void OperatorControl() {
    AHRS gyro{SPI::Port::kMXP};
    frc::Timer timer;
    timer.Start();
    while (IsEnabled()) {
      if (timer.HasPeriodPassed(TIMESTAMP_PERIOD_MS)) {
        std::cout << gyro.GetLastSensorTimestamp() << std::endl;
      }
      std::this_thread::sleep_for(LOOP_SLEEP_MS);
    }
  }

  void RobotInit() {}

  void Disabled() {
    while (IsDisabled()) {
      std::this_thread::sleep_for(LOOP_SLEEP_MS);
    }
  }
};

START_ROBOT_CLASS(Robot)
<|endoftext|>