<commit_before>/*
 * Copyright (c) 2012 Stanford University
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <string>

#include <ori/oriutil.h>

#include "fuse_cmd.h"

bool OF_HasFuse()
{
    return OF_ControlPath() != "";
}

std::string OF_ControlPath()
{
    char *cwdbuf = getcwd(NULL, 0);
    std::string path = cwdbuf;
    free(cwdbuf);

    while (path.size() > 0) {
        std::string control_path = path + "/" + ORI_CONTROL_FILENAME;
        if (Util_FileExists(control_path)) {
            return control_path;
        }
        path = StrUtil_Dirname(path);
    }

    return "";
}

bool OF_RunCommand(const char *cmd)
{
    size_t status;
    std::string controlPath = OF_ControlPath();

    if (controlPath.size() == 0)
        return false;

    int fd = open(controlPath.c_str(), O_RDWR | O_TRUNC);
    if (fd < 0) {
        perror("OF_RunCommand open");
        return false;
    }

    status = write(fd, cmd, strlen(cmd));
    if (status < 0) {
        perror("Failed to write control node");
        return false;
    }
    fsync(fd);
    lseek(fd, 0, SEEK_SET);

    // Read output
    struct stat sb;
    fstat(fd, &sb);
    size_t left = sb.st_size;
    while (left > 0) {
        size_t to_read = left;
        if (to_read > 1024)
            to_read = 1024;

        char buf[1024];
        int bytes_read = read(fd, buf, to_read);
        if (bytes_read == -1) {
            perror("Failed to read control node");
            return false;
        }
        fwrite(buf, bytes_read, 1, stdout);
        left -= bytes_read;
    }

    return true;
}

<commit_msg>Fix error handling in ori CLI FUSE control path.<commit_after>/*
 * Copyright (c) 2012 Stanford University
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <string>

#include <ori/oriutil.h>

#include "fuse_cmd.h"

bool OF_HasFuse()
{
    return OF_ControlPath() != "";
}

std::string OF_ControlPath()
{
    char *cwdbuf = getcwd(NULL, 0);
    std::string path = cwdbuf;
    free(cwdbuf);

    while (path.size() > 0) {
        std::string control_path = path + "/" + ORI_CONTROL_FILENAME;
        if (Util_FileExists(control_path)) {
            return control_path;
        }
        path = StrUtil_Dirname(path);
    }

    return "";
}

bool OF_RunCommand(const char *cmd)
{
    std::string controlPath = OF_ControlPath();

    if (controlPath.size() == 0)
        return false;

    int fd = open(controlPath.c_str(), O_RDWR | O_TRUNC);
    if (fd < 0) {
        perror("OF_RunCommand open");
        return false;
    }

    int status = write(fd, cmd, strlen(cmd));
    if (status < 0) {
        perror("Failed to write control node");
        return false;
    }
    fsync(fd);
    lseek(fd, 0, SEEK_SET);

    // Read output
    struct stat sb;
    fstat(fd, &sb);
    size_t left = sb.st_size;
    while (left > 0) {
        size_t to_read = left;
        if (to_read > 1024)
            to_read = 1024;

        char buf[1024];
        int bytes_read = read(fd, buf, to_read);
        if (bytes_read == -1) {
            perror("Failed to read control node");
            return false;
        }
        fwrite(buf, bytes_read, 1, stdout);
        left -= bytes_read;
    }

    return true;
}

<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS dr12 (1.25.12); FILE MERGED 2004/08/27 07:46:05 sab 1.25.12.5: RESYNC: (1.37-1.39); FILE MERGED 2004/07/26 22:44:54 sab 1.25.12.4: RESYNC: (1.30-1.37); FILE MERGED 2004/05/06 11:08:19 dr 1.25.12.3: RESYNC: (1.26-1.30); FILE MERGED 2004/02/25 10:35:23 dr 1.25.12.2: RESYNC: (1.25-1.26); FILE MERGED 2004/02/24 09:58:15 jmarmion 1.25.12.1: #i21255# text formatting for cell notes<commit_after><|endoftext|>


<commit_before>//===--- TypeCheckPattern.cpp - Type Checking for Patterns ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for patterns, analysing a
// pattern tree in both bottom-up and top-down ways.
//
//===----------------------------------------------------------------------===//

#include "TypeChecker.h"
#include "swift/AST/Attr.h"
#include "swift/AST/ExprHandle.h"
#include "swift/AST/ASTVisitor.h"
using namespace swift;

namespace {

class ResolvePattern : public ASTVisitor<ResolvePattern,
                                         /*ExprRetTy=*/Pattern*,
                                         /*StmtRetTy=*/void,
                                         /*DeclRetTy=*/void,
                                         /*PatternRetTy=*/Pattern*>
{
public:
  ASTContext &C;

  ResolvePattern(ASTContext &C) : C(C) {}

  // Handle productions that are always leaf patterns or are already resolved.
#define ALWAYS_RESOLVED_PATTERN(Id) \
  Pattern *visit##Id##Pattern(Id##Pattern *P) { return P; }
  ALWAYS_RESOLVED_PATTERN(Named)
  ALWAYS_RESOLVED_PATTERN(Any)
  ALWAYS_RESOLVED_PATTERN(Isa)
  ALWAYS_RESOLVED_PATTERN(Paren)
  ALWAYS_RESOLVED_PATTERN(Tuple)
  ALWAYS_RESOLVED_PATTERN(NominalType)
  ALWAYS_RESOLVED_PATTERN(Typed)
#undef ALWAYS_RESOLVED_PATTERN

  Pattern *visitVarPattern(VarPattern *P) {
    Pattern *newSub = visit(P->getSubPattern());
    P->setSubPattern(newSub);
    return P;
  }

  Pattern *visitExprPattern(ExprPattern *P) {
    if (P->isResolved())
      return P;

    // Try to convert to a pattern.
    Pattern *exprAsPattern = visit(P->getSubExpr());
    // If we failed, keep the ExprPattern as is.
    if (!exprAsPattern) {
      P->setResolved(true);
      return P;
    }
    return exprAsPattern;
  }

  // Most exprs remain exprs and should be wrapped in ExprPatterns.
  Pattern *visitExpr(Expr *E) {
    return nullptr;
  }

  // Unwrap UnresolvedPatternExprs.
  Pattern *visitUnresolvedPatternExpr(UnresolvedPatternExpr *E) {
    return visit(E->getSubPattern());
  }

  // Parens and tuples have to become patterns if they contain any patterns. If
  // they have only exprs as children, a tuple pattern or expr would be
  // equivalent, but it avoids some destructuring if we leave them as leaf
  // exprs.
  Pattern *visitParenExpr(ParenExpr *E) {
    if (Pattern *subPattern = visit(E->getSubExpr()))
      return new (C) ParenPattern(E->getLParenLoc(), subPattern,
                                  E->getRParenLoc());
    return nullptr;
  }

  Pattern *visitTupleExpr(TupleExpr *E) {
    SmallVector<Pattern*, 4> patterns;
    bool hasPattern = false;

    for (auto *subExpr : E->getElements()) {
      Pattern *pattern = visit(subExpr);
      hasPattern |= bool(pattern);
      patterns.push_back(pattern);
    }

    // If there were no subpatterns, leave the entire tuple as a leaf
    // expression.
    if (!hasPattern)
      return nullptr;

    // Otherwise, construct a TuplePattern.
    // FIXME: Carry over field labels.
    SmallVector<TuplePatternElt, 4> patternElts;

    for (unsigned i = 0, e = E->getNumElements(); i < e; ++i) {
      Pattern *pattern = patterns[i];
      if (!pattern)
        pattern = new (C) ExprPattern(E->getElement(i),
                                      /*isResolved*/ true,
                                      /*matchFn*/ false);
      patternElts.push_back(TuplePatternElt(pattern));
    }

    return TuplePattern::create(C, E->getLoc(),
                                patternElts, E->getRParenLoc());
  }

  // TODO: Call syntax 'T(x...)' forms a pattern if 'T' is a type and '(x...)' is a
  // TuplePattern with labeled fields.
  /*
  Pattern *visitCallExpr(CallExpr *E) {
    // The arguments must form a tuple with all named keys.
    auto *argTuple = dyn_cast<TupleExpr>(E->getArg());
    if (!argTuple)
      return nullptr;
    if (!argTuple->getElementNames())
      return nullptr;
    for (unsigned i = 0, e = argTuple->getNumElements(); i < e; ++i)
      if (!argTuple->getElementName(i).get())
        return nullptr;
    ...;
  }
   */
};

} // end anonymous namespace

/// Perform top-down syntactic disambiguation of a pattern. Where ambiguous
/// expr/pattern productions occur (tuples, function calls, etc.), favor the
/// pattern interpretation if it forms a valid pattern; otherwise, leave it as
/// an expression.
Pattern *TypeChecker::resolvePattern(Pattern *P) {
  return ResolvePattern(Context).visit(P);
}

/// Perform bottom-up type-checking on a pattern.  If this returns
/// false, the type of the pattern will have been set.  If allowUnknownTypes is
/// true, then this accepts "any" and "named" patterns, setting their type to
/// UnresolvedType.
bool TypeChecker::typeCheckPattern(Pattern *P, DeclContext *dc,
                                   bool isFirstPass,
                                   bool allowUnknownTypes) {
  switch (P->getKind()) {
  // Type-check paren patterns by checking the sub-pattern and
  // propagating that type out.
  case PatternKind::Paren: {
    Pattern *SP = cast<ParenPattern>(P)->getSubPattern();
    if (typeCheckPattern(SP, dc, isFirstPass, allowUnknownTypes)) {
      P->setType(ErrorType::get(Context));
      return true;
    }
    P->setType(SP->getType());
    return false;
  }

  // If we see an explicit type annotation, coerce the sub-pattern to
  // that type.
  case PatternKind::Typed: {
    bool hadError = false;
    TypedPattern *TP = cast<TypedPattern>(P);
    if (validateType(TP->getTypeLoc())) {
      TP->setType(ErrorType::get(Context));
      hadError = true;
    } else {
      TP->setType(TP->getTypeLoc().getType());
    }
    hadError |= coerceToType(TP->getSubPattern(), dc, P->getType());
    return hadError;
  }

  // A wildcard or name pattern cannot appear by itself in a context
  // which requires an explicit type.
  case PatternKind::Any:
  case PatternKind::Named:
    // If we're type checking this pattern in a context that can provide type
    // information, then the lack of type information is not an error.  Just set
    // our type to UnresolvedType.
    if (allowUnknownTypes) {
      P->setType(Context.TheUnstructuredUnresolvedType);
      return false;
    }

    diagnose(P->getLoc(), diag::cannot_infer_type_for_pattern);
    P->setType(ErrorType::get(Context));
    return true;

  // A tuple pattern propagates its tuple-ness out.
  case PatternKind::Tuple: {
    bool hadError = false;
    SmallVector<TupleTypeElt, 8> typeElts;

    for (TuplePatternElt &elt : cast<TuplePattern>(P)->getFields()) {
      Type type;
      ExprHandle *init = elt.getInit();
      Pattern *pattern = elt.getPattern();
      if (typeCheckPattern(pattern, dc, isFirstPass, allowUnknownTypes)) {
        hadError = true;
      } else {
        type = pattern->getType();
      }

      if (init && !isFirstPass && !init->alreadyChecked()) {
        Expr *e = init->getExpr();
        typeCheckExpression(e, dc, type);
        init->setExpr(e, true);
      }

      typeElts.push_back(TupleTypeElt(type, pattern->getBoundName(), init,
                                      elt.getVarargBaseType()));
    }

    if (hadError) {
      P->setType(ErrorType::get(Context));
      return true;
    }
    P->setType(TupleType::get(typeElts, Context));
    return false;
  }

#define PATTERN(Id, Parent)
#define REFUTABLE_PATTERN(Id, Parent) case PatternKind::Id:
#include "swift/AST/PatternNodes.def"
    llvm_unreachable("not implemented");
  }
  llvm_unreachable("bad pattern kind!");
}

/// Perform top-down type coercion on the given pattern.
bool TypeChecker::coerceToType(Pattern *P, DeclContext *dc, Type type) {
  switch (P->getKind()) {
  // For parens and vars, just set the type annotation and propagate inwards.
  case PatternKind::Paren:
    P->setType(type);
    return coerceToType(cast<ParenPattern>(P)->getSubPattern(), dc, type);
  case PatternKind::Var:
    P->setType(type);
    return coerceToType(cast<VarPattern>(P)->getSubPattern(), dc, type);

  // If we see an explicit type annotation, coerce the sub-pattern to
  // that type.
  case PatternKind::Typed: {
    TypedPattern *TP = cast<TypedPattern>(P);
    bool hadError = false;
    if (validateType(TP->getTypeLoc())) {
      TP->overwriteType(ErrorType::get(Context));
      hadError = true;
    } else {
      TP->setType(TP->getTypeLoc().getType());
      if (!type->isEqual(TP->getType()) && !type->is<ErrorType>()) {
        // Complain if the types don't match exactly.
        // TODO: allow implicit conversions?
        diagnose(P->getLoc(), diag::pattern_type_mismatch_context, type);
        hadError = true;
      }
    }

    hadError |= coerceToType(TP->getSubPattern(), dc, TP->getType());
    return hadError;
  }

  // For wildcard and name patterns, just set the type.
  case PatternKind::Named: {
    NamedPattern *NP = cast<NamedPattern>(P);
    NP->getDecl()->overwriteType(type);

    P->setType(type);
    return false;
  }
  case PatternKind::Any:
    P->setType(type);
    return false;

  // We can match a tuple pattern with a tuple type.
  // TODO: permit implicit conversions?
  case PatternKind::Tuple: {
    TuplePattern *TP = cast<TuplePattern>(P);
    bool hadError = false;

    if (type->is<ErrorType>())
      hadError = true;

    // The context type must be a tuple.
    TupleType *tupleTy = type->getAs<TupleType>();
    if (!tupleTy && !hadError) {
      diagnose(TP->getLParenLoc(), diag::tuple_pattern_in_non_tuple_context,
               type);
      hadError = true;
    }

    // The number of elements must match exactly.
    // TODO: incomplete tuple patterns, with some syntax.
    if (!hadError && tupleTy->getFields().size() != TP->getNumFields()) {
      diagnose(TP->getLParenLoc(), diag::tuple_pattern_length_mismatch, type);
      hadError = true;
    }

    // Coerce each tuple element to the respective type.
    // TODO: detect and diagnose shuffling
    // TODO: permit shuffling
    P->setType(type);

    for (unsigned i = 0, e = TP->getNumFields(); i != e; ++i) {
      TuplePatternElt &elt = TP->getFields()[i];
      Pattern *pattern = elt.getPattern();

      Type CoercionType;
      if (hadError)
        CoercionType = ErrorType::get(Context);
      else
        CoercionType = tupleTy->getFields()[i].getType();

      hadError |= coerceToType(pattern, dc, CoercionType);

      // Type-check the initialization expression.
      if (ExprHandle *initHandle = elt.getInit()) {
        Expr *init = initHandle->getExpr();
        if (initHandle->alreadyChecked()) {
          // Nothing to do
        } else if (typeCheckExpression(init, dc, CoercionType)) {
          initHandle->setExpr(nullptr, true);
        } else {
          initHandle->setExpr(init, true);
        }
      }
    }

    return hadError;
  }

  // Coerce expressions to the type.
  // TODO: Look up a match operator to resolve the type of the expression.
  case PatternKind::Expr: {
    ExprPattern *EP = dyn_cast<ExprPattern>(P);
    Expr *subExpr = EP->getSubExpr();
    if (typeCheckExpression(subExpr, dc, type))
      return true;
    EP->setSubExpr(subExpr);
    EP->setType(type);
    return false;
  }

  // Coerce an 'is' pattern by determining the cast kind.
  case PatternKind::Isa: {
    // TODO: Resolve the cast kind.
    P->setType(type);
    return false;
  }

  case PatternKind::NominalType:
    // TODO: Check the type against the coerced type, then coerce the
    // subpatterns to the field types.
    llvm_unreachable("not implemented");
  }
  llvm_unreachable("bad pattern kind!");
}
<commit_msg>Fix warning about bool-to-pointer conversion.<commit_after>//===--- TypeCheckPattern.cpp - Type Checking for Patterns ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for patterns, analysing a
// pattern tree in both bottom-up and top-down ways.
//
//===----------------------------------------------------------------------===//

#include "TypeChecker.h"
#include "swift/AST/Attr.h"
#include "swift/AST/ExprHandle.h"
#include "swift/AST/ASTVisitor.h"
using namespace swift;

namespace {

class ResolvePattern : public ASTVisitor<ResolvePattern,
                                         /*ExprRetTy=*/Pattern*,
                                         /*StmtRetTy=*/void,
                                         /*DeclRetTy=*/void,
                                         /*PatternRetTy=*/Pattern*>
{
public:
  ASTContext &C;

  ResolvePattern(ASTContext &C) : C(C) {}

  // Handle productions that are always leaf patterns or are already resolved.
#define ALWAYS_RESOLVED_PATTERN(Id) \
  Pattern *visit##Id##Pattern(Id##Pattern *P) { return P; }
  ALWAYS_RESOLVED_PATTERN(Named)
  ALWAYS_RESOLVED_PATTERN(Any)
  ALWAYS_RESOLVED_PATTERN(Isa)
  ALWAYS_RESOLVED_PATTERN(Paren)
  ALWAYS_RESOLVED_PATTERN(Tuple)
  ALWAYS_RESOLVED_PATTERN(NominalType)
  ALWAYS_RESOLVED_PATTERN(Typed)
#undef ALWAYS_RESOLVED_PATTERN

  Pattern *visitVarPattern(VarPattern *P) {
    Pattern *newSub = visit(P->getSubPattern());
    P->setSubPattern(newSub);
    return P;
  }

  Pattern *visitExprPattern(ExprPattern *P) {
    if (P->isResolved())
      return P;

    // Try to convert to a pattern.
    Pattern *exprAsPattern = visit(P->getSubExpr());
    // If we failed, keep the ExprPattern as is.
    if (!exprAsPattern) {
      P->setResolved(true);
      return P;
    }
    return exprAsPattern;
  }

  // Most exprs remain exprs and should be wrapped in ExprPatterns.
  Pattern *visitExpr(Expr *E) {
    return nullptr;
  }

  // Unwrap UnresolvedPatternExprs.
  Pattern *visitUnresolvedPatternExpr(UnresolvedPatternExpr *E) {
    return visit(E->getSubPattern());
  }

  // Parens and tuples have to become patterns if they contain any patterns. If
  // they have only exprs as children, a tuple pattern or expr would be
  // equivalent, but it avoids some destructuring if we leave them as leaf
  // exprs.
  Pattern *visitParenExpr(ParenExpr *E) {
    if (Pattern *subPattern = visit(E->getSubExpr()))
      return new (C) ParenPattern(E->getLParenLoc(), subPattern,
                                  E->getRParenLoc());
    return nullptr;
  }

  Pattern *visitTupleExpr(TupleExpr *E) {
    SmallVector<Pattern*, 4> patterns;
    bool hasPattern = false;

    for (auto *subExpr : E->getElements()) {
      Pattern *pattern = visit(subExpr);
      hasPattern |= bool(pattern);
      patterns.push_back(pattern);
    }

    // If there were no subpatterns, leave the entire tuple as a leaf
    // expression.
    if (!hasPattern)
      return nullptr;

    // Otherwise, construct a TuplePattern.
    // FIXME: Carry over field labels.
    SmallVector<TuplePatternElt, 4> patternElts;

    for (unsigned i = 0, e = E->getNumElements(); i < e; ++i) {
      Pattern *pattern = patterns[i];
      if (!pattern)
        pattern = new (C) ExprPattern(E->getElement(i),
                                      /*isResolved*/ true,
                                      /*matchFn*/ nullptr);
      patternElts.push_back(TuplePatternElt(pattern));
    }

    return TuplePattern::create(C, E->getLoc(),
                                patternElts, E->getRParenLoc());
  }

  // TODO: Call syntax 'T(x...)' forms a pattern if 'T' is a type and '(x...)' is a
  // TuplePattern with labeled fields.
  /*
  Pattern *visitCallExpr(CallExpr *E) {
    // The arguments must form a tuple with all named keys.
    auto *argTuple = dyn_cast<TupleExpr>(E->getArg());
    if (!argTuple)
      return nullptr;
    if (!argTuple->getElementNames())
      return nullptr;
    for (unsigned i = 0, e = argTuple->getNumElements(); i < e; ++i)
      if (!argTuple->getElementName(i).get())
        return nullptr;
    ...;
  }
   */
};

} // end anonymous namespace

/// Perform top-down syntactic disambiguation of a pattern. Where ambiguous
/// expr/pattern productions occur (tuples, function calls, etc.), favor the
/// pattern interpretation if it forms a valid pattern; otherwise, leave it as
/// an expression.
Pattern *TypeChecker::resolvePattern(Pattern *P) {
  return ResolvePattern(Context).visit(P);
}

/// Perform bottom-up type-checking on a pattern.  If this returns
/// false, the type of the pattern will have been set.  If allowUnknownTypes is
/// true, then this accepts "any" and "named" patterns, setting their type to
/// UnresolvedType.
bool TypeChecker::typeCheckPattern(Pattern *P, DeclContext *dc,
                                   bool isFirstPass,
                                   bool allowUnknownTypes) {
  switch (P->getKind()) {
  // Type-check paren patterns by checking the sub-pattern and
  // propagating that type out.
  case PatternKind::Paren: {
    Pattern *SP = cast<ParenPattern>(P)->getSubPattern();
    if (typeCheckPattern(SP, dc, isFirstPass, allowUnknownTypes)) {
      P->setType(ErrorType::get(Context));
      return true;
    }
    P->setType(SP->getType());
    return false;
  }

  // If we see an explicit type annotation, coerce the sub-pattern to
  // that type.
  case PatternKind::Typed: {
    bool hadError = false;
    TypedPattern *TP = cast<TypedPattern>(P);
    if (validateType(TP->getTypeLoc())) {
      TP->setType(ErrorType::get(Context));
      hadError = true;
    } else {
      TP->setType(TP->getTypeLoc().getType());
    }
    hadError |= coerceToType(TP->getSubPattern(), dc, P->getType());
    return hadError;
  }

  // A wildcard or name pattern cannot appear by itself in a context
  // which requires an explicit type.
  case PatternKind::Any:
  case PatternKind::Named:
    // If we're type checking this pattern in a context that can provide type
    // information, then the lack of type information is not an error.  Just set
    // our type to UnresolvedType.
    if (allowUnknownTypes) {
      P->setType(Context.TheUnstructuredUnresolvedType);
      return false;
    }

    diagnose(P->getLoc(), diag::cannot_infer_type_for_pattern);
    P->setType(ErrorType::get(Context));
    return true;

  // A tuple pattern propagates its tuple-ness out.
  case PatternKind::Tuple: {
    bool hadError = false;
    SmallVector<TupleTypeElt, 8> typeElts;

    for (TuplePatternElt &elt : cast<TuplePattern>(P)->getFields()) {
      Type type;
      ExprHandle *init = elt.getInit();
      Pattern *pattern = elt.getPattern();
      if (typeCheckPattern(pattern, dc, isFirstPass, allowUnknownTypes)) {
        hadError = true;
      } else {
        type = pattern->getType();
      }

      if (init && !isFirstPass && !init->alreadyChecked()) {
        Expr *e = init->getExpr();
        typeCheckExpression(e, dc, type);
        init->setExpr(e, true);
      }

      typeElts.push_back(TupleTypeElt(type, pattern->getBoundName(), init,
                                      elt.getVarargBaseType()));
    }

    if (hadError) {
      P->setType(ErrorType::get(Context));
      return true;
    }
    P->setType(TupleType::get(typeElts, Context));
    return false;
  }

#define PATTERN(Id, Parent)
#define REFUTABLE_PATTERN(Id, Parent) case PatternKind::Id:
#include "swift/AST/PatternNodes.def"
    llvm_unreachable("not implemented");
  }
  llvm_unreachable("bad pattern kind!");
}

/// Perform top-down type coercion on the given pattern.
bool TypeChecker::coerceToType(Pattern *P, DeclContext *dc, Type type) {
  switch (P->getKind()) {
  // For parens and vars, just set the type annotation and propagate inwards.
  case PatternKind::Paren:
    P->setType(type);
    return coerceToType(cast<ParenPattern>(P)->getSubPattern(), dc, type);
  case PatternKind::Var:
    P->setType(type);
    return coerceToType(cast<VarPattern>(P)->getSubPattern(), dc, type);

  // If we see an explicit type annotation, coerce the sub-pattern to
  // that type.
  case PatternKind::Typed: {
    TypedPattern *TP = cast<TypedPattern>(P);
    bool hadError = false;
    if (validateType(TP->getTypeLoc())) {
      TP->overwriteType(ErrorType::get(Context));
      hadError = true;
    } else {
      TP->setType(TP->getTypeLoc().getType());
      if (!type->isEqual(TP->getType()) && !type->is<ErrorType>()) {
        // Complain if the types don't match exactly.
        // TODO: allow implicit conversions?
        diagnose(P->getLoc(), diag::pattern_type_mismatch_context, type);
        hadError = true;
      }
    }

    hadError |= coerceToType(TP->getSubPattern(), dc, TP->getType());
    return hadError;
  }

  // For wildcard and name patterns, just set the type.
  case PatternKind::Named: {
    NamedPattern *NP = cast<NamedPattern>(P);
    NP->getDecl()->overwriteType(type);

    P->setType(type);
    return false;
  }
  case PatternKind::Any:
    P->setType(type);
    return false;

  // We can match a tuple pattern with a tuple type.
  // TODO: permit implicit conversions?
  case PatternKind::Tuple: {
    TuplePattern *TP = cast<TuplePattern>(P);
    bool hadError = false;

    if (type->is<ErrorType>())
      hadError = true;

    // The context type must be a tuple.
    TupleType *tupleTy = type->getAs<TupleType>();
    if (!tupleTy && !hadError) {
      diagnose(TP->getLParenLoc(), diag::tuple_pattern_in_non_tuple_context,
               type);
      hadError = true;
    }

    // The number of elements must match exactly.
    // TODO: incomplete tuple patterns, with some syntax.
    if (!hadError && tupleTy->getFields().size() != TP->getNumFields()) {
      diagnose(TP->getLParenLoc(), diag::tuple_pattern_length_mismatch, type);
      hadError = true;
    }

    // Coerce each tuple element to the respective type.
    // TODO: detect and diagnose shuffling
    // TODO: permit shuffling
    P->setType(type);

    for (unsigned i = 0, e = TP->getNumFields(); i != e; ++i) {
      TuplePatternElt &elt = TP->getFields()[i];
      Pattern *pattern = elt.getPattern();

      Type CoercionType;
      if (hadError)
        CoercionType = ErrorType::get(Context);
      else
        CoercionType = tupleTy->getFields()[i].getType();

      hadError |= coerceToType(pattern, dc, CoercionType);

      // Type-check the initialization expression.
      if (ExprHandle *initHandle = elt.getInit()) {
        Expr *init = initHandle->getExpr();
        if (initHandle->alreadyChecked()) {
          // Nothing to do
        } else if (typeCheckExpression(init, dc, CoercionType)) {
          initHandle->setExpr(nullptr, true);
        } else {
          initHandle->setExpr(init, true);
        }
      }
    }

    return hadError;
  }

  // Coerce expressions to the type.
  // TODO: Look up a match operator to resolve the type of the expression.
  case PatternKind::Expr: {
    ExprPattern *EP = dyn_cast<ExprPattern>(P);
    Expr *subExpr = EP->getSubExpr();
    if (typeCheckExpression(subExpr, dc, type))
      return true;
    EP->setSubExpr(subExpr);
    EP->setType(type);
    return false;
  }

  // Coerce an 'is' pattern by determining the cast kind.
  case PatternKind::Isa: {
    // TODO: Resolve the cast kind.
    P->setType(type);
    return false;
  }

  case PatternKind::NominalType:
    // TODO: Check the type against the coerced type, then coerce the
    // subpatterns to the field types.
    llvm_unreachable("not implemented");
  }
  llvm_unreachable("bad pattern kind!");
}
<|endoftext|>


<commit_before>//===-- ConstantRange.cpp - ConstantRange implementation ------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Represent a range of possible values that may occur when the program is run
// for an integral value.  This keeps track of a lower and upper bound for the
// constant, which MAY wrap around the end of the numeric range.  To do this, it
// keeps track of a [lower, upper) bound, which specifies an interval just like
// STL iterators.  When used with boolean values, the following are important
// ranges (other integral ranges use min/max values for special range values):
//
//  [F, F) = {}     = Empty set
//  [T, F) = {T}
//  [F, T) = {F}
//  [T, T) = {F, T} = Full set
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/ConstantRange.h"
#include "llvm/Support/Streams.h"
#include <ostream>
using namespace llvm;

/// Initialize a full (the default) or empty set for the specified type.
///
ConstantRange::ConstantRange(uint32_t BitWidth, bool Full) :
  Lower(BitWidth, 0), Upper(BitWidth, 0) {
  if (Full)
    Lower = Upper = APInt::getMaxValue(BitWidth);
  else
    Lower = Upper = APInt::getMinValue(BitWidth);
}

/// Initialize a range to hold the single specified value.
///
ConstantRange::ConstantRange(const APInt & V) : Lower(V), Upper(V + 1) { }

ConstantRange::ConstantRange(const APInt &L, const APInt &U) :
  Lower(L), Upper(U) {
  assert(L.getBitWidth() == U.getBitWidth() &&
         "ConstantRange with unequal bit widths");
  uint32_t BitWidth = L.getBitWidth();
  assert((L != U || (L == APInt::getMaxValue(BitWidth) ||
                     L == APInt::getMinValue(BitWidth))) &&
         "Lower == Upper, but they aren't min or max value!");
}

/// isFullSet - Return true if this set contains all of the elements possible
/// for this data-type
bool ConstantRange::isFullSet() const {
  return Lower == Upper && Lower == APInt::getMaxValue(getBitWidth());
}

/// isEmptySet - Return true if this set contains no members.
///
bool ConstantRange::isEmptySet() const {
  return Lower == Upper && Lower == APInt::getMinValue(getBitWidth());
}

/// isWrappedSet - Return true if this set wraps around the top of the range,
/// for example: [100, 8)
///
bool ConstantRange::isWrappedSet() const {
  return Lower.ugt(Upper);
}

/// getSetSize - Return the number of elements in this set.
///
APInt ConstantRange::getSetSize() const {
  if (isEmptySet())
    return APInt(getBitWidth(), 0);
  if (getBitWidth() == 1) {
    if (Lower != Upper)  // One of T or F in the set...
      return APInt(2, 1);
    return APInt(2, 2);      // Must be full set...
  }

  // Simply subtract the bounds...
  return Upper - Lower;
}

/// contains - Return true if the specified value is in the set.
///
bool ConstantRange::contains(const APInt &V) const {
  if (Lower == Upper)
    return isFullSet();

  if (!isWrappedSet())
    return Lower.ule(V) && V.ult(Upper);
  else
    return Lower.ule(V) || V.ult(Upper);
}

/// subtract - Subtract the specified constant from the endpoints of this
/// constant range.
ConstantRange ConstantRange::subtract(const APInt &Val) const {
  assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
  // If the set is empty or full, don't modify the endpoints.
  if (Lower == Upper)
    return *this;
  return ConstantRange(Lower - Val, Upper - Val);
}

// intersect1Wrapped - This helper function is used to intersect two ranges when
// it is known that LHS is wrapped and RHS isn't.
//
ConstantRange
ConstantRange::intersect1Wrapped(const ConstantRange &LHS,
                                 const ConstantRange &RHS) {
  assert(LHS.isWrappedSet() && !RHS.isWrappedSet());

  // Check to see if we overlap on the Left side of RHS...
  //
  if (RHS.Lower.ult(LHS.Upper)) {
    // We do overlap on the left side of RHS, see if we overlap on the right of
    // RHS...
    if (RHS.Upper.ugt(LHS.Lower)) {
      // Ok, the result overlaps on both the left and right sides.  See if the
      // resultant interval will be smaller if we wrap or not...
      //
      if (LHS.getSetSize().ult(RHS.getSetSize()))
        return LHS;
      else
        return RHS;

    } else {
      // No overlap on the right, just on the left.
      return ConstantRange(RHS.Lower, LHS.Upper);
    }
  } else {
    // We don't overlap on the left side of RHS, see if we overlap on the right
    // of RHS...
    if (RHS.Upper.ugt(LHS.Lower)) {
      // Simple overlap...
      return ConstantRange(LHS.Lower, RHS.Upper);
    } else {
      // No overlap...
      return ConstantRange(LHS.getBitWidth(), false);
    }
  }
}

/// intersectWith - Return the range that results from the intersection of this
/// range with another range.
///
ConstantRange ConstantRange::intersectWith(const ConstantRange &CR) const {
  assert(getBitWidth() == CR.getBitWidth() &&
         "ConstantRange types don't agree!");
  // Handle common special cases
  if (isEmptySet() || CR.isFullSet())
    return *this;
  if (isFullSet()  || CR.isEmptySet())
    return CR;

  if (!isWrappedSet()) {
    if (!CR.isWrappedSet()) {
      using namespace APIntOps;
      APInt L = umax(Lower, CR.Lower);
      APInt U = umin(Upper, CR.Upper);

      if (L.ult(U)) // If range isn't empty...
        return ConstantRange(L, U);
      else
        return ConstantRange(getBitWidth(), false);// Otherwise, empty set
    } else
      return intersect1Wrapped(CR, *this);
  } else {   // We know "this" is wrapped...
    if (!CR.isWrappedSet())
      return intersect1Wrapped(*this, CR);
    else {
      // Both ranges are wrapped...
      using namespace APIntOps;
      APInt L = umax(Lower, CR.Lower);
      APInt U = umin(Upper, CR.Upper);
      return ConstantRange(L, U);
    }
  }
  return *this;
}

/// unionWith - Return the range that results from the union of this range with
/// another range.  The resultant range is guaranteed to include the elements of
/// both sets, but may contain more.  For example, [3, 9) union [12,15) is [3,
/// 15), which includes 9, 10, and 11, which were not included in either set
/// before.
///
ConstantRange ConstantRange::unionWith(const ConstantRange &CR) const {
  assert(getBitWidth() == CR.getBitWidth() &&
         "ConstantRange types don't agree!");

  assert(0 && "Range union not implemented yet!");

  return *this;
}

/// zeroExtend - Return a new range in the specified integer type, which must
/// be strictly larger than the current type.  The returned range will
/// correspond to the possible range of values as if the source range had been
/// zero extended.
ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
  unsigned SrcTySize = getBitWidth();
  assert(SrcTySize < DstTySize && "Not a value extension");
  if (isFullSet())
    // Change a source full set into [0, 1 << 8*numbytes)
    return ConstantRange(APInt(DstTySize,0), APInt(DstTySize,1).shl(SrcTySize));

  APInt L = Lower; L.zext(DstTySize);
  APInt U = Upper; U.zext(DstTySize);
  return ConstantRange(L, U);
}

/// truncate - Return a new range in the specified integer type, which must be
/// strictly smaller than the current type.  The returned range will
/// correspond to the possible range of values as if the source range had been
/// truncated to the specified type.
ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
  unsigned SrcTySize = getBitWidth();
  assert(SrcTySize > DstTySize && "Not a value truncation");
  APInt Size = APInt::getMaxValue(DstTySize).zext(SrcTySize);
  if (isFullSet() || getSetSize().ugt(Size))
    return ConstantRange(DstTySize);

  APInt L = Lower; L.trunc(DstTySize);
  APInt U = Upper; U.trunc(DstTySize);
  return ConstantRange(L, U);
}

/// print - Print out the bounds to a stream...
///
void ConstantRange::print(std::ostream &OS) const {
  OS << "[" << Lower.toStringSigned(10) << ","
            << Upper.toStringSigned(10) << " )";
}

/// dump - Allow printing from a debugger easily...
///
void ConstantRange::dump() const {
  print(cerr);
}
<commit_msg>Implement unionWith.<commit_after>//===-- ConstantRange.cpp - ConstantRange implementation ------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Represent a range of possible values that may occur when the program is run
// for an integral value.  This keeps track of a lower and upper bound for the
// constant, which MAY wrap around the end of the numeric range.  To do this, it
// keeps track of a [lower, upper) bound, which specifies an interval just like
// STL iterators.  When used with boolean values, the following are important
// ranges (other integral ranges use min/max values for special range values):
//
//  [F, F) = {}     = Empty set
//  [T, F) = {T}
//  [F, T) = {F}
//  [T, T) = {F, T} = Full set
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/ConstantRange.h"
#include "llvm/Support/Streams.h"
#include <ostream>
using namespace llvm;

/// Initialize a full (the default) or empty set for the specified type.
///
ConstantRange::ConstantRange(uint32_t BitWidth, bool Full) :
  Lower(BitWidth, 0), Upper(BitWidth, 0) {
  if (Full)
    Lower = Upper = APInt::getMaxValue(BitWidth);
  else
    Lower = Upper = APInt::getMinValue(BitWidth);
}

/// Initialize a range to hold the single specified value.
///
ConstantRange::ConstantRange(const APInt & V) : Lower(V), Upper(V + 1) { }

ConstantRange::ConstantRange(const APInt &L, const APInt &U) :
  Lower(L), Upper(U) {
  assert(L.getBitWidth() == U.getBitWidth() &&
         "ConstantRange with unequal bit widths");
  uint32_t BitWidth = L.getBitWidth();
  assert((L != U || (L == APInt::getMaxValue(BitWidth) ||
                     L == APInt::getMinValue(BitWidth))) &&
         "Lower == Upper, but they aren't min or max value!");
}

/// isFullSet - Return true if this set contains all of the elements possible
/// for this data-type
bool ConstantRange::isFullSet() const {
  return Lower == Upper && Lower == APInt::getMaxValue(getBitWidth());
}

/// isEmptySet - Return true if this set contains no members.
///
bool ConstantRange::isEmptySet() const {
  return Lower == Upper && Lower == APInt::getMinValue(getBitWidth());
}

/// isWrappedSet - Return true if this set wraps around the top of the range,
/// for example: [100, 8)
///
bool ConstantRange::isWrappedSet() const {
  return Lower.ugt(Upper);
}

/// getSetSize - Return the number of elements in this set.
///
APInt ConstantRange::getSetSize() const {
  if (isEmptySet())
    return APInt(getBitWidth(), 0);
  if (getBitWidth() == 1) {
    if (Lower != Upper)  // One of T or F in the set...
      return APInt(2, 1);
    return APInt(2, 2);      // Must be full set...
  }

  // Simply subtract the bounds...
  return Upper - Lower;
}

/// contains - Return true if the specified value is in the set.
///
bool ConstantRange::contains(const APInt &V) const {
  if (Lower == Upper)
    return isFullSet();

  if (!isWrappedSet())
    return Lower.ule(V) && V.ult(Upper);
  else
    return Lower.ule(V) || V.ult(Upper);
}

/// subtract - Subtract the specified constant from the endpoints of this
/// constant range.
ConstantRange ConstantRange::subtract(const APInt &Val) const {
  assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
  // If the set is empty or full, don't modify the endpoints.
  if (Lower == Upper)
    return *this;
  return ConstantRange(Lower - Val, Upper - Val);
}

// intersect1Wrapped - This helper function is used to intersect two ranges when
// it is known that LHS is wrapped and RHS isn't.
//
ConstantRange
ConstantRange::intersect1Wrapped(const ConstantRange &LHS,
                                 const ConstantRange &RHS) {
  assert(LHS.isWrappedSet() && !RHS.isWrappedSet());

  // Check to see if we overlap on the Left side of RHS...
  //
  if (RHS.Lower.ult(LHS.Upper)) {
    // We do overlap on the left side of RHS, see if we overlap on the right of
    // RHS...
    if (RHS.Upper.ugt(LHS.Lower)) {
      // Ok, the result overlaps on both the left and right sides.  See if the
      // resultant interval will be smaller if we wrap or not...
      //
      if (LHS.getSetSize().ult(RHS.getSetSize()))
        return LHS;
      else
        return RHS;

    } else {
      // No overlap on the right, just on the left.
      return ConstantRange(RHS.Lower, LHS.Upper);
    }
  } else {
    // We don't overlap on the left side of RHS, see if we overlap on the right
    // of RHS...
    if (RHS.Upper.ugt(LHS.Lower)) {
      // Simple overlap...
      return ConstantRange(LHS.Lower, RHS.Upper);
    } else {
      // No overlap...
      return ConstantRange(LHS.getBitWidth(), false);
    }
  }
}

/// intersectWith - Return the range that results from the intersection of this
/// range with another range.
///
ConstantRange ConstantRange::intersectWith(const ConstantRange &CR) const {
  assert(getBitWidth() == CR.getBitWidth() &&
         "ConstantRange types don't agree!");
  // Handle common special cases
  if (isEmptySet() || CR.isFullSet())
    return *this;
  if (isFullSet()  || CR.isEmptySet())
    return CR;

  if (!isWrappedSet()) {
    if (!CR.isWrappedSet()) {
      using namespace APIntOps;
      APInt L = umax(Lower, CR.Lower);
      APInt U = umin(Upper, CR.Upper);

      if (L.ult(U)) // If range isn't empty...
        return ConstantRange(L, U);
      else
        return ConstantRange(getBitWidth(), false);// Otherwise, empty set
    } else
      return intersect1Wrapped(CR, *this);
  } else {   // We know "this" is wrapped...
    if (!CR.isWrappedSet())
      return intersect1Wrapped(*this, CR);
    else {
      // Both ranges are wrapped...
      using namespace APIntOps;
      APInt L = umax(Lower, CR.Lower);
      APInt U = umin(Upper, CR.Upper);
      return ConstantRange(L, U);
    }
  }
  return *this;
}

/// unionWith - Return the range that results from the union of this range with
/// another range.  The resultant range is guaranteed to include the elements of
/// both sets, but may contain more.  For example, [3, 9) union [12,15) is [3,
/// 15), which includes 9, 10, and 11, which were not included in either set
/// before.
///
ConstantRange ConstantRange::unionWith(const ConstantRange &CR) const {
  assert(getBitWidth() == CR.getBitWidth() &&
         "ConstantRange types don't agree!");

  if (   isFullSet() || CR.isEmptySet()) return *this;
  if (CR.isFullSet() ||    isEmptySet()) return CR;

  APInt L = Lower, U = Upper;

  if (!contains(CR.Lower))
    L = APIntOps::umin(L, CR.Lower);

  if (!contains(CR.Upper - 1))
    U = APIntOps::umax(U, CR.Upper);

  return ConstantRange(L, U);
}

/// zeroExtend - Return a new range in the specified integer type, which must
/// be strictly larger than the current type.  The returned range will
/// correspond to the possible range of values as if the source range had been
/// zero extended.
ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
  unsigned SrcTySize = getBitWidth();
  assert(SrcTySize < DstTySize && "Not a value extension");
  if (isFullSet())
    // Change a source full set into [0, 1 << 8*numbytes)
    return ConstantRange(APInt(DstTySize,0), APInt(DstTySize,1).shl(SrcTySize));

  APInt L = Lower; L.zext(DstTySize);
  APInt U = Upper; U.zext(DstTySize);
  return ConstantRange(L, U);
}

/// truncate - Return a new range in the specified integer type, which must be
/// strictly smaller than the current type.  The returned range will
/// correspond to the possible range of values as if the source range had been
/// truncated to the specified type.
ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
  unsigned SrcTySize = getBitWidth();
  assert(SrcTySize > DstTySize && "Not a value truncation");
  APInt Size = APInt::getMaxValue(DstTySize).zext(SrcTySize);
  if (isFullSet() || getSetSize().ugt(Size))
    return ConstantRange(DstTySize);

  APInt L = Lower; L.trunc(DstTySize);
  APInt U = Upper; U.trunc(DstTySize);
  return ConstantRange(L, U);
}

/// print - Print out the bounds to a stream...
///
void ConstantRange::print(std::ostream &OS) const {
  OS << "[" << Lower.toStringSigned(10) << ","
            << Upper.toStringSigned(10) << " )";
}

/// dump - Allow printing from a debugger easily...
///
void ConstantRange::dump() const {
  print(cerr);
}
<|endoftext|>


<commit_before>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>

#include "Sensor.h"
#include "I22cCom.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
///#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"

#include <vector>
#include <iostream>
#include <wiringPi.h>  //compile with -lwiringPi

using namespace std;

vector<Sensor*> motionSensors;    //Vector of the sensors
vector<Light*> lights;      //Vector of the lights
vector<int> active;
PressureSensor& pressureSensor;
Camera* cam;                //Pointer to the camera
Log* log;

int pressureValue;
bool sleep = false;
bool day = true;
bool anomaly = false;
int temperature = 20;

int sumActive(int active[]) {
	int sum=0;
	for(int i=0;i<sizeof(active[])/sizeof(active[0]);i++)
		sum+=active[i];
	return sum;
}

void checkAnomaly();
void updateSensors();
void checkCam();
void sendAlert();
void init();

int main() {

    init();

    while(1) {
        /*
        for(int i=0;i<sensors.capacity();i++) // For every sensor
            if(sensors[i]->Check()) { // Call their check function
				active[i]=1; // And if the check is positive (returns true).
				//TODO ENABLE LIGHTS
			} else active[i]=0;
		if(sumActive(active)==0) {
            sendAlert();
		}
		for(i=0;i<lights.capacity();i++) // For every light
			lights[i]->Check(); // Check if timer expired yet
        */
        updateSensors();
        checkAnomaly();
        checkCam();
	}
}

/*Init for the main*/
void init() {
    wiringPiSetupGpio();
    I2CCom i2c(I2CLOC);     //the i2c to communicate with sensors

    Light x(22);
    MotionSensor s1(0x05,i2c);
    PressureSensor s2(0x06, i2c);
    Log l1(LOG);
    Camera c1();

    cam = &c1
    log = &l1;
    pressureSensor = &s2;
    motionSensors.push_back(&s1);
    lights.push_back(&x);

    active.resize(motionSensors.size);
}
/*Updates sensors*/
void updateSensors() {
    //update van elke sensor de value en de active
    bool alert = true;
    for(int i = 0; i<motionSensors.size();i++) {
        if(motionSensors[i]->check()) {
            active[i]=1;
            alert = false;
        } else {
            active[i]=0;
        }
    }
    if(alert && sleep = false) {
        sendAlert();
    }
}

/*Send Alarm*/
void sendAlert(){
    cout<<"Alert"<<endl;
}

/*Sets the camera*/
void checkCam(){
    if(day) {
        cam.setCamera(true);
    } else if(anomaly) {
        cam.setCamera(true);
    } else {
        cam.setCamera(false);
    }
}

void checkAnomaly(){

    if(pressureValue > 20 && pressureValue < 150) {
        anomaly = true;
    }
    if(pressureValue > 150 && pressureValue < 200) { // Changing positions while asleep
        //Do nothing, maybe verify if person really is sleeping
    }
    if(pressureValue > 200) {
        sleep = true;
    }

}

<commit_msg>bug fix<commit_after>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>

#include "Sensor.h"
#include "I22cCom.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
///#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"

#include <vector>
#include <iostream>
#include <wiringPi.h>  //compile with -lwiringPi

using namespace std;

vector<Sensor*> motionSensors;    //Vector of the sensors
vector<Light*> lights;      //Vector of the lights
vector<int> active;
PressureSensor& pressureSensor;
Camera* cam;                //Pointer to the camera
Log* log;

int pressureValue;
bool sleep = false;
bool day = true;
bool anomaly = false;
int temperature = 20;

int sumActive(int active[]) {
	int sum=0;
	for(int i=0;i<sizeof(active[])/sizeof(active[0]);i++)
		sum+=active[i];
	return sum;
}

void checkAnomaly();
void updateSensors();
void checkCam();
void sendAlert();
void init();

int main() {

    init();

    while(1) {
        /*
        for(int i=0;i<sensors.capacity();i++) // For every sensor
            if(sensors[i]->Check()) { // Call their check function
				active[i]=1; // And if the check is positive (returns true).
				//TODO ENABLE LIGHTS
			} else active[i]=0;
		if(sumActive(active)==0) {
            sendAlert();
		}
		for(i=0;i<lights.capacity();i++) // For every light
			lights[i]->Check(); // Check if timer expired yet
        */
        updateSensors();
        checkAnomaly();
        checkCam();
	}
}

/*Init for the main*/
void init() {
    wiringPiSetupGpio();
    I2CCom i2c(I2CLOC);     //the i2c to communicate with sensors

    Light x(22);
    MotionSensor s1(0x05,i2c);
    PressureSensor s2(0x06, i2c);
    Log l1(LOG);
    Camera c1();

    cam = &c1
    log = &l1;
    pressureSensor = &s2;
    motionSensors.push_back(&s1);
    lights.push_back(&x);

    active.resize(motionSensors.size);
}
/*Updates sensors*/
void updateSensors() {
    //update van elke sensor de value en de active
    bool alert = true;
    for(int i = 0; i<motionSensors.size();i++) {
        if(motionSensors[i]->check()) {
            active[i]=1;
            alert = false;
        } else {
            active[i]=0;
        }
    }
    if(alert && sleep = false) {
        sendAlert();
    }
}

/*Send Alarm*/
void sendAlert(){
    cout<<"Alert"<<endl;
}

/*Sets the camera*/
void checkCam(){
    if(day) {
        cam->setCamera(true);
    } else if(anomaly) {
        cam->setCamera(true);
    } else {
        cam->setCamera(false);
    }
}

void checkAnomaly(){

    if(pressureValue > 20 && pressureValue < 150) {
        anomaly = true;
    }
    if(pressureValue > 150 && pressureValue < 200) { // Changing positions while asleep
        //Do nothing, maybe verify if person really is sleeping
    }
    if(pressureValue > 200) {
        sleep = true;
    }

}

<|endoftext|>


<commit_before>//===-- X86JITInfo.cpp - Implement the JIT interfaces for the X86 target --===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the JIT interfaces for the X86 target.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "jit"
#include <cstdlib>
#include "X86JITInfo.h"
#include "X86Relocations.h"
#include "llvm/CodeGen/MachineCodeEmitter.h"
#include "llvm/Config/alloca.h"
using namespace llvm;

void X86JITInfo::replaceMachineCodeForFunction(void *Old, void *New) {
  unsigned char *OldByte = (unsigned char *)Old;
  *OldByte++ = 0xE9;                // Emit JMP opcode.
  unsigned *OldWord = (unsigned *)OldByte;
  unsigned NewAddr = (intptr_t)New;
  unsigned OldAddr = (intptr_t)OldWord;
  *OldWord = NewAddr - OldAddr - 4; // Emit PC-relative addr of New code.
}

/// JITCompilerFunction - This contains the address of the JIT function used to
/// compile a function lazily.
static TargetJITInfo::JITCompilerFn JITCompilerFunction;

// Provide a wrapper for X86CompilationCallback2 that saves non-traditional
// callee saved registers, for the fastcc calling convention.
extern "C" {
#if defined(__i386__) || defined(i386) || defined(_M_IX86)
#ifndef _MSC_VER
  void X86CompilationCallback(void);
  asm(
    ".text\n"
    ".align 8\n"
    ".globl X86CompilationCallback\n"
  "X86CompilationCallback:\n"
    "pushl   %ebp\n"
    "movl    %esp, %ebp\n"    // Standard prologue
    "pushl   %eax\n"
    "pushl   %edx\n"          // save EAX/EDX
    "call X86CompilationCallback2\n"
    "popl    %edx\n"
    "popl    %eax\n"
    "popl    %ebp\n"
    "ret\n");
#else
  extern "C" void *_AddressOfReturnAddress(void);
  #pragma intrinsic(_AddressOfReturnAddress)

  void X86CompilationCallback2(void);

  _declspec(naked) void X86CompilationCallback(void) {
    __asm {
      push  eax
      push  edx
      call  X86CompilationCallback2
      pop   edx
      pop   eax
      ret
    }
  }
#endif

#else
  // Not an i386 host
  void X86CompilationCallback() {
    assert(0 && "This is not a X86, you can't execute this!");
    abort();
  }
#endif
}

/// X86CompilationCallback - This is the target-specific function invoked by the
/// function stub when we did not know the real target of a call.  This function
/// must locate the start of the stub or call site and pass it into the JIT
/// compiler function.
extern "C" void X86CompilationCallback2() {
#ifdef _MSC_VER
  assert(sizeof(size_t) == 4); // FIXME: handle Win64
  unsigned *RetAddrLoc = (unsigned *)_AddressOfReturnAddress();
  RetAddrLoc += 3;  // skip over ret addr, edx, eax
  unsigned RetAddr = *RetAddrLoc;
#else
  unsigned *StackPtr = (unsigned*)__builtin_frame_address(1);
  unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(1);
  unsigned *RetAddrLoc = &StackPtr[1];

  // NOTE: __builtin_frame_address doesn't work if frame pointer elimination has
  // been performed.  Having a variable sized alloca disables frame pointer
  // elimination currently, even if it's dead.  This is a gross hack.
  alloca(10+(RetAddr >> 31));

#endif
  assert(*RetAddrLoc == RetAddr &&
         "Could not find return address on the stack!");

  // It's a stub if there is an interrupt marker after the call.
  bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;

  // The call instruction should have pushed the return value onto the stack...
  RetAddr -= 4;  // Backtrack to the reference itself...

#if 0
  DEBUG(std::cerr << "In callback! Addr=" << (void*)RetAddr
                  << " ESP=" << (void*)StackPtr
                  << ": Resolving call to function: "
                  << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n");
#endif

  // Sanity check to make sure this really is a call instruction.
  assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&"Not a call instr!");

  unsigned NewVal = (intptr_t)JITCompilerFunction((void*)(intptr_t)RetAddr);

  // Rewrite the call target... so that we don't end up here every time we
  // execute the call.
  *(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;

  if (isStub) {
    // If this is a stub, rewrite the call into an unconditional branch
    // instruction so that two return addresses are not pushed onto the stack
    // when the requested function finally gets called.  This also makes the
    // 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
    ((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;
  }

  // Change the return address to reexecute the call instruction...
  *RetAddrLoc -= 5;
}

TargetJITInfo::LazyResolverFn
X86JITInfo::getLazyResolverFunction(JITCompilerFn F) {
  JITCompilerFunction = F;
  return X86CompilationCallback;
}

void *X86JITInfo::emitFunctionStub(void *Fn, MachineCodeEmitter &MCE) {
  if (Fn != X86CompilationCallback) {
    MCE.startFunctionStub(5);
    MCE.emitByte(0xE9);
    MCE.emitWord((intptr_t)Fn-MCE.getCurrentPCValue()-4);
    return MCE.finishFunctionStub(0);
  }

  MCE.startFunctionStub(6);
  MCE.emitByte(0xE8);   // Call with 32 bit pc-rel destination...

  MCE.emitWord((intptr_t)Fn-MCE.getCurrentPCValue()-4);

  MCE.emitByte(0xCD);   // Interrupt - Just a marker identifying the stub!
  return MCE.finishFunctionStub(0);
}

/// relocate - Before the JIT can run a block of code that has been emitted,
/// it must rewrite the code to contain the actual addresses of any
/// referenced global symbols.
void X86JITInfo::relocate(void *Function, MachineRelocation *MR,
                          unsigned NumRelocs) {
  for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {
    void *RelocPos = (char*)Function + MR->getMachineCodeOffset();
    intptr_t ResultPtr = (intptr_t)MR->getResultPointer();
    switch ((X86::RelocationType)MR->getRelocationType()) {
    case X86::reloc_pcrel_word:
      // PC relative relocation, add the relocated value to the value already in
      // memory, after we adjust it for where the PC is.
      ResultPtr = ResultPtr-(intptr_t)RelocPos-4;
      *((intptr_t*)RelocPos) += ResultPtr;
      break;
    case X86::reloc_absolute_word:
      // Absolute relocation, just add the relocated value to the value already
      // in memory.
      *((intptr_t*)RelocPos) += ResultPtr;
      break;
    }
  }
}
<commit_msg>Since everyone else has "fixed" this file, might as well join in the fun. * Change assert() to std::cerr printout, as it will not appear in opt builds * Add comments to clarify what #ifdef/#else/#endif match what condition(s)<commit_after>//===-- X86JITInfo.cpp - Implement the JIT interfaces for the X86 target --===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the JIT interfaces for the X86 target.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "jit"
#include <cstdlib>
#include "X86JITInfo.h"
#include "X86Relocations.h"
#include "llvm/CodeGen/MachineCodeEmitter.h"
#include "llvm/Config/alloca.h"
using namespace llvm;

void X86JITInfo::replaceMachineCodeForFunction(void *Old, void *New) {
  unsigned char *OldByte = (unsigned char *)Old;
  *OldByte++ = 0xE9;                // Emit JMP opcode.
  unsigned *OldWord = (unsigned *)OldByte;
  unsigned NewAddr = (intptr_t)New;
  unsigned OldAddr = (intptr_t)OldWord;
  *OldWord = NewAddr - OldAddr - 4; // Emit PC-relative addr of New code.
}

/// JITCompilerFunction - This contains the address of the JIT function used to
/// compile a function lazily.
static TargetJITInfo::JITCompilerFn JITCompilerFunction;

// Provide a wrapper for X86CompilationCallback2 that saves non-traditional
// callee saved registers, for the fastcc calling convention.
extern "C" {
#if defined(__i386__) || defined(i386) || defined(_M_IX86)
#ifndef _MSC_VER
  void X86CompilationCallback(void);
  asm(
    ".text\n"
    ".align 8\n"
    ".globl X86CompilationCallback\n"
  "X86CompilationCallback:\n"
    "pushl   %ebp\n"
    "movl    %esp, %ebp\n"    // Standard prologue
    "pushl   %eax\n"
    "pushl   %edx\n"          // save EAX/EDX
    "call X86CompilationCallback2\n"
    "popl    %edx\n"
    "popl    %eax\n"
    "popl    %ebp\n"
    "ret\n");
#else
  extern "C" void *_AddressOfReturnAddress(void);
  #pragma intrinsic(_AddressOfReturnAddress)

  void X86CompilationCallback2(void);

  _declspec(naked) void X86CompilationCallback(void) {
    __asm {
      push  eax
      push  edx
      call  X86CompilationCallback2
      pop   edx
      pop   eax
      ret
    }
  }
#endif // _MSC_VER

#else // Not an i386 host
  void X86CompilationCallback() {
    std::cerr << "Cannot call X86CompilationCallback() on a non-x86 arch!\n";
    abort();
  }
#endif
}

/// X86CompilationCallback - This is the target-specific function invoked by the
/// function stub when we did not know the real target of a call.  This function
/// must locate the start of the stub or call site and pass it into the JIT
/// compiler function.
extern "C" void X86CompilationCallback2() {
#ifdef _MSC_VER
  assert(sizeof(size_t) == 4); // FIXME: handle Win64
  unsigned *RetAddrLoc = (unsigned *)_AddressOfReturnAddress();
  RetAddrLoc += 3;  // skip over ret addr, edx, eax
  unsigned RetAddr = *RetAddrLoc;
#else
  unsigned *StackPtr = (unsigned*)__builtin_frame_address(1);
  unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(1);
  unsigned *RetAddrLoc = &StackPtr[1];

  // NOTE: __builtin_frame_address doesn't work if frame pointer elimination has
  // been performed.  Having a variable sized alloca disables frame pointer
  // elimination currently, even if it's dead.  This is a gross hack.
  alloca(10+(RetAddr >> 31));

#endif
  assert(*RetAddrLoc == RetAddr &&
         "Could not find return address on the stack!");

  // It's a stub if there is an interrupt marker after the call.
  bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;

  // The call instruction should have pushed the return value onto the stack...
  RetAddr -= 4;  // Backtrack to the reference itself...

#if 0
  DEBUG(std::cerr << "In callback! Addr=" << (void*)RetAddr
                  << " ESP=" << (void*)StackPtr
                  << ": Resolving call to function: "
                  << TheVM->getFunctionReferencedName((void*)RetAddr) << "\n");
#endif

  // Sanity check to make sure this really is a call instruction.
  assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&"Not a call instr!");

  unsigned NewVal = (intptr_t)JITCompilerFunction((void*)(intptr_t)RetAddr);

  // Rewrite the call target... so that we don't end up here every time we
  // execute the call.
  *(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;

  if (isStub) {
    // If this is a stub, rewrite the call into an unconditional branch
    // instruction so that two return addresses are not pushed onto the stack
    // when the requested function finally gets called.  This also makes the
    // 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
    ((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;
  }

  // Change the return address to reexecute the call instruction...
  *RetAddrLoc -= 5;
}

TargetJITInfo::LazyResolverFn
X86JITInfo::getLazyResolverFunction(JITCompilerFn F) {
  JITCompilerFunction = F;
  return X86CompilationCallback;
}

void *X86JITInfo::emitFunctionStub(void *Fn, MachineCodeEmitter &MCE) {
  if (Fn != X86CompilationCallback) {
    MCE.startFunctionStub(5);
    MCE.emitByte(0xE9);
    MCE.emitWord((intptr_t)Fn-MCE.getCurrentPCValue()-4);
    return MCE.finishFunctionStub(0);
  }

  MCE.startFunctionStub(6);
  MCE.emitByte(0xE8);   // Call with 32 bit pc-rel destination...

  MCE.emitWord((intptr_t)Fn-MCE.getCurrentPCValue()-4);

  MCE.emitByte(0xCD);   // Interrupt - Just a marker identifying the stub!
  return MCE.finishFunctionStub(0);
}

/// relocate - Before the JIT can run a block of code that has been emitted,
/// it must rewrite the code to contain the actual addresses of any
/// referenced global symbols.
void X86JITInfo::relocate(void *Function, MachineRelocation *MR,
                          unsigned NumRelocs) {
  for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {
    void *RelocPos = (char*)Function + MR->getMachineCodeOffset();
    intptr_t ResultPtr = (intptr_t)MR->getResultPointer();
    switch ((X86::RelocationType)MR->getRelocationType()) {
    case X86::reloc_pcrel_word:
      // PC relative relocation, add the relocated value to the value already in
      // memory, after we adjust it for where the PC is.
      ResultPtr = ResultPtr-(intptr_t)RelocPos-4;
      *((intptr_t*)RelocPos) += ResultPtr;
      break;
    case X86::reloc_absolute_word:
      // Absolute relocation, just add the relocated value to the value already
      // in memory.
      *((intptr_t*)RelocPos) += ResultPtr;
      break;
    }
  }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: salvd.cxx,v $
 *
 *  $Revision: 1.22 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-05 17:01:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that 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 library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#include "salvd.h"
#include "salinst.h"
#include "salgdi.h"
#include "saldata.hxx"

#include "vcl/sysdata.hxx"

// -----------------------------------------------------------------------

SalVirtualDevice* AquaSalInstance::CreateVirtualDevice( SalGraphics* pGraphics,
    long nDX, long nDY, USHORT nBitCount, const SystemGraphicsData *pData )
{
    return new AquaSalVirtualDevice( static_cast< AquaSalGraphics* >( pGraphics ), nDX, nDY, nBitCount, pData );
}

// -----------------------------------------------------------------------

void AquaSalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice )
{
    delete pDevice;
}

// =======================================================================

AquaSalVirtualDevice::AquaSalVirtualDevice( AquaSalGraphics* pGraphic, long nDX, long nDY, USHORT nBitCount, const SystemGraphicsData *pData )
: mbGraphicsUsed( false ),
  mxContext( 0 )
{
    if( pGraphic && pData && pData->rCGContext)
    {
        // Create virtual device based on existing SystemGraphicsData
        // We ignore nDx and nDY, as the desired size comes from the SystemGraphicsData
        mxContext = pData->rCGContext;
        mbForeignContext = true;        // the mxContext is from pData
        mpGraphics = pGraphic;
        mpGraphics->SetVirDevGraphics( mxContext, true );
    }
    else
    {
        // create empty new virtual device
        mbForeignContext = false;           // the mxContext is created within VCL
        mpGraphics = new AquaSalGraphics(); // never fails

        if( nDX && nDY )
            SetSize( nDX, nDY );

        // NOTE: if SetSize does not succeed, we just ignore the nDX and nDY
    }
}

// -----------------------------------------------------------------------

AquaSalVirtualDevice::~AquaSalVirtualDevice()
{
    if( mpGraphics )
    {
        mpGraphics->SetVirDevGraphics( 0, true );
        delete mpGraphics;
        mpGraphics = 0;
    }
    Destroy();
}

// -----------------------------------------------------------------------

void AquaSalVirtualDevice::Destroy()
{
    if( mbForeignContext ) {
        // Do not delete mxContext that we have received from outside VCL
        return;
    }

    if( mxContext )
    {
        if( mpGraphics )
            mpGraphics->SetVirDevGraphics( 0, true );
        void* pBuffer = CGBitmapContextGetData(mxContext);
        CFRelease( mxContext );
        mxContext = 0;
        if( pBuffer )
            free( pBuffer );
    }
}
// -----------------------------------------------------------------------

SalGraphics* AquaSalVirtualDevice::GetGraphics()
{
    if( mbGraphicsUsed || !mpGraphics )
        return 0;

    mbGraphicsUsed = true;
    return mpGraphics;
}

// -----------------------------------------------------------------------

void AquaSalVirtualDevice::ReleaseGraphics( SalGraphics *pGraphics )
{
    mbGraphicsUsed = false;
}

// -----------------------------------------------------------------------

BOOL AquaSalVirtualDevice::SetSize( long nDX, long nDY )
{
    if( mbForeignContext )
    {
        // Do not delete/resize mxContext that we have received from outside VCL
        return true;
    }

    if( mxContext &&
        ( nDX == static_cast<long> (CGBitmapContextGetWidth( mxContext ) ) ) &&
        ( nDY == static_cast<long> (CGBitmapContextGetHeight( mxContext ) ) ) )
    {
        // Yay, we do not have to do anything :)
        return true;
    }

    Destroy();

    void* pData = malloc( nDX * 4 * nDY );
    if (pData)
    {
        mxContext = CGBitmapContextCreate( pData, nDX, nDY, 8, nDX * 4, GetSalData()->mxRGBSpace, kCGImageAlphaNoneSkipFirst );

        if( mxContext )
        {
            if( mpGraphics )
                mpGraphics->SetVirDevGraphics( mxContext, true );
        }
        else
        {
            free (pData);
            DBG_ERROR( "vcl::AquaSalVirtualDevice::SetSize(), could not create Bitmap Context" );
        }
    }
    else
    {
        DBG_ERROR( "vcl::AquaSalVirtualDevice::SetSize(), could not allocate bitmap data" );
    }

    return mxContext != 0;
}

// -----------------------------------------------------------------------

void AquaSalVirtualDevice::GetSize( long& rWidth, long& rHeight )
{
    if( mxContext )
    {
        rWidth = CGBitmapContextGetWidth( mxContext );
        rHeight = CGBitmapContextGetHeight( mxContext );
    }
    else
    {
        rWidth = 0;
        rHeight = 0;
    }
}
<commit_msg>INTEGRATION: CWS changefileheader (1.22.22); FILE MERGED 2008/03/28 15:44:06 rt 1.22.22.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: salvd.cxx,v $
 * $Revision: 1.23 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#include "salvd.h"
#include "salinst.h"
#include "salgdi.h"
#include "saldata.hxx"

#include "vcl/sysdata.hxx"

// -----------------------------------------------------------------------

SalVirtualDevice* AquaSalInstance::CreateVirtualDevice( SalGraphics* pGraphics,
    long nDX, long nDY, USHORT nBitCount, const SystemGraphicsData *pData )
{
    return new AquaSalVirtualDevice( static_cast< AquaSalGraphics* >( pGraphics ), nDX, nDY, nBitCount, pData );
}

// -----------------------------------------------------------------------

void AquaSalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice )
{
    delete pDevice;
}

// =======================================================================

AquaSalVirtualDevice::AquaSalVirtualDevice( AquaSalGraphics* pGraphic, long nDX, long nDY, USHORT nBitCount, const SystemGraphicsData *pData )
: mbGraphicsUsed( false ),
  mxContext( 0 )
{
    if( pGraphic && pData && pData->rCGContext)
    {
        // Create virtual device based on existing SystemGraphicsData
        // We ignore nDx and nDY, as the desired size comes from the SystemGraphicsData
        mxContext = pData->rCGContext;
        mbForeignContext = true;        // the mxContext is from pData
        mpGraphics = pGraphic;
        mpGraphics->SetVirDevGraphics( mxContext, true );
    }
    else
    {
        // create empty new virtual device
        mbForeignContext = false;           // the mxContext is created within VCL
        mpGraphics = new AquaSalGraphics(); // never fails

        if( nDX && nDY )
            SetSize( nDX, nDY );

        // NOTE: if SetSize does not succeed, we just ignore the nDX and nDY
    }
}

// -----------------------------------------------------------------------

AquaSalVirtualDevice::~AquaSalVirtualDevice()
{
    if( mpGraphics )
    {
        mpGraphics->SetVirDevGraphics( 0, true );
        delete mpGraphics;
        mpGraphics = 0;
    }
    Destroy();
}

// -----------------------------------------------------------------------

void AquaSalVirtualDevice::Destroy()
{
    if( mbForeignContext ) {
        // Do not delete mxContext that we have received from outside VCL
        return;
    }

    if( mxContext )
    {
        if( mpGraphics )
            mpGraphics->SetVirDevGraphics( 0, true );
        void* pBuffer = CGBitmapContextGetData(mxContext);
        CFRelease( mxContext );
        mxContext = 0;
        if( pBuffer )
            free( pBuffer );
    }
}
// -----------------------------------------------------------------------

SalGraphics* AquaSalVirtualDevice::GetGraphics()
{
    if( mbGraphicsUsed || !mpGraphics )
        return 0;

    mbGraphicsUsed = true;
    return mpGraphics;
}

// -----------------------------------------------------------------------

void AquaSalVirtualDevice::ReleaseGraphics( SalGraphics *pGraphics )
{
    mbGraphicsUsed = false;
}

// -----------------------------------------------------------------------

BOOL AquaSalVirtualDevice::SetSize( long nDX, long nDY )
{
    if( mbForeignContext )
    {
        // Do not delete/resize mxContext that we have received from outside VCL
        return true;
    }

    if( mxContext &&
        ( nDX == static_cast<long> (CGBitmapContextGetWidth( mxContext ) ) ) &&
        ( nDY == static_cast<long> (CGBitmapContextGetHeight( mxContext ) ) ) )
    {
        // Yay, we do not have to do anything :)
        return true;
    }

    Destroy();

    void* pData = malloc( nDX * 4 * nDY );
    if (pData)
    {
        mxContext = CGBitmapContextCreate( pData, nDX, nDY, 8, nDX * 4, GetSalData()->mxRGBSpace, kCGImageAlphaNoneSkipFirst );

        if( mxContext )
        {
            if( mpGraphics )
                mpGraphics->SetVirDevGraphics( mxContext, true );
        }
        else
        {
            free (pData);
            DBG_ERROR( "vcl::AquaSalVirtualDevice::SetSize(), could not create Bitmap Context" );
        }
    }
    else
    {
        DBG_ERROR( "vcl::AquaSalVirtualDevice::SetSize(), could not allocate bitmap data" );
    }

    return mxContext != 0;
}

// -----------------------------------------------------------------------

void AquaSalVirtualDevice::GetSize( long& rWidth, long& rHeight )
{
    if( mxContext )
    {
        rWidth = CGBitmapContextGetWidth( mxContext );
        rHeight = CGBitmapContextGetHeight( mxContext );
    }
    else
    {
        rWidth = 0;
        rHeight = 0;
    }
}
<|endoftext|>


<commit_before><commit_msg>protect against past-the-end access of empty string<commit_after><|endoftext|>


<commit_before>#ifndef TAKEWHILE__H__
#define TAKEWHILE__H__

#include "iterbase.hpp"

#include <utility>
#include <iterator>
#include <initializer_list>

namespace iter {

    //Forward declarations of TakeWhile and takewhile
    template <typename FilterFunc, typename Container>
    class TakeWhile;

    template <typename FilterFunc, typename Container>
    TakeWhile<FilterFunc, Container> takewhile(FilterFunc, Container&&);

    template <typename FilterFunc, typename T>
    TakeWhile<FilterFunc, std::initializer_list<T>> takewhile(
            FilterFunc, std::initializer_list<T>);

    template <typename FilterFunc, typename Container>
    class TakeWhile {
        private:
            Container container;
            FilterFunc filter_func;

            friend TakeWhile takewhile<FilterFunc, Container>(
                    FilterFunc, Container&&);

            template <typename FF, typename T>
            friend TakeWhile<FF, std::initializer_list<T>> takewhile(
                    FF, std::initializer_list<T>);

            // Value constructor for use only in the takewhile function
            TakeWhile(FilterFunc filter_func, Container container)
                : container(std::forward<Container>(container)),
                filter_func(filter_func)
            { }

            TakeWhile () = delete;
            TakeWhile& operator=(const TakeWhile&) = delete;

        public:
            TakeWhile(const TakeWhile&) = default;

            class Iterator {
                private:
                    using iter_type = iterator_type<Container>;
                    iterator_type<Container> sub_iter;
                    const iterator_type<Container> sub_end;
                    FilterFunc filter_func;

                    // check if the current value is true under the predicate
                    // if it is not, set the sub_iter to the end using
                    // placement new to avoid the requirement of the iterator
                    // having an operator=
                    void check_current() {
                        if (!this->filter_func(*this->sub_iter)) {
                            this->sub_iter.~iter_type();
                            new(&this->sub_iter) iterator_type<Container>(
                                    this->sub_end);
                        }
                    }

                public:
                    Iterator (iterator_type<Container> iter,
                            iterator_type<Container> end,
                            FilterFunc filter_func)
                        : sub_iter{iter},
                        sub_end{end},
                        filter_func(filter_func)
                    {
                        if (this->sub_iter != this->sub_end) {
                            // only do the check if not already at the end
                            this->check_current();
                        }
                    }

                    iterator_deref<Container> operator*() const {
                        return *this->sub_iter;
                    }

                    Iterator& operator++() {
                        ++this->sub_iter;
                        this->check_current();
                        return *this;
                    }

                    bool operator!=(const Iterator& other) const {
                        return this->sub_iter != other.sub_iter;
                    }
            };

            Iterator begin() {
                return {std::begin(this->container),
                        std::end(this->container),
                        this->filter_func};
            }

            Iterator end() {
                return {std::end(this->container),
                        std::end(this->container),
                        this->filter_func};
            }

    };

    // Helper function to instantiate a TakeWhile
    template <typename FilterFunc, typename Container>
    TakeWhile<FilterFunc, Container> takewhile(
            FilterFunc filter_func, Container&& container) {
        return {filter_func, std::forward<Container>(container)};
    }

    template <typename FilterFunc, typename T>
    TakeWhile<FilterFunc, std::initializer_list<T>> takewhile(
            FilterFunc filter_func, std::initializer_list<T> il)
    {
        return {filter_func, std::move(il)};
    }

}

#endif //ifndef TAKEWHILE__H__
<commit_msg>takewhile iter inherits from std iterator<commit_after>#ifndef ITER_TAKEWHILE_H_
#define ITER_TAKEWHILE_H_

#include "iterbase.hpp"

#include <utility>
#include <iterator>
#include <initializer_list>

namespace iter {

    //Forward declarations of TakeWhile and takewhile
    template <typename FilterFunc, typename Container>
    class TakeWhile;

    template <typename FilterFunc, typename Container>
    TakeWhile<FilterFunc, Container> takewhile(FilterFunc, Container&&);

    template <typename FilterFunc, typename T>
    TakeWhile<FilterFunc, std::initializer_list<T>> takewhile(
            FilterFunc, std::initializer_list<T>);

    template <typename FilterFunc, typename Container>
    class TakeWhile {
        private:
            Container container;
            FilterFunc filter_func;

            friend TakeWhile takewhile<FilterFunc, Container>(
                    FilterFunc, Container&&);

            template <typename FF, typename T>
            friend TakeWhile<FF, std::initializer_list<T>> takewhile(
                    FF, std::initializer_list<T>);

            // Value constructor for use only in the takewhile function
            TakeWhile(FilterFunc filter_func, Container container)
                : container(std::forward<Container>(container)),
                filter_func(filter_func)
            { }

        public:

            class Iterator
                : public std::iterator<std::input_iterator_tag,
                    iterator_traits_deref<Container>>
            {
                private:
                    using iter_type = iterator_type<Container>;
                    iterator_type<Container> sub_iter;
                    const iterator_type<Container> sub_end;
                    FilterFunc filter_func;

                    // check if the current value is true under the predicate
                    // if it is not, set the sub_iter to the end using
                    // placement new to avoid the requirement of the iterator
                    // having an operator=
                    void check_current() {
                        if (!this->filter_func(*this->sub_iter)) {
                            this->sub_iter.~iter_type();
                            new(&this->sub_iter) iterator_type<Container>(
                                    this->sub_end);
                        }
                    }

                public:
                    Iterator (iterator_type<Container> iter,
                            iterator_type<Container> end,
                            FilterFunc filter_func)
                        : sub_iter{iter},
                        sub_end{end},
                        filter_func(filter_func)
                    {
                        if (this->sub_iter != this->sub_end) {
                            // only do the check if not already at the end
                            this->check_current();
                        }
                    }

                    iterator_deref<Container> operator*() const {
                        return *this->sub_iter;
                    }

                    Iterator& operator++() {
                        ++this->sub_iter;
                        this->check_current();
                        return *this;
                    }

                    bool operator!=(const Iterator& other) const {
                        return this->sub_iter != other.sub_iter;
                    }
            };

            Iterator begin() {
                return {std::begin(this->container),
                        std::end(this->container),
                        this->filter_func};
            }

            Iterator end() {
                return {std::end(this->container),
                        std::end(this->container),
                        this->filter_func};
            }

    };

    // Helper function to instantiate a TakeWhile
    template <typename FilterFunc, typename Container>
    TakeWhile<FilterFunc, Container> takewhile(
            FilterFunc filter_func, Container&& container) {
        return {filter_func, std::forward<Container>(container)};
    }

    template <typename FilterFunc, typename T>
    TakeWhile<FilterFunc, std::initializer_list<T>> takewhile(
            FilterFunc filter_func, std::initializer_list<T> il)
    {
        return {filter_func, std::move(il)};
    }

}

#endif
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <cstdio>
#include <map>

#include "testing/gtest/include/gtest/gtest.h"

#include "webrtc/system_wrappers/interface/clock.h"
#include "webrtc/typedefs.h"
#include "webrtc/video_engine/new_include/video_engine.h"
#include "webrtc/video_engine/test/common/direct_transport.h"
#include "webrtc/video_engine/test/common/flags.h"
#include "webrtc/video_engine/test/common/generate_ssrcs.h"
#include "webrtc/video_engine/test/common/run_tests.h"
#include "webrtc/video_engine/test/common/video_capturer.h"
#include "webrtc/video_engine/test/common/video_renderer.h"

namespace webrtc {

class LoopbackTest : public ::testing::Test {
 protected:
  std::map<uint32_t, bool> reserved_ssrcs;
};

TEST_F(LoopbackTest, Test) {
  test::VideoRenderer* local_preview = test::VideoRenderer::Create(
      "Local Preview", test::flags::Width(), test::flags::Height());
  test::VideoRenderer* loopback_video = test::VideoRenderer::Create(
      "Loopback Video", test::flags::Width(), test::flags::Height());

  newapi::VideoEngine* video_engine =
      newapi::VideoEngine::Create(webrtc::newapi::VideoEngineConfig());

  test::DirectTransport transport(NULL);
  newapi::VideoCall* call = video_engine->CreateCall(&transport);

  // Loopback, call sends to itself.
  transport.SetReceiver(call->Receiver());

  newapi::VideoSendStream::Config send_config = call->GetDefaultSendConfig();
  test::GenerateRandomSsrcs(&send_config, &reserved_ssrcs);

  send_config.local_renderer = local_preview;

  // TODO(pbos): static_cast shouldn't be required after mflodman refactors the
  //             VideoCodec struct.
  send_config.codec.width = static_cast<uint16_t>(test::flags::Width());
  send_config.codec.height = static_cast<uint16_t>(test::flags::Height());
  send_config.codec.minBitrate =
      static_cast<unsigned int>(test::flags::MinBitrate());
  send_config.codec.startBitrate =
      static_cast<unsigned int>(test::flags::StartBitrate());
  send_config.codec.maxBitrate =
      static_cast<unsigned int>(test::flags::MaxBitrate());

  newapi::VideoSendStream* send_stream = call->CreateSendStream(send_config);

  Clock* test_clock = Clock::GetRealTimeClock();

  test::VideoCapturer* camera =
      test::VideoCapturer::Create(send_stream->Input(),
                                  test::flags::Width(),
                                  test::flags::Height(),
                                  test::flags::Fps(),
                                  test_clock);

  newapi::VideoReceiveStream::Config receive_config =
      call->GetDefaultReceiveConfig();
  receive_config.rtp.ssrc = send_config.rtp.ssrcs[0];
  receive_config.renderer = loopback_video;

  newapi::VideoReceiveStream* receive_stream =
      call->CreateReceiveStream(receive_config);

  receive_stream->StartReceive();
  send_stream->StartSend();

  camera->Start();

  // TODO(pbos): Run this time limited (optionally), so it can run automated.
  puts(">> Press ENTER to continue...");
  while (getchar() != '\n' && !feof(stdin));

  receive_stream->StopReceive();
  send_stream->StopSend();

  // Stop sending
  delete camera;

  call->DestroyReceiveStream(receive_stream);
  call->DestroySendStream(send_stream);

  delete call;
  delete video_engine;

  delete loopback_video;
  delete local_preview;
}
}  // webrtc

int main(int argc, char* argv[]) {
  ::testing::InitGoogleTest(&argc, argv);
  webrtc::test::flags::Init(&argc, &argv);

  return webrtc::test::RunAllTests();
}
<commit_msg>Use scoped_ptr<> for loopback.cc<commit_after>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <cstdio>
#include <map>

#include "testing/gtest/include/gtest/gtest.h"

#include "webrtc/system_wrappers/interface/clock.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/typedefs.h"
#include "webrtc/video_engine/new_include/video_engine.h"
#include "webrtc/video_engine/test/common/direct_transport.h"
#include "webrtc/video_engine/test/common/flags.h"
#include "webrtc/video_engine/test/common/generate_ssrcs.h"
#include "webrtc/video_engine/test/common/run_tests.h"
#include "webrtc/video_engine/test/common/video_capturer.h"
#include "webrtc/video_engine/test/common/video_renderer.h"

namespace webrtc {

class LoopbackTest : public ::testing::Test {
 protected:
  std::map<uint32_t, bool> reserved_ssrcs;
};

TEST_F(LoopbackTest, Test) {
  scoped_ptr<test::VideoRenderer> local_preview(test::VideoRenderer::Create(
      "Local Preview", test::flags::Width(), test::flags::Height()));
  scoped_ptr<test::VideoRenderer> loopback_video(test::VideoRenderer::Create(
      "Loopback Video", test::flags::Width(), test::flags::Height()));

  scoped_ptr<newapi::VideoEngine> video_engine(
      newapi::VideoEngine::Create(webrtc::newapi::VideoEngineConfig()));

  test::DirectTransport transport(NULL);
  scoped_ptr<newapi::VideoCall> call(video_engine->CreateCall(&transport));

  // Loopback, call sends to itself.
  transport.SetReceiver(call->Receiver());

  newapi::VideoSendStream::Config send_config = call->GetDefaultSendConfig();
  test::GenerateRandomSsrcs(&send_config, &reserved_ssrcs);

  send_config.local_renderer = local_preview.get();

  // TODO(pbos): static_cast shouldn't be required after mflodman refactors the
  //             VideoCodec struct.
  send_config.codec.width = static_cast<uint16_t>(test::flags::Width());
  send_config.codec.height = static_cast<uint16_t>(test::flags::Height());
  send_config.codec.minBitrate =
      static_cast<unsigned int>(test::flags::MinBitrate());
  send_config.codec.startBitrate =
      static_cast<unsigned int>(test::flags::StartBitrate());
  send_config.codec.maxBitrate =
      static_cast<unsigned int>(test::flags::MaxBitrate());

  newapi::VideoSendStream* send_stream = call->CreateSendStream(send_config);

  Clock* test_clock = Clock::GetRealTimeClock();

  scoped_ptr<test::VideoCapturer> camera(
      test::VideoCapturer::Create(send_stream->Input(),
                                  test::flags::Width(),
                                  test::flags::Height(),
                                  test::flags::Fps(),
                                  test_clock));

  newapi::VideoReceiveStream::Config receive_config =
      call->GetDefaultReceiveConfig();
  receive_config.rtp.ssrc = send_config.rtp.ssrcs[0];
  receive_config.renderer = loopback_video.get();

  newapi::VideoReceiveStream* receive_stream =
      call->CreateReceiveStream(receive_config);

  receive_stream->StartReceive();
  send_stream->StartSend();

  camera->Start();

  // TODO(pbos): Run this time limited (optionally), so it can run automated.
  puts(">> Press ENTER to continue...");
  while (getchar() != '\n' && !feof(stdin))
    ;

  camera->Stop();
  send_stream->StopSend();
  receive_stream->StopReceive();

  call->DestroyReceiveStream(receive_stream);
  call->DestroySendStream(send_stream);
}
}  // webrtc

int main(int argc, char* argv[]) {
  ::testing::InitGoogleTest(&argc, argv);
  webrtc::test::flags::Init(&argc, &argv);

  return webrtc::test::RunAllTests();
}
<|endoftext|>