<commit_before>/*=========================================================================

  Program:   Visualization Library
  Module:    Glyph3D.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include "Glyph3D.hh"
#include "Trans.hh"
#include "FVectors.hh"
#include "FNormals.hh"
#include "vlMath.hh"

// Description
// Construct object with scaling on, scaling mode is by scalar value,
// scale factor = 1.0, the range is (0,1), orient geometry is on, and
// orientation is by vector.
vlGlyph3D::vlGlyph3D()
{
  this->Source = NULL;
  this->Scaling = 1;
  this->ScaleMode = SCALE_BY_SCALAR;
  this->ScaleFactor = 1.0;
  this->Range[0] = 0.0;
  this->Range[1] = 1.0;
  this->Orient = 1;
  this->VectorMode = USE_VECTOR;
}

vlGlyph3D::~vlGlyph3D()
{
}

void vlGlyph3D::PrintSelf(ostream& os, vlIndent indent)
{
  if (this->ShouldIPrint(vlGlyph3D::GetClassName()))
    {
    vlDataSetToPolyFilter::PrintSelf(os,indent);

    os << indent << "Source: " << this->Source << "\n";
    os << indent << "Scaling: " << (this->Scaling ? "On\n" : "Off\n");
    os << indent << "Scale Mode: " << (this->ScaleMode == SCALE_BY_SCALAR ? "Scale by scalar\n" : "Scale by vector\n");
    os << indent << "Scale Factor: " << this->ScaleFactor << "\n";
    os << indent << "Range: (" << this->Range[0] << ", " << this->Range[1] << ")\n";
    os << indent << "Orient: " << (this->Orient ? "On\n" : "Off\n");

    os << indent << "Orient Mode: " << (this->VectorMode == USE_VECTOR ? "Orient by vector\n" : "Orient by normal\n");
    }
}

void vlGlyph3D::Execute()
{
  vlPointData *pd;
  vlScalars *inScalars;
  vlVectors *inVectors;
  vlNormals *inNormals, *sourceNormals;
  int numPts, numSourcePts, numSourceCells;
  int inPtId, i;
  vlPoints *sourcePts;
  vlCellArray *sourceCells;
  vlFloatPoints *newPts;
  vlFloatScalars *newScalars=NULL;
  vlFloatVectors *newVectors=NULL;
  vlFloatNormals *newNormals=NULL;
  float *x, *v, vNew[3];
  vlTransform trans;
  vlCell *cell;
  vlIdList *cellPts;
  int npts, pts[MAX_CELL_SIZE];
  int orient, scaleSource, ptIncr, cellId;
  float scale, den;
  vlMath math;

  vlDebugMacro(<<"Generating glyphs");
  this->Initialize();

  pd = this->Input->GetPointData();
  inScalars = pd->GetScalars();
  inVectors = pd->GetVectors();
  inNormals = pd->GetNormals();

  numPts = this->Input->GetNumberOfPoints();
//
// Allocate storage for output PolyData
//
  sourcePts = this->Source->GetPoints();
  numSourcePts = sourcePts->GetNumberOfPoints();
  numSourceCells = this->Source->GetNumberOfCells();
  sourceNormals = this->Source->GetPointData()->GetNormals();

  newPts = new vlFloatPoints(numPts*numSourcePts);
  if (inScalars != NULL)
    newScalars = new vlFloatScalars(numPts*numSourcePts);
  if (inVectors != NULL || inNormals != NULL )
    newVectors = new vlFloatVectors(numPts*numSourcePts);
  if (sourceNormals != NULL)
    newNormals = new vlFloatNormals(numPts*numSourcePts);

  // Setting up for calls to PolyData::InsertNextCell()
  if ( (sourceCells=this->Source->GetVerts())->GetNumberOfCells() > 0 )
    {
    this->SetVerts(new vlCellArray(numPts*sourceCells->GetSize()));
    }
  if ( (sourceCells=this->Source->GetLines())->GetNumberOfCells() > 0 )
    {
    this->SetLines(new vlCellArray(numPts*sourceCells->GetSize()));
    }
  if ( (sourceCells=this->Source->GetPolys())->GetNumberOfCells() > 0 )
    {
    this->SetPolys(new vlCellArray(numPts*sourceCells->GetSize()));
    }
  if ( (sourceCells=this->Source->GetStrips())->GetNumberOfCells() > 0 )
    {
    this->SetStrips(new vlCellArray(numPts*sourceCells->GetSize()));
    }
//
// Copy (input scalars) to (output scalars) and either (input vectors or
// normals) to (output vectors). All other point attributes are copied
// from Source.
//
  pd = this->Source->GetPointData();
  this->PointData.CopyScalarsOff();
  this->PointData.CopyVectorsOff();
  this->PointData.CopyNormalsOff();
  this->PointData.CopyAllocate(pd,numPts*numSourcePts);
//
// First copy all topology (transformation independent)
//
  for (inPtId=0; inPtId < numPts; inPtId++)
    {
    ptIncr = inPtId * numSourcePts;
    for (cellId=0; cellId < numSourceCells; cellId++)
      {
      cell = this->Source->GetCell(cellId);
      cellPts = cell->GetPointIds();
      npts = cellPts->GetNumberOfIds();
      for (i=0; i < npts; i++) pts[i] = cellPts->GetId(i) + ptIncr;
      this->InsertNextCell(cell->GetCellType(),npts,pts);
      }
    }
//
// Traverse all Input points, transforming Source points and copying
// point attributes.
//
  if ( this->VectorMode == USE_VECTOR && inVectors != NULL ||
  this->VectorMode == USE_NORMAL && inNormals != NULL )
    orient = 1;
  else
    orient = 0;

  if ( this->Scaling &&
  ((this->ScaleMode == SCALE_BY_SCALAR && inScalars != NULL) ||
  (this->ScaleMode == SCALE_BY_VECTOR && (inVectors || inNormals))) )
    scaleSource = 1;
  else
    scaleSource = 0;

  for (inPtId=0; inPtId < numPts; inPtId++)
    {
    ptIncr = inPtId * numSourcePts;

    trans.Identity();

    // translate Source to Input point
    x = this->Input->GetPoint(inPtId);
    trans.Translate(x[0], x[1], x[2]);

    if ( this->VectorMode == USE_NORMAL )
      v = inNormals->GetNormal(inPtId);
    else
      v = inVectors->GetVector(inPtId);
    scale = math.Norm(v);

    if ( orient )
      {
      // Copy Input vector
      for (i=0; i < numSourcePts; i++)
        newVectors->InsertVector(ptIncr+i,v);

      if ( this->Orient )
        {
        vNew[0] = (v[0]+scale) / 2.0;
        vNew[1] = v[1] / 2.0;
        vNew[2] = v[2] / 2.0;
        trans.RotateWXYZ(180.0,vNew[0],vNew[1],vNew[2]);
        }
      }

    // determine scale factor from scalars if appropriate
    if ( inScalars != NULL )
      {
      // Copy Input scalar
      for (i=0; i < numSourcePts; i++)
        newScalars->InsertScalar(ptIncr+i,scale);

      if ( this->ScaleMode == SCALE_BY_SCALAR )
        {
        if ( (den = this->Range[1] - this->Range[0]) == 0.0 ) den = 1.0;
        scale = inScalars->GetScalar(inPtId);

        scale = (scale < this->Range[0] ? this->Range[0] :
                 (scale > this->Range[1] ? this->Range[1] : scale));
        scale = (scale - this->Range[0]) / den;

        }
      }

    // scale data if appropriate
    if ( scaleSource )
      {
      scale *= this->ScaleFactor;
      if ( scale == 0.0 ) scale = 1.0e-10;
      trans.Scale(scale,scale,scale);
      }

    // multiply points and normals by resulting matrix
    trans.MultiplyPoints(sourcePts,newPts);
    if ( sourceNormals != NULL )
      trans.MultiplyNormals(sourceNormals,newNormals);

    // Copy point data from source
    for (i=0; i < numSourcePts; i++)
      this->PointData.CopyData(pd,i,ptIncr+i);
    }
//
// Update ourselves
//
  this->SetPoints(newPts);
  this->PointData.SetScalars(newScalars);
  this->PointData.SetVectors(newVectors);
  this->PointData.SetNormals(newNormals);
  this->Squeeze();
}

// Description:
// Override update method because execution can branch two ways (Input
// and Source)
void vlGlyph3D::Update()
{
  // make sure input is available
  if ( this->Input == NULL )
    {
    vlErrorMacro(<< "No input!");
    return;
    }

  if ( this->Source == NULL )
    {
    vlErrorMacro(<< "No source data!");
    return;
    }

  // prevent chasing our tail
  if (this->Updating) return;

  this->Updating = 1;
  this->Input->Update();
  this->Source->Update();
  this->Updating = 0;

  if (this->Input->GetMTime() > this->GetMTime() ||
  this->Source->GetMTime() > this->GetMTime() ||
  this->GetMTime() > this->ExecuteTime )
    {
    if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);
    this->Execute();
    this->ExecuteTime.Modified();
    if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);
    }
}
<commit_msg>*** empty log message ***<commit_after>/*=========================================================================

  Program:   Visualization Library
  Module:    Glyph3D.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include "Glyph3D.hh"
#include "Trans.hh"
#include "FVectors.hh"
#include "FNormals.hh"
#include "vlMath.hh"

// Description
// Construct object with scaling on, scaling mode is by scalar value,
// scale factor = 1.0, the range is (0,1), orient geometry is on, and
// orientation is by vector.
vlGlyph3D::vlGlyph3D()
{
  this->Source = NULL;
  this->Scaling = 1;
  this->ScaleMode = SCALE_BY_SCALAR;
  this->ScaleFactor = 1.0;
  this->Range[0] = 0.0;
  this->Range[1] = 1.0;
  this->Orient = 1;
  this->VectorMode = USE_VECTOR;
}

vlGlyph3D::~vlGlyph3D()
{
}

void vlGlyph3D::Execute()
{
  vlPointData *pd;
  vlScalars *inScalars;
  vlVectors *inVectors;
  vlNormals *inNormals, *sourceNormals;
  int numPts, numSourcePts, numSourceCells;
  int inPtId, i;
  vlPoints *sourcePts;
  vlCellArray *sourceCells;
  vlFloatPoints *newPts;
  vlFloatScalars *newScalars=NULL;
  vlFloatVectors *newVectors=NULL;
  vlFloatNormals *newNormals=NULL;
  float *x, *v, vNew[3];
  vlTransform trans;
  vlCell *cell;
  vlIdList *cellPts;
  int npts, pts[MAX_CELL_SIZE];
  int orient, scaleSource, ptIncr, cellId;
  float scale, den;
  vlMath math;

  vlDebugMacro(<<"Generating glyphs");
  this->Initialize();

  pd = this->Input->GetPointData();
  inScalars = pd->GetScalars();
  inVectors = pd->GetVectors();
  inNormals = pd->GetNormals();

  numPts = this->Input->GetNumberOfPoints();
//
// Allocate storage for output PolyData
//
  sourcePts = this->Source->GetPoints();
  numSourcePts = sourcePts->GetNumberOfPoints();
  numSourceCells = this->Source->GetNumberOfCells();
  sourceNormals = this->Source->GetPointData()->GetNormals();

  newPts = new vlFloatPoints(numPts*numSourcePts);
  if (inScalars != NULL)
    newScalars = new vlFloatScalars(numPts*numSourcePts);
  if (inVectors != NULL || inNormals != NULL )
    newVectors = new vlFloatVectors(numPts*numSourcePts);
  if (sourceNormals != NULL)
    newNormals = new vlFloatNormals(numPts*numSourcePts);

  // Setting up for calls to PolyData::InsertNextCell()
  if ( (sourceCells=this->Source->GetVerts())->GetNumberOfCells() > 0 )
    {
    this->SetVerts(new vlCellArray(numPts*sourceCells->GetSize()));
    }
  if ( (sourceCells=this->Source->GetLines())->GetNumberOfCells() > 0 )
    {
    this->SetLines(new vlCellArray(numPts*sourceCells->GetSize()));
    }
  if ( (sourceCells=this->Source->GetPolys())->GetNumberOfCells() > 0 )
    {
    this->SetPolys(new vlCellArray(numPts*sourceCells->GetSize()));
    }
  if ( (sourceCells=this->Source->GetStrips())->GetNumberOfCells() > 0 )
    {
    this->SetStrips(new vlCellArray(numPts*sourceCells->GetSize()));
    }
//
// Copy (input scalars) to (output scalars) and either (input vectors or
// normals) to (output vectors). All other point attributes are copied
// from Source.
//
  pd = this->Source->GetPointData();
  this->PointData.CopyScalarsOff();
  this->PointData.CopyVectorsOff();
  this->PointData.CopyNormalsOff();
  this->PointData.CopyAllocate(pd,numPts*numSourcePts);
//
// First copy all topology (transformation independent)
//
  for (inPtId=0; inPtId < numPts; inPtId++)
    {
    ptIncr = inPtId * numSourcePts;
    for (cellId=0; cellId < numSourceCells; cellId++)
      {
      cell = this->Source->GetCell(cellId);
      cellPts = cell->GetPointIds();
      npts = cellPts->GetNumberOfIds();
      for (i=0; i < npts; i++) pts[i] = cellPts->GetId(i) + ptIncr;
      this->InsertNextCell(cell->GetCellType(),npts,pts);
      }
    }
//
// Traverse all Input points, transforming Source points and copying
// point attributes.
//
  if ( this->VectorMode == USE_VECTOR && inVectors != NULL ||
  this->VectorMode == USE_NORMAL && inNormals != NULL )
    orient = 1;
  else
    orient = 0;

  if ( this->Scaling &&
  ((this->ScaleMode == SCALE_BY_SCALAR && inScalars != NULL) ||
  (this->ScaleMode == SCALE_BY_VECTOR && (inVectors || inNormals))) )
    scaleSource = 1;
  else
    scaleSource = 0;

  for (inPtId=0; inPtId < numPts; inPtId++)
    {
    ptIncr = inPtId * numSourcePts;

    trans.Identity();

    // translate Source to Input point
    x = this->Input->GetPoint(inPtId);
    trans.Translate(x[0], x[1], x[2]);

    if ( this->VectorMode == USE_NORMAL )
      v = inNormals->GetNormal(inPtId);
    else
      v = inVectors->GetVector(inPtId);
    scale = math.Norm(v);

    if ( orient )
      {
      // Copy Input vector
      for (i=0; i < numSourcePts; i++)
        newVectors->InsertVector(ptIncr+i,v);

      if ( this->Orient )
        {
        vNew[0] = (v[0]+scale) / 2.0;
        vNew[1] = v[1] / 2.0;
        vNew[2] = v[2] / 2.0;
        trans.RotateWXYZ(180.0,vNew[0],vNew[1],vNew[2]);
        }
      }

    // determine scale factor from scalars if appropriate
    if ( inScalars != NULL )
      {
      // Copy Input scalar
      for (i=0; i < numSourcePts; i++)
        newScalars->InsertScalar(ptIncr+i,scale);

      if ( this->ScaleMode == SCALE_BY_SCALAR )
        {
        if ( (den = this->Range[1] - this->Range[0]) == 0.0 ) den = 1.0;
        scale = inScalars->GetScalar(inPtId);

        scale = (scale < this->Range[0] ? this->Range[0] :
                 (scale > this->Range[1] ? this->Range[1] : scale));
        scale = (scale - this->Range[0]) / den;

        }
      }

    // scale data if appropriate
    if ( scaleSource )
      {
      scale *= this->ScaleFactor;
      if ( scale == 0.0 ) scale = 1.0e-10;
      trans.Scale(scale,scale,scale);
      }

    // multiply points and normals by resulting matrix
    trans.MultiplyPoints(sourcePts,newPts);
    if ( sourceNormals != NULL )
      trans.MultiplyNormals(sourceNormals,newNormals);

    // Copy point data from source
    for (i=0; i < numSourcePts; i++)
      this->PointData.CopyData(pd,i,ptIncr+i);
    }
//
// Update ourselves
//
  this->SetPoints(newPts);
  this->PointData.SetScalars(newScalars);
  this->PointData.SetVectors(newVectors);
  this->PointData.SetNormals(newNormals);
  this->Squeeze();
}

// Description:
// Override update method because execution can branch two ways (Input
// and Source)
void vlGlyph3D::Update()
{
  // make sure input is available
  if ( this->Input == NULL )
    {
    vlErrorMacro(<< "No input!");
    return;
    }

  if ( this->Source == NULL )
    {
    vlErrorMacro(<< "No source data!");
    return;
    }

  // prevent chasing our tail
  if (this->Updating) return;

  this->Updating = 1;
  this->Input->Update();
  this->Source->Update();
  this->Updating = 0;

  if (this->Input->GetMTime() > this->GetMTime() ||
  this->Source->GetMTime() > this->GetMTime() ||
  this->GetMTime() > this->ExecuteTime )
    {
    if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg);
    this->Execute();
    this->ExecuteTime.Modified();
    if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg);
    }
}

void vlGlyph3D::PrintSelf(ostream& os, vlIndent indent)
{
  if (this->ShouldIPrint(vlGlyph3D::GetClassName()))
    {
    vlDataSetToPolyFilter::PrintSelf(os,indent);

    os << indent << "Source: " << this->Source << "\n";
    os << indent << "Scaling: " << (this->Scaling ? "On\n" : "Off\n");
    os << indent << "Scale Mode: " << (this->ScaleMode == SCALE_BY_SCALAR ? "Scale by scalar\n" : "Scale by vector\n");
    os << indent << "Scale Factor: " << this->ScaleFactor << "\n";
    os << indent << "Range: (" << this->Range[0] << ", " << this->Range[1] << ")\n";
    os << indent << "Orient: " << (this->Orient ? "On\n" : "Off\n");

    os << indent << "Orient Mode: " << (this->VectorMode == USE_VECTOR ? "Orient by vector\n" : "Orient by normal\n");
    }
}

<|endoftext|>


<commit_before>//===--- ASTScopePrinting.cpp - Swift Object-Oriented AST Scope -----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// This file implements the printing functions of the ASTScopeImpl ontology.
///
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTScope.h"

#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/Module.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/TypeRepr.h"
#include "swift/Basic/STLExtras.h"
#include "llvm/Support/Compiler.h"
#include <algorithm>

using namespace swift;
using namespace ast_scope;

#pragma mark dumping

void ASTScopeImpl::dump() const { print(llvm::errs(), 0, false); }

void ASTScopeImpl::dumpOneScopeMapLocation(
    std::pair<unsigned, unsigned> lineColumn) const {
  auto bufferID = getSourceFile()->getBufferID();
  if (!bufferID) {
    llvm::errs() << "***No buffer, dumping all scopes***";
    print(llvm::errs());
    return;
  }
  SourceLoc loc = getSourceManager().getLocForLineCol(
      *bufferID, lineColumn.first, lineColumn.second);
  if (loc.isInvalid())
    return;

  llvm::errs() << "***Scope at " << lineColumn.first << ":" << lineColumn.second
               << "***\n";
  auto *locScope = findInnermostEnclosingScope(loc);
  locScope->print(llvm::errs(), 0, false, false);

  // Dump the AST context, too.
  if (auto *dc = locScope->getDeclContext().getPtrOrNull())
    dc->printContext(llvm::errs());

  namelookup::ASTScopeDeclGatherer gatherer;
  // Print the local bindings introduced by this scope.
  locScope->lookupLocalBindings(gatherer);
  if (!gatherer.getDecls().empty()) {
    llvm::errs() << "Local bindings: ";
    interleave(gatherer.getDecls().begin(), gatherer.getDecls().end(),
               [&](ValueDecl *value) { llvm::errs() << value->getFullName(); },
               [&]() { llvm::errs() << " "; });
    llvm::errs() << "\n";
  }
}

llvm::raw_ostream &ASTScopeImpl::verificationError() const {
  return llvm::errs() << "ASTScopeImpl verification error in source file '"
                      << getSourceFile()->getFilename() << "': ";
}

#pragma mark printing

void ASTScopeImpl::print(llvm::raw_ostream &out, unsigned level, bool lastChild,
                         bool printChildren) const {
  // Indent for levels 2+.
  if (level > 1)
    out.indent((level - 1) * 2);

  // Print child marker and leading '-' for levels 1+.
  if (level > 0)
    out << (lastChild ? '`' : '|') << '-';

  out << getClassName();
  if (auto *a = addressForPrinting().getPtrOrNull())
    out << " " << a;
  printSpecifics(out);
  printRange(out);
  out << "\n";

  if (printChildren) {
    for (unsigned i : indices(getChildren())) {
      getChildren()[i]->print(out, level + 1,
                              /*lastChild=*/i == getChildren().size() - 1);
    }
  }
}

void ASTScopeImpl::printRange(llvm::raw_ostream &out) const {
  if (!cachedSourceRange)
    out << " (uncached)";
  SourceRange range = cachedSourceRange
                          ? getSourceRange(/*forDebugging=*/true)
                          : getUncachedSourceRange(/*forDebugging=*/true);
  if (range.isInvalid()) {
    out << " [invalid source range]";
    return;
  }

  auto startLineAndCol = getSourceManager().getLineAndColumn(range.Start);
  auto endLineAndCol = getSourceManager().getLineAndColumn(range.End);

  out << " [" << startLineAndCol.first << ":" << startLineAndCol.second << " - "
      << endLineAndCol.first << ":" << endLineAndCol.second << "]";
}

#pragma mark printSpecifics

void ASTSourceFileScope::printSpecifics(
    llvm::raw_ostream &out) const {
  out << " '" << SF->getFilename() << "'";
}

NullablePtr<const void> ASTScopeImpl::addressForPrinting() const {
  if (auto *p = getDecl().getPtrOrNull())
    return p;
  return nullptr;
}

void GTXScope::printSpecifics(llvm::raw_ostream &out) const {
  out << " ";
  if (shouldHaveABody() && !doesDeclHaveABody())
    out << "<no body>";

  else if (auto *n = getCorrespondingNominalTypeDecl().getPtrOrNull())
    out << "'" << n->getFullName() << "'";
  else
    out << "<no extended nominal?!>";
}

void GenericParamScope::printSpecifics(llvm::raw_ostream &out) const {
  out << " param " << index;
  auto *genericTypeParamDecl = paramList->getParams()[index];
  out << " '";
  genericTypeParamDecl->print(out);
  out << "'";
}

void AbstractFunctionDeclScope::printSpecifics(llvm::raw_ostream &out) const {
  out << " '" << decl->getFullName() << "'";
}

void AbstractPatternEntryScope::printSpecifics(llvm::raw_ostream &out) const {
  out << " entry " << patternEntryIndex;
}

void StatementConditionElementPatternScope::printSpecifics(
    llvm::raw_ostream &out) const {
  pattern->print(out);
}

void ConditionalClauseScope::printSpecifics(llvm::raw_ostream &out) const {
  ASTScopeImpl::printSpecifics(out);
  out << " index " << index;
}

void SubscriptDeclScope::printSpecifics(llvm::raw_ostream &out) const {
  out << " ";
  decl->dumpRef(out);
}

void VarDeclScope::printSpecifics(llvm::raw_ostream &out) const {
  out << " ";
  decl->dumpRef(out);
}

bool GTXScope::doesDeclHaveABody() const { return false; }

bool IterableTypeScope::doesDeclHaveABody() const {
  return getBraces().Start != getBraces().End;
}
<commit_msg>Better pattern printing<commit_after>//===--- ASTScopePrinting.cpp - Swift Object-Oriented AST Scope -----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// This file implements the printing functions of the ASTScopeImpl ontology.
///
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTScope.h"

#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/Module.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/TypeRepr.h"
#include "swift/Basic/STLExtras.h"
#include "llvm/Support/Compiler.h"
#include <algorithm>

using namespace swift;
using namespace ast_scope;

#pragma mark dumping

void ASTScopeImpl::dump() const { print(llvm::errs(), 0, false); }

void ASTScopeImpl::dumpOneScopeMapLocation(
    std::pair<unsigned, unsigned> lineColumn) const {
  auto bufferID = getSourceFile()->getBufferID();
  if (!bufferID) {
    llvm::errs() << "***No buffer, dumping all scopes***";
    print(llvm::errs());
    return;
  }
  SourceLoc loc = getSourceManager().getLocForLineCol(
      *bufferID, lineColumn.first, lineColumn.second);
  if (loc.isInvalid())
    return;

  llvm::errs() << "***Scope at " << lineColumn.first << ":" << lineColumn.second
               << "***\n";
  auto *locScope = findInnermostEnclosingScope(loc);
  locScope->print(llvm::errs(), 0, false, false);

  // Dump the AST context, too.
  if (auto *dc = locScope->getDeclContext().getPtrOrNull())
    dc->printContext(llvm::errs());

  namelookup::ASTScopeDeclGatherer gatherer;
  // Print the local bindings introduced by this scope.
  locScope->lookupLocalBindings(gatherer);
  if (!gatherer.getDecls().empty()) {
    llvm::errs() << "Local bindings: ";
    interleave(gatherer.getDecls().begin(), gatherer.getDecls().end(),
               [&](ValueDecl *value) { llvm::errs() << value->getFullName(); },
               [&]() { llvm::errs() << " "; });
    llvm::errs() << "\n";
  }
}

llvm::raw_ostream &ASTScopeImpl::verificationError() const {
  return llvm::errs() << "ASTScopeImpl verification error in source file '"
                      << getSourceFile()->getFilename() << "': ";
}

#pragma mark printing

void ASTScopeImpl::print(llvm::raw_ostream &out, unsigned level, bool lastChild,
                         bool printChildren) const {
  // Indent for levels 2+.
  if (level > 1)
    out.indent((level - 1) * 2);

  // Print child marker and leading '-' for levels 1+.
  if (level > 0)
    out << (lastChild ? '`' : '|') << '-';

  out << getClassName();
  if (auto *a = addressForPrinting().getPtrOrNull())
    out << " " << a;
  printSpecifics(out);
  printRange(out);
  out << "\n";

  if (printChildren) {
    for (unsigned i : indices(getChildren())) {
      getChildren()[i]->print(out, level + 1,
                              /*lastChild=*/i == getChildren().size() - 1);
    }
  }
}

void ASTScopeImpl::printRange(llvm::raw_ostream &out) const {
  if (!cachedSourceRange)
    out << " (uncached)";
  SourceRange range = cachedSourceRange
                          ? getSourceRange(/*forDebugging=*/true)
                          : getUncachedSourceRange(/*forDebugging=*/true);
  if (range.isInvalid()) {
    out << " [invalid source range]";
    return;
  }

  auto startLineAndCol = getSourceManager().getLineAndColumn(range.Start);
  auto endLineAndCol = getSourceManager().getLineAndColumn(range.End);

  out << " [" << startLineAndCol.first << ":" << startLineAndCol.second << " - "
      << endLineAndCol.first << ":" << endLineAndCol.second << "]";
}

#pragma mark printSpecifics

void ASTSourceFileScope::printSpecifics(
    llvm::raw_ostream &out) const {
  out << " '" << SF->getFilename() << "'";
}

NullablePtr<const void> ASTScopeImpl::addressForPrinting() const {
  if (auto *p = getDecl().getPtrOrNull())
    return p;
  return nullptr;
}

void GTXScope::printSpecifics(llvm::raw_ostream &out) const {
  out << " ";
  if (shouldHaveABody() && !doesDeclHaveABody())
    out << "<no body>";

  else if (auto *n = getCorrespondingNominalTypeDecl().getPtrOrNull())
    out << "'" << n->getFullName() << "'";
  else
    out << "<no extended nominal?!>";
}

void GenericParamScope::printSpecifics(llvm::raw_ostream &out) const {
  out << " param " << index;
  auto *genericTypeParamDecl = paramList->getParams()[index];
  out << " '";
  genericTypeParamDecl->print(out);
  out << "'";
}

void AbstractFunctionDeclScope::printSpecifics(llvm::raw_ostream &out) const {
  out << " '" << decl->getFullName() << "'";
}

void AbstractPatternEntryScope::printSpecifics(llvm::raw_ostream &out) const {
  out << " entry " << patternEntryIndex;
  getPattern()->forEachVariable([&](VarDecl *vd) {
    out << " '" << vd->getName() << "'";
  });
}

void StatementConditionElementPatternScope::printSpecifics(
    llvm::raw_ostream &out) const {
  pattern->print(out);
}

void ConditionalClauseScope::printSpecifics(llvm::raw_ostream &out) const {
  ASTScopeImpl::printSpecifics(out);
  out << " index " << index;
}

void SubscriptDeclScope::printSpecifics(llvm::raw_ostream &out) const {
  out << " ";
  decl->dumpRef(out);
}

void VarDeclScope::printSpecifics(llvm::raw_ostream &out) const {
  out << " ";
  decl->dumpRef(out);
}

bool GTXScope::doesDeclHaveABody() const { return false; }

bool IterableTypeScope::doesDeclHaveABody() const {
  return getBraces().Start != getBraces().End;
}
<|endoftext|>


<commit_before>//== RegionStore.cpp - Field-sensitive store model --------------*- C++ -*--==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a basic region store model. In this model, we do have field
// sensitivity. But we assume nothing about the heap shape. So recursive data
// structures are largely ignored. Basically we do 1-limiting analysis.
// Parameter pointers are assumed with no aliasing. Pointee objects of
// parameters are created lazily.
//
//===----------------------------------------------------------------------===//
#include "clang/Analysis/PathSensitive/MemRegion.h"
#include "clang/Analysis/PathSensitive/GRState.h"
#include "clang/Analysis/Analyses/LiveVariables.h"

#include "llvm/ADT/ImmutableMap.h"
#include "llvm/Support/Compiler.h"

using namespace clang;

typedef llvm::ImmutableMap<const MemRegion*, SVal> RegionBindingsTy;

namespace {

class VISIBILITY_HIDDEN RegionStoreManager : public StoreManager {
  RegionBindingsTy::Factory RBFactory;
  GRStateManager& StateMgr;
  MemRegionManager MRMgr;

public:
  RegionStoreManager(GRStateManager& mgr)
    : StateMgr(mgr), MRMgr(StateMgr.getAllocator()) {}

  virtual ~RegionStoreManager() {}

  SVal Retrieve(Store S, Loc L, QualType T);
  Store Bind(Store St, Loc LV, SVal V);

  Store getInitialStore();

  Store AddDecl(Store store, const VarDecl* VD, Expr* Ex, SVal InitVal,
                unsigned Count);

  Loc getVarLoc(const VarDecl* VD) {
    return loc::MemRegionVal(MRMgr.getVarRegion(VD));
  }

  Loc getElementLoc(const VarDecl* VD, SVal Idx);

  static inline RegionBindingsTy GetRegionBindings(Store store) {
   return RegionBindingsTy(static_cast<const RegionBindingsTy::TreeTy*>(store));
  }
};

} // end anonymous namespace

Loc RegionStoreManager::getElementLoc(const VarDecl* VD, SVal Idx) {
  MemRegion* R = MRMgr.getVarRegion(VD);
  ElementRegion* ER = MRMgr.getElementRegion(Idx, R);
  return loc::MemRegionVal(ER);
}

SVal RegionStoreManager::Retrieve(Store S, Loc L, QualType T) {
  assert(!isa<UnknownVal>(L) && "location unknown");
  assert(!isa<UndefinedVal>(L) && "location undefined");

  switch (L.getSubKind()) {
  case loc::MemRegionKind: {
    const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion();
    assert(R && "bad region");

    RegionBindingsTy B(static_cast<const RegionBindingsTy::TreeTy*>(S));
    RegionBindingsTy::data_type* V = B.lookup(R);
    return V ? *V : UnknownVal();
  }

  case loc::SymbolValKind:
    return UnknownVal();

  case loc::ConcreteIntKind:
    return UndefinedVal(); // As in BasicStoreManager.

  case loc::FuncValKind:
    return L;

  case loc::StringLiteralValKind:
    return UnknownVal();

  default:
    assert(false && "Invalid Location");
    break;
  }
}

Store RegionStoreManager::Bind(Store store, Loc LV, SVal V) {
  assert(LV.getSubKind() == loc::MemRegionKind);

  const MemRegion* R = cast<loc::MemRegionVal>(LV).getRegion();

  if (!R)
    return store;

  RegionBindingsTy B = GetRegionBindings(store);
  return V.isUnknown()
         ? RBFactory.Remove(B, R).getRoot()
         : RBFactory.Add(B, R, V).getRoot();
}

Store RegionStoreManager::getInitialStore() {
  typedef LiveVariables::AnalysisDataTy LVDataTy;
  LVDataTy& D = StateMgr.getLiveVariables().getAnalysisData();

  Store St = RBFactory.GetEmptyMap().getRoot();

  for (LVDataTy::decl_iterator I=D.begin_decl(), E=D.end_decl(); I != E; ++I) {
    NamedDecl* ND = const_cast<NamedDecl*>(I->first);

    if (VarDecl* VD = dyn_cast<VarDecl>(ND)) {
      // Punt on static variables for now.
      if (VD->getStorageClass() == VarDecl::Static)
        continue;

      QualType T = VD->getType();
      // Only handle pointers and integers for now.
      if (Loc::IsLocType(T) || T->isIntegerType()) {
        // Initialize globals and parameters to symbolic values.
        // Initialize local variables to undefined.
        SVal X = (VD->hasGlobalStorage() || isa<ParmVarDecl>(VD) ||
                  isa<ImplicitParamDecl>(VD))
                 ? SVal::GetSymbolValue(StateMgr.getSymbolManager(), VD)
                 : UndefinedVal();

        St = Bind(St, getVarLoc(VD), X);
      }
    }
  }
  return St;
}

Store RegionStoreManager::AddDecl(Store store,
                                  const VarDecl* VD, Expr* Ex,
                                  SVal InitVal, unsigned Count) {
  BasicValueFactory& BasicVals = StateMgr.getBasicVals();
  SymbolManager& SymMgr = StateMgr.getSymbolManager();

  if (VD->hasGlobalStorage()) {
    // Static global variables should not be visited here.
    assert(!(VD->getStorageClass() == VarDecl::Static &&
             VD->isFileVarDecl()));
    // Process static variables.
    if (VD->getStorageClass() == VarDecl::Static) {
      if (!Ex) {
        // Only handle pointer and integer static variables.

        QualType T = VD->getType();

        if (Loc::IsLocType(T))
          store = Bind(store, getVarLoc(VD),
                       loc::ConcreteInt(BasicVals.getValue(0, T)));

        else if (T->isIntegerType())
          store = Bind(store, getVarLoc(VD),
                       loc::ConcreteInt(BasicVals.getValue(0, T)));
        else
          assert("ignore other types of variables");
      } else {
        store = Bind(store, getVarLoc(VD), InitVal);
      }
    }
  } else {
    // Process local variables.

    QualType T = VD->getType();

    if (Loc::IsLocType(T) || T->isIntegerType()) {
      SVal V = Ex ? InitVal : UndefinedVal();
      if (Ex && InitVal.isUnknown()) {
        // "Conjured" symbols.
        SymbolID Sym = SymMgr.getConjuredSymbol(Ex, Count);
        V = Loc::IsLocType(Ex->getType())
          ? cast<SVal>(loc::SymbolVal(Sym))
          : cast<SVal>(nonloc::SymbolVal(Sym));
      }
      store = Bind(store, getVarLoc(VD), V);

    } else if (T->isArrayType()) {
      // Only handle constant size array.
      if (ConstantArrayType* CAT=dyn_cast<ConstantArrayType>(T.getTypePtr())) {

        llvm::APInt Size = CAT->getSize();

        for (llvm::APInt i = llvm::APInt::getNullValue(Size.getBitWidth());
             i != Size; ++i) {
          nonloc::ConcreteInt Idx(BasicVals.getValue(llvm::APSInt(i)));
          store = Bind(store, getElementLoc(VD, Idx), UndefinedVal());
        }
      }
    } else if (T->isStructureType()) {
      // FIXME: Implement struct initialization.
    }
  }
  return store;
}

<commit_msg>Add a bunch of getLValue* methods to RegionStore.<commit_after>//== RegionStore.cpp - Field-sensitive store model --------------*- C++ -*--==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a basic region store model. In this model, we do have field
// sensitivity. But we assume nothing about the heap shape. So recursive data
// structures are largely ignored. Basically we do 1-limiting analysis.
// Parameter pointers are assumed with no aliasing. Pointee objects of
// parameters are created lazily.
//
//===----------------------------------------------------------------------===//
#include "clang/Analysis/PathSensitive/MemRegion.h"
#include "clang/Analysis/PathSensitive/GRState.h"
#include "clang/Analysis/Analyses/LiveVariables.h"

#include "llvm/ADT/ImmutableMap.h"
#include "llvm/Support/Compiler.h"

using namespace clang;

typedef llvm::ImmutableMap<const MemRegion*, SVal> RegionBindingsTy;

namespace {

class VISIBILITY_HIDDEN RegionStoreManager : public StoreManager {
  RegionBindingsTy::Factory RBFactory;
  GRStateManager& StateMgr;
  MemRegionManager MRMgr;

public:
  RegionStoreManager(GRStateManager& mgr)
    : StateMgr(mgr), MRMgr(StateMgr.getAllocator()) {}

  virtual ~RegionStoreManager() {}

  SVal getLValueVar(const GRState* St, const VarDecl* VD);

  SVal getLValueIvar(const GRState* St, const ObjCIvarDecl* D, SVal Base);

  SVal getLValueField(const GRState* St, SVal Base, const FieldDecl* D);

  SVal Retrieve(Store S, Loc L, QualType T);

  Store Bind(Store St, Loc LV, SVal V);

  Store getInitialStore();

  Store AddDecl(Store store, const VarDecl* VD, Expr* Ex, SVal InitVal,
                unsigned Count);

  Loc getVarLoc(const VarDecl* VD) {
    return loc::MemRegionVal(MRMgr.getVarRegion(VD));
  }

  Loc getElementLoc(const VarDecl* VD, SVal Idx);

  static inline RegionBindingsTy GetRegionBindings(Store store) {
   return RegionBindingsTy(static_cast<const RegionBindingsTy::TreeTy*>(store));
  }
};

} // end anonymous namespace

Loc RegionStoreManager::getElementLoc(const VarDecl* VD, SVal Idx) {
  MemRegion* R = MRMgr.getVarRegion(VD);
  ElementRegion* ER = MRMgr.getElementRegion(Idx, R);
  return loc::MemRegionVal(ER);
}

SVal RegionStoreManager::getLValueVar(const GRState* St, const VarDecl* VD) {
  return loc::MemRegionVal(MRMgr.getVarRegion(VD));
}

SVal RegionStoreManager::getLValueIvar(const GRState* St, const ObjCIvarDecl* D,
                                       SVal Base) {
  return UnknownVal();
}

SVal RegionStoreManager::getLValueField(const GRState* St, SVal Base,
                                        const FieldDecl* D) {
  if (Base.isUnknownOrUndef())
    return Base;

  Loc BaseL = cast<Loc>(Base);
  const MemRegion* BaseR = 0;

  switch (BaseL.getSubKind()) {
  case loc::MemRegionKind:
    BaseR = cast<loc::MemRegionVal>(BaseL).getRegion();
    break;

  case loc::SymbolValKind:
    BaseR = MRMgr.getSymbolicRegion(cast<loc::SymbolVal>(&BaseL)->getSymbol());
    break;

  case loc::GotoLabelKind:
  case loc::FuncValKind:
    // These are anormal cases. Flag an undefined value.
    return UndefinedVal();

  case loc::ConcreteIntKind:
  case loc::StringLiteralValKind:
    // While these seem funny, this can happen through casts.
    // FIXME: What we should return is the field offset.  For example,
    //  add the field offset to the integer value.  That way funny things
    //  like this work properly:  &(((struct foo *) 0xa)->f)
    return Base;

  default:
    assert("Unhandled Base.");
    return Base;
  }

  return loc::MemRegionVal(MRMgr.getFieldRegion(D, BaseR));
}

SVal RegionStoreManager::Retrieve(Store S, Loc L, QualType T) {
  assert(!isa<UnknownVal>(L) && "location unknown");
  assert(!isa<UndefinedVal>(L) && "location undefined");

  switch (L.getSubKind()) {
  case loc::MemRegionKind: {
    const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion();
    assert(R && "bad region");

    RegionBindingsTy B(static_cast<const RegionBindingsTy::TreeTy*>(S));
    RegionBindingsTy::data_type* V = B.lookup(R);
    return V ? *V : UnknownVal();
  }

  case loc::SymbolValKind:
    return UnknownVal();

  case loc::ConcreteIntKind:
    return UndefinedVal(); // As in BasicStoreManager.

  case loc::FuncValKind:
    return L;

  case loc::StringLiteralValKind:
    return UnknownVal();

  default:
    assert(false && "Invalid Location");
    break;
  }
}

Store RegionStoreManager::Bind(Store store, Loc LV, SVal V) {
  assert(LV.getSubKind() == loc::MemRegionKind);

  const MemRegion* R = cast<loc::MemRegionVal>(LV).getRegion();

  if (!R)
    return store;

  RegionBindingsTy B = GetRegionBindings(store);
  return V.isUnknown()
         ? RBFactory.Remove(B, R).getRoot()
         : RBFactory.Add(B, R, V).getRoot();
}

Store RegionStoreManager::getInitialStore() {
  typedef LiveVariables::AnalysisDataTy LVDataTy;
  LVDataTy& D = StateMgr.getLiveVariables().getAnalysisData();

  Store St = RBFactory.GetEmptyMap().getRoot();

  for (LVDataTy::decl_iterator I=D.begin_decl(), E=D.end_decl(); I != E; ++I) {
    NamedDecl* ND = const_cast<NamedDecl*>(I->first);

    if (VarDecl* VD = dyn_cast<VarDecl>(ND)) {
      // Punt on static variables for now.
      if (VD->getStorageClass() == VarDecl::Static)
        continue;

      QualType T = VD->getType();
      // Only handle pointers and integers for now.
      if (Loc::IsLocType(T) || T->isIntegerType()) {
        // Initialize globals and parameters to symbolic values.
        // Initialize local variables to undefined.
        SVal X = (VD->hasGlobalStorage() || isa<ParmVarDecl>(VD) ||
                  isa<ImplicitParamDecl>(VD))
                 ? SVal::GetSymbolValue(StateMgr.getSymbolManager(), VD)
                 : UndefinedVal();

        St = Bind(St, getVarLoc(VD), X);
      }
    }
  }
  return St;
}

Store RegionStoreManager::AddDecl(Store store,
                                  const VarDecl* VD, Expr* Ex,
                                  SVal InitVal, unsigned Count) {
  BasicValueFactory& BasicVals = StateMgr.getBasicVals();
  SymbolManager& SymMgr = StateMgr.getSymbolManager();

  if (VD->hasGlobalStorage()) {
    // Static global variables should not be visited here.
    assert(!(VD->getStorageClass() == VarDecl::Static &&
             VD->isFileVarDecl()));
    // Process static variables.
    if (VD->getStorageClass() == VarDecl::Static) {
      if (!Ex) {
        // Only handle pointer and integer static variables.

        QualType T = VD->getType();

        if (Loc::IsLocType(T))
          store = Bind(store, getVarLoc(VD),
                       loc::ConcreteInt(BasicVals.getValue(0, T)));

        else if (T->isIntegerType())
          store = Bind(store, getVarLoc(VD),
                       loc::ConcreteInt(BasicVals.getValue(0, T)));
        else
          assert("ignore other types of variables");
      } else {
        store = Bind(store, getVarLoc(VD), InitVal);
      }
    }
  } else {
    // Process local variables.

    QualType T = VD->getType();

    if (Loc::IsLocType(T) || T->isIntegerType()) {
      SVal V = Ex ? InitVal : UndefinedVal();
      if (Ex && InitVal.isUnknown()) {
        // "Conjured" symbols.
        SymbolID Sym = SymMgr.getConjuredSymbol(Ex, Count);
        V = Loc::IsLocType(Ex->getType())
          ? cast<SVal>(loc::SymbolVal(Sym))
          : cast<SVal>(nonloc::SymbolVal(Sym));
      }
      store = Bind(store, getVarLoc(VD), V);

    } else if (T->isArrayType()) {
      // Only handle constant size array.
      if (ConstantArrayType* CAT=dyn_cast<ConstantArrayType>(T.getTypePtr())) {

        llvm::APInt Size = CAT->getSize();

        for (llvm::APInt i = llvm::APInt::getNullValue(Size.getBitWidth());
             i != Size; ++i) {
          nonloc::ConcreteInt Idx(BasicVals.getValue(llvm::APSInt(i)));
          store = Bind(store, getElementLoc(VD, Idx), UndefinedVal());
        }
      }
    } else if (T->isStructureType()) {
      // FIXME: Implement struct initialization.
    }
  }
  return store;
}

<|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file KeyMap.cxx
 ** Defines a mapping between keystrokes and commands.
 **/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include "Platform.h"

#include "Scintilla.h"

#include "KeyMap.h"

KeyMap::KeyMap() : kmap(0), len(0), alloc(0) {
	for (int i = 0; MapDefault[i].key; i++) {
		AssignCmdKey(MapDefault[i].key,
			MapDefault[i].modifiers,
             		MapDefault[i].msg);
	}
}

KeyMap::~KeyMap() {
	Clear();
}

void KeyMap::Clear() {
	delete []kmap;
	kmap = 0;
	len = 0;
	alloc = 0;
}

void KeyMap::AssignCmdKey(int key, int modifiers, unsigned int msg) {
	if ((len+1) >= alloc) {
		KeyToCommand *ktcNew = new KeyToCommand[alloc + 5];
		if (!ktcNew)
			return;
		for (int k=0;k<len;k++)
			ktcNew[k] = kmap[k];
		alloc += 5;
		delete []kmap;
		kmap = ktcNew;
	}
	for (int keyIndex = 0; keyIndex < len; keyIndex++) {
		if ((key == kmap[keyIndex].key) && (modifiers == kmap[keyIndex].modifiers)) {
			kmap[keyIndex].msg = msg;
			return;
		}
	}
	kmap[len].key = key;
	kmap[len].modifiers = modifiers;
	kmap[len].msg = msg;
	len++;
}

unsigned int KeyMap::Find(int key, int modifiers) {
	for (int i=0; i < len; i++) {
		if ((key == kmap[i].key) && (modifiers == kmap[i].modifiers)) {
			return kmap[i].msg;
		}
	}
	return 0;
}

const KeyToCommand KeyMap::MapDefault[] = {
    {SCK_DOWN,		SCI_NORM,	SCI_LINEDOWN},
    {SCK_DOWN,		SCI_SHIFT,	SCI_LINEDOWNEXTEND},
    {SCK_DOWN,		SCI_CTRL,	SCI_LINESCROLLDOWN},
    {SCK_UP,			SCI_NORM,	SCI_LINEUP},
    {SCK_UP,			SCI_SHIFT,	SCI_LINEUPEXTEND},
    {SCK_UP,			SCI_CTRL,	SCI_LINESCROLLUP},
    {SCK_LEFT,		SCI_NORM,	SCI_CHARLEFT},
    {SCK_LEFT,		SCI_SHIFT,	SCI_CHARLEFTEXTEND},
    {SCK_LEFT,		SCI_CTRL,	SCI_WORDLEFT},
    {SCK_LEFT,		SCI_CSHIFT,	SCI_WORDLEFTEXTEND},
    {SCK_LEFT,		SCI_ALT,		SCI_WORDPARTLEFT},
    {SCK_LEFT,		SCI_ASHIFT,	SCI_WORDPARTLEFTEXTEND},
    {SCK_RIGHT,		SCI_NORM,	SCI_CHARRIGHT},
    {SCK_RIGHT,		SCI_SHIFT,	SCI_CHARRIGHTEXTEND},
    {SCK_RIGHT,		SCI_CTRL,	SCI_WORDRIGHT},
    {SCK_RIGHT,		SCI_CSHIFT,	SCI_WORDRIGHTEXTEND},
    {SCK_RIGHT,		SCI_ALT,		SCI_WORDPARTRIGHT},
    {SCK_RIGHT,		SCI_ASHIFT,	SCI_WORDPARTRIGHTEXTEND},
    {SCK_HOME, 		SCI_NORM, 	SCI_VCHOME},
    {SCK_HOME, 		SCI_SHIFT, 	SCI_VCHOMEEXTEND},
    {SCK_HOME, 		SCI_CTRL, 	SCI_DOCUMENTSTART},
    {SCK_HOME, 		SCI_CSHIFT, 	SCI_DOCUMENTSTARTEXTEND},
    {SCK_END,	 	SCI_NORM, 	SCI_LINEEND},
    {SCK_END,	 	SCI_SHIFT, 	SCI_LINEENDEXTEND},
    {SCK_END, 		SCI_CTRL, 	SCI_DOCUMENTEND},
    {SCK_END, 		SCI_CSHIFT, 	SCI_DOCUMENTENDEXTEND},
    {SCK_PRIOR,		SCI_NORM, 	SCI_PAGEUP},
    {SCK_PRIOR,		SCI_SHIFT, 	SCI_PAGEUPEXTEND},
    {SCK_NEXT, 		SCI_NORM, 	SCI_PAGEDOWN},
    {SCK_NEXT, 		SCI_SHIFT, 	SCI_PAGEDOWNEXTEND},
    {SCK_DELETE, 	SCI_NORM,	SCI_CLEAR},
    {SCK_DELETE, 	SCI_SHIFT,	SCI_CUT},
    {SCK_DELETE, 	SCI_CTRL,	SCI_DELWORDRIGHT},
    {SCK_DELETE,	SCI_CSHIFT,	SCI_DELLINERIGHT},
    {SCK_INSERT, 		SCI_NORM,	SCI_EDITTOGGLEOVERTYPE},
    {SCK_INSERT, 		SCI_SHIFT,	SCI_PASTE},
    {SCK_INSERT, 		SCI_CTRL,	SCI_COPY},
    {SCK_ESCAPE,  	SCI_NORM,	SCI_CANCEL},
    {SCK_BACK,		SCI_NORM, 	SCI_DELETEBACK},
    {SCK_BACK,		SCI_SHIFT, 	SCI_DELETEBACK},
    {SCK_BACK,		SCI_CTRL, 	SCI_DELWORDLEFT},
    {SCK_BACK, 		SCI_ALT,	SCI_UNDO},
    {SCK_BACK,		SCI_CSHIFT,	SCI_DELLINELEFT},
    {'Z', 			SCI_CTRL,	SCI_UNDO},
    {'Y', 			SCI_CTRL,	SCI_REDO},
    {'X', 			SCI_CTRL,	SCI_CUT},
    {'C', 			SCI_CTRL,	SCI_COPY},
    {'V', 			SCI_CTRL,	SCI_PASTE},
    {'A', 			SCI_CTRL,	SCI_SELECTALL},
    {SCK_TAB,		SCI_NORM,	SCI_TAB},
    {SCK_TAB,		SCI_SHIFT,	SCI_BACKTAB},
    {SCK_RETURN, 	SCI_NORM,	SCI_NEWLINE},
    {SCK_ADD, 		SCI_CTRL,	SCI_ZOOMIN},
    {SCK_SUBTRACT,	SCI_CTRL,	SCI_ZOOMOUT},
    {SCK_DIVIDE,	SCI_CTRL,	SCI_SETZOOM},
    //'L', 			SCI_CTRL,		SCI_FORMFEED,
    {'L', 			SCI_CTRL,	SCI_LINECUT},
    {'L', 			SCI_CSHIFT,	SCI_LINEDELETE},
    {'T', 			SCI_CTRL,	SCI_LINETRANSPOSE},
    {'U', 			SCI_CTRL,	SCI_LOWERCASE},
    {'U', 			SCI_CSHIFT,	SCI_UPPERCASE},
    {0,0,0},
};

<commit_msg>Made Shift+Enter be the same as Enter.<commit_after>// Scintilla source code edit control
/** @file KeyMap.cxx
 ** Defines a mapping between keystrokes and commands.
 **/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include "Platform.h"

#include "Scintilla.h"

#include "KeyMap.h"

KeyMap::KeyMap() : kmap(0), len(0), alloc(0) {
	for (int i = 0; MapDefault[i].key; i++) {
		AssignCmdKey(MapDefault[i].key,
			MapDefault[i].modifiers,
             		MapDefault[i].msg);
	}
}

KeyMap::~KeyMap() {
	Clear();
}

void KeyMap::Clear() {
	delete []kmap;
	kmap = 0;
	len = 0;
	alloc = 0;
}

void KeyMap::AssignCmdKey(int key, int modifiers, unsigned int msg) {
	if ((len+1) >= alloc) {
		KeyToCommand *ktcNew = new KeyToCommand[alloc + 5];
		if (!ktcNew)
			return;
		for (int k=0;k<len;k++)
			ktcNew[k] = kmap[k];
		alloc += 5;
		delete []kmap;
		kmap = ktcNew;
	}
	for (int keyIndex = 0; keyIndex < len; keyIndex++) {
		if ((key == kmap[keyIndex].key) && (modifiers == kmap[keyIndex].modifiers)) {
			kmap[keyIndex].msg = msg;
			return;
		}
	}
	kmap[len].key = key;
	kmap[len].modifiers = modifiers;
	kmap[len].msg = msg;
	len++;
}

unsigned int KeyMap::Find(int key, int modifiers) {
	for (int i=0; i < len; i++) {
		if ((key == kmap[i].key) && (modifiers == kmap[i].modifiers)) {
			return kmap[i].msg;
		}
	}
	return 0;
}

const KeyToCommand KeyMap::MapDefault[] = {
    {SCK_DOWN,		SCI_NORM,	SCI_LINEDOWN},
    {SCK_DOWN,		SCI_SHIFT,	SCI_LINEDOWNEXTEND},
    {SCK_DOWN,		SCI_CTRL,	SCI_LINESCROLLDOWN},
    {SCK_UP,			SCI_NORM,	SCI_LINEUP},
    {SCK_UP,			SCI_SHIFT,	SCI_LINEUPEXTEND},
    {SCK_UP,			SCI_CTRL,	SCI_LINESCROLLUP},
    {SCK_LEFT,		SCI_NORM,	SCI_CHARLEFT},
    {SCK_LEFT,		SCI_SHIFT,	SCI_CHARLEFTEXTEND},
    {SCK_LEFT,		SCI_CTRL,	SCI_WORDLEFT},
    {SCK_LEFT,		SCI_CSHIFT,	SCI_WORDLEFTEXTEND},
    {SCK_LEFT,		SCI_ALT,		SCI_WORDPARTLEFT},
    {SCK_LEFT,		SCI_ASHIFT,	SCI_WORDPARTLEFTEXTEND},
    {SCK_RIGHT,		SCI_NORM,	SCI_CHARRIGHT},
    {SCK_RIGHT,		SCI_SHIFT,	SCI_CHARRIGHTEXTEND},
    {SCK_RIGHT,		SCI_CTRL,	SCI_WORDRIGHT},
    {SCK_RIGHT,		SCI_CSHIFT,	SCI_WORDRIGHTEXTEND},
    {SCK_RIGHT,		SCI_ALT,		SCI_WORDPARTRIGHT},
    {SCK_RIGHT,		SCI_ASHIFT,	SCI_WORDPARTRIGHTEXTEND},
    {SCK_HOME, 		SCI_NORM, 	SCI_VCHOME},
    {SCK_HOME, 		SCI_SHIFT, 	SCI_VCHOMEEXTEND},
    {SCK_HOME, 		SCI_CTRL, 	SCI_DOCUMENTSTART},
    {SCK_HOME, 		SCI_CSHIFT, 	SCI_DOCUMENTSTARTEXTEND},
    {SCK_END,	 	SCI_NORM, 	SCI_LINEEND},
    {SCK_END,	 	SCI_SHIFT, 	SCI_LINEENDEXTEND},
    {SCK_END, 		SCI_CTRL, 	SCI_DOCUMENTEND},
    {SCK_END, 		SCI_CSHIFT, 	SCI_DOCUMENTENDEXTEND},
    {SCK_PRIOR,		SCI_NORM, 	SCI_PAGEUP},
    {SCK_PRIOR,		SCI_SHIFT, 	SCI_PAGEUPEXTEND},
    {SCK_NEXT, 		SCI_NORM, 	SCI_PAGEDOWN},
    {SCK_NEXT, 		SCI_SHIFT, 	SCI_PAGEDOWNEXTEND},
    {SCK_DELETE, 	SCI_NORM,	SCI_CLEAR},
    {SCK_DELETE, 	SCI_SHIFT,	SCI_CUT},
    {SCK_DELETE, 	SCI_CTRL,	SCI_DELWORDRIGHT},
    {SCK_DELETE,	SCI_CSHIFT,	SCI_DELLINERIGHT},
    {SCK_INSERT, 		SCI_NORM,	SCI_EDITTOGGLEOVERTYPE},
    {SCK_INSERT, 		SCI_SHIFT,	SCI_PASTE},
    {SCK_INSERT, 		SCI_CTRL,	SCI_COPY},
    {SCK_ESCAPE,  	SCI_NORM,	SCI_CANCEL},
    {SCK_BACK,		SCI_NORM, 	SCI_DELETEBACK},
    {SCK_BACK,		SCI_SHIFT, 	SCI_DELETEBACK},
    {SCK_BACK,		SCI_CTRL, 	SCI_DELWORDLEFT},
    {SCK_BACK, 		SCI_ALT,	SCI_UNDO},
    {SCK_BACK,		SCI_CSHIFT,	SCI_DELLINELEFT},
    {'Z', 			SCI_CTRL,	SCI_UNDO},
    {'Y', 			SCI_CTRL,	SCI_REDO},
    {'X', 			SCI_CTRL,	SCI_CUT},
    {'C', 			SCI_CTRL,	SCI_COPY},
    {'V', 			SCI_CTRL,	SCI_PASTE},
    {'A', 			SCI_CTRL,	SCI_SELECTALL},
    {SCK_TAB,		SCI_NORM,	SCI_TAB},
    {SCK_TAB,		SCI_SHIFT,	SCI_BACKTAB},
    {SCK_RETURN, 	SCI_NORM,	SCI_NEWLINE},
    {SCK_RETURN, 	SCI_SHIFT,	SCI_NEWLINE},
    {SCK_ADD, 		SCI_CTRL,	SCI_ZOOMIN},
    {SCK_SUBTRACT,	SCI_CTRL,	SCI_ZOOMOUT},
    {SCK_DIVIDE,	SCI_CTRL,	SCI_SETZOOM},
    //'L', 			SCI_CTRL,		SCI_FORMFEED,
    {'L', 			SCI_CTRL,	SCI_LINECUT},
    {'L', 			SCI_CSHIFT,	SCI_LINEDELETE},
    {'T', 			SCI_CTRL,	SCI_LINETRANSPOSE},
    {'U', 			SCI_CTRL,	SCI_LOWERCASE},
    {'U', 			SCI_CSHIFT,	SCI_UPPERCASE},
    {0,0,0},
};

<|endoftext|>


<commit_before>//===-- MachineInstr.cpp --------------------------------------------------===//
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Value.h"
using std::cerr;

// Constructor for instructions with fixed #operands (nearly all)
MachineInstr::MachineInstr(MachineOpCode _opCode,
			   OpCodeMask    _opCodeMask)
  : opCode(_opCode),
    opCodeMask(_opCodeMask),
    operands(TargetInstrDescriptors[_opCode].numOperands)
{
  assert(TargetInstrDescriptors[_opCode].numOperands >= 0);
}

// Constructor for instructions with variable #operands
MachineInstr::MachineInstr(MachineOpCode _opCode,
			   unsigned	 numOperands,
			   OpCodeMask    _opCodeMask)
  : opCode(_opCode),
    opCodeMask(_opCodeMask),
    operands(numOperands)
{
}

void
MachineInstr::SetMachineOperandVal(unsigned int i,
                                   MachineOperand::MachineOperandType opType,
                                   Value* _val,
                                   bool isdef,
                                   bool isDefAndUse)
{
  assert(i < operands.size());
  operands[i].Initialize(opType, _val);
  if (isdef || TargetInstrDescriptors[opCode].resultPos == (int) i)
    operands[i].markDef();
  if (isDefAndUse)
    operands[i].markDefAndUse();
}

void
MachineInstr::SetMachineOperandConst(unsigned int i,
				MachineOperand::MachineOperandType operandType,
                                     int64_t intValue)
{
  assert(i < operands.size());
  assert(TargetInstrDescriptors[opCode].resultPos != (int) i &&
         "immed. constant cannot be defined");
  operands[i].InitializeConst(operandType, intValue);
}

void
MachineInstr::SetMachineOperandReg(unsigned int i,
                                   int regNum,
                                   bool isdef,
                                   bool isDefAndUse,
                                   bool isCCReg)
{
  assert(i < operands.size());
  operands[i].InitializeReg(regNum, isCCReg);
  if (isdef || TargetInstrDescriptors[opCode].resultPos == (int) i)
    operands[i].markDef();
  if (isDefAndUse)
    operands[i].markDefAndUse();
  regsUsed.insert(regNum);
}

void
MachineInstr::SetRegForOperand(unsigned i, int regNum)
{
  operands[i].setRegForValue(regNum);
  regsUsed.insert(regNum);
}

// Subsitute all occurrences of Value* oldVal with newVal in all operands
// and all implicit refs.  If defsOnly == true, substitute defs only.
unsigned
MachineInstr::substituteValue(const Value* oldVal, Value* newVal, bool defsOnly)
{
  unsigned numSubst = 0;

  // Subsitute operands
  for (MachineInstr::val_op_iterator O = begin(), E = end(); O != E; ++O)
    if (*O == oldVal)
      if (!defsOnly || O.isDef())
        {
          O.getMachineOperand().value = newVal;
          ++numSubst;
        }

  // Subsitute implicit refs
  for (unsigned i=0, N=implicitRefs.size(); i < N; ++i)
    if (implicitRefs[i] == oldVal)
      if (!defsOnly || implicitRefIsDefined(i))
        {
          implicitRefs[i] = newVal;
          ++numSubst;
        }

  return numSubst;
}

void
MachineInstr::dump() const
{
  cerr << "  " << *this;
}

static inline std::ostream &OutputValue(std::ostream &os,
                                        const Value* val)
{
  os << "(val ";
  if (val && val->hasName())
    return os << val->getName() << ")";
  else
    return os << (void*) val << ")";              // print address only
}

std::ostream &operator<<(std::ostream& os, const MachineInstr& minstr)
{
  os << TargetInstrDescriptors[minstr.opCode].opCodeString;

  for (unsigned i=0, N=minstr.getNumOperands(); i < N; i++) {
    os << "\t" << minstr.getOperand(i);
    if( minstr.operandIsDefined(i) )
      os << "*";
    if( minstr.operandIsDefinedAndUsed(i) )
      os << "*";
  }

  // code for printing implict references
  unsigned NumOfImpRefs =  minstr.getNumImplicitRefs();
  if(  NumOfImpRefs > 0 ) {
    os << "\tImplicit: ";
    for(unsigned z=0; z < NumOfImpRefs; z++) {
      OutputValue(os, minstr.getImplicitRef(z));
      if( minstr.implicitRefIsDefined(z)) os << "*";
      if( minstr.implicitRefIsDefinedAndUsed(z)) os << "*";
      os << "\t";
    }
  }

  return os << "\n";
}

std::ostream &operator<<(std::ostream &os, const MachineOperand &mop)
{
  if (mop.opHiBits32())
    os << "%lm(";
  else if (mop.opLoBits32())
    os << "%lo(";
  else if (mop.opHiBits64())
    os << "%hh(";
  else if (mop.opLoBits64())
    os << "%hm(";

  switch(mop.opType)
    {
    case MachineOperand::MO_VirtualRegister:
      os << "%reg";
      OutputValue(os, mop.getVRegValue());
      break;
    case MachineOperand::MO_CCRegister:
      os << "%ccreg";
      OutputValue(os, mop.getVRegValue());
      break;
    case MachineOperand::MO_MachineRegister:
      os << "%reg";
      os << "(" << mop.getMachineRegNum() << ")";
      break;
    case MachineOperand::MO_SignExtendedImmed:
      os << (long)mop.immedVal;
      break;
    case MachineOperand::MO_UnextendedImmed:
      os << (long)mop.immedVal;
      break;
    case MachineOperand::MO_PCRelativeDisp:
      {
        const Value* opVal = mop.getVRegValue();
        bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
        os << "%disp(" << (isLabel? "label " : "addr-of-val ");
        if (opVal->hasName())
          os << opVal->getName();
        else
          os << (const void*) opVal;
        os << ")";
        break;
      }
    default:
      assert(0 && "Unrecognized operand type");
      break;
    }

  if (mop.flags &
      (MachineOperand::HIFLAG32 | MachineOperand::LOFLAG32 |
       MachineOperand::HIFLAG64 | MachineOperand::LOFLAG64))
    os << ")";

  return os;
}
<commit_msg>Dump routine now writes out allocated register numbers if available.<commit_after>//===-- MachineInstr.cpp --------------------------------------------------===//
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Value.h"
using std::cerr;

// Constructor for instructions with fixed #operands (nearly all)
MachineInstr::MachineInstr(MachineOpCode _opCode,
			   OpCodeMask    _opCodeMask)
  : opCode(_opCode),
    opCodeMask(_opCodeMask),
    operands(TargetInstrDescriptors[_opCode].numOperands)
{
  assert(TargetInstrDescriptors[_opCode].numOperands >= 0);
}

// Constructor for instructions with variable #operands
MachineInstr::MachineInstr(MachineOpCode _opCode,
			   unsigned	 numOperands,
			   OpCodeMask    _opCodeMask)
  : opCode(_opCode),
    opCodeMask(_opCodeMask),
    operands(numOperands)
{
}

void
MachineInstr::SetMachineOperandVal(unsigned int i,
                                   MachineOperand::MachineOperandType opType,
                                   Value* _val,
                                   bool isdef,
                                   bool isDefAndUse)
{
  assert(i < operands.size());
  operands[i].Initialize(opType, _val);
  if (isdef || TargetInstrDescriptors[opCode].resultPos == (int) i)
    operands[i].markDef();
  if (isDefAndUse)
    operands[i].markDefAndUse();
}

void
MachineInstr::SetMachineOperandConst(unsigned int i,
				MachineOperand::MachineOperandType operandType,
                                     int64_t intValue)
{
  assert(i < operands.size());
  assert(TargetInstrDescriptors[opCode].resultPos != (int) i &&
         "immed. constant cannot be defined");
  operands[i].InitializeConst(operandType, intValue);
}

void
MachineInstr::SetMachineOperandReg(unsigned int i,
                                   int regNum,
                                   bool isdef,
                                   bool isDefAndUse,
                                   bool isCCReg)
{
  assert(i < operands.size());
  operands[i].InitializeReg(regNum, isCCReg);
  if (isdef || TargetInstrDescriptors[opCode].resultPos == (int) i)
    operands[i].markDef();
  if (isDefAndUse)
    operands[i].markDefAndUse();
  regsUsed.insert(regNum);
}

void
MachineInstr::SetRegForOperand(unsigned i, int regNum)
{
  operands[i].setRegForValue(regNum);
  regsUsed.insert(regNum);
}

// Subsitute all occurrences of Value* oldVal with newVal in all operands
// and all implicit refs.  If defsOnly == true, substitute defs only.
unsigned
MachineInstr::substituteValue(const Value* oldVal, Value* newVal, bool defsOnly)
{
  unsigned numSubst = 0;

  // Subsitute operands
  for (MachineInstr::val_op_iterator O = begin(), E = end(); O != E; ++O)
    if (*O == oldVal)
      if (!defsOnly || O.isDef())
        {
          O.getMachineOperand().value = newVal;
          ++numSubst;
        }

  // Subsitute implicit refs
  for (unsigned i=0, N=implicitRefs.size(); i < N; ++i)
    if (implicitRefs[i] == oldVal)
      if (!defsOnly || implicitRefIsDefined(i))
        {
          implicitRefs[i] = newVal;
          ++numSubst;
        }

  return numSubst;
}

void
MachineInstr::dump() const
{
  cerr << "  " << *this;
}

static inline std::ostream&
OutputValue(std::ostream &os, const Value* val)
{
  os << "(val ";
  if (val && val->hasName())
    return os << val->getName() << ")";
  else
    return os << (void*) val << ")";              // print address only
}

static inline std::ostream&
OutputReg(std::ostream &os, unsigned int regNum)
{
  return os << "%mreg(" << regNum << ")";
}

std::ostream &operator<<(std::ostream& os, const MachineInstr& minstr)
{
  os << TargetInstrDescriptors[minstr.opCode].opCodeString;

  for (unsigned i=0, N=minstr.getNumOperands(); i < N; i++) {
    os << "\t" << minstr.getOperand(i);
    if( minstr.operandIsDefined(i) )
      os << "*";
    if( minstr.operandIsDefinedAndUsed(i) )
      os << "*";
  }

  // code for printing implict references
  unsigned NumOfImpRefs =  minstr.getNumImplicitRefs();
  if(  NumOfImpRefs > 0 ) {
    os << "\tImplicit: ";
    for(unsigned z=0; z < NumOfImpRefs; z++) {
      OutputValue(os, minstr.getImplicitRef(z));
      if( minstr.implicitRefIsDefined(z)) os << "*";
      if( minstr.implicitRefIsDefinedAndUsed(z)) os << "*";
      os << "\t";
    }
  }

  return os << "\n";
}

std::ostream &operator<<(std::ostream &os, const MachineOperand &mop)
{
  if (mop.opHiBits32())
    os << "%lm(";
  else if (mop.opLoBits32())
    os << "%lo(";
  else if (mop.opHiBits64())
    os << "%hh(";
  else if (mop.opLoBits64())
    os << "%hm(";

  switch(mop.opType)
    {
    case MachineOperand::MO_VirtualRegister:
      os << "%reg";
      OutputValue(os, mop.getVRegValue());
      if (mop.hasAllocatedReg())
        os << "==" << OutputReg(os, mop.getAllocatedRegNum());
      break;
    case MachineOperand::MO_CCRegister:
      os << "%ccreg";
      OutputValue(os, mop.getVRegValue());
      if (mop.hasAllocatedReg())
        os << "==" << OutputReg(os, mop.getAllocatedRegNum());
      break;
    case MachineOperand::MO_MachineRegister:
      OutputReg(os, mop.getMachineRegNum());
      break;
    case MachineOperand::MO_SignExtendedImmed:
      os << (long)mop.immedVal;
      break;
    case MachineOperand::MO_UnextendedImmed:
      os << (long)mop.immedVal;
      break;
    case MachineOperand::MO_PCRelativeDisp:
      {
        const Value* opVal = mop.getVRegValue();
        bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
        os << "%disp(" << (isLabel? "label " : "addr-of-val ");
        if (opVal->hasName())
          os << opVal->getName();
        else
          os << (const void*) opVal;
        os << ")";
        break;
      }
    default:
      assert(0 && "Unrecognized operand type");
      break;
    }

  if (mop.flags &
      (MachineOperand::HIFLAG32 | MachineOperand::LOFLAG32 |
       MachineOperand::HIFLAG64 | MachineOperand::LOFLAG64))
    os << ")";

  return os;
}
<|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file LexCPP.cxx
 ** Lexer for C++, C, Java, and Javascript.
 **/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

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

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

static bool classifyWordCpp(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {
	char s[100];
	for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) {
		s[i] = styler[start + i];
		s[i + 1] = '\0';
	}
	bool wordIsUUID = false;
	char chAttr = SCE_C_IDENTIFIER;
	if (isdigit(s[0]) || (s[0] == '.'))
		chAttr = SCE_C_NUMBER;
	else {
		if (keywords.InList(s)) {
			chAttr = SCE_C_WORD;
			wordIsUUID = strcmp(s, "uuid") == 0;
		}
	}
	styler.ColourTo(end, chAttr);
	return wordIsUUID;
}

static bool isOKBeforeRE(char ch) {
	return (ch == '(') || (ch == '=') || (ch == ',');
}

static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
	Accessor &styler) {

	WordList &keywords = *keywordlists[0];

	styler.StartAt(startPos);

	bool fold = styler.GetPropertyInt("fold");
	bool foldComment = styler.GetPropertyInt("fold.comment");
	bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor");
	int lineCurrent = styler.GetLine(startPos);
	int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
	int levelCurrent = levelPrev;

	int state = initStyle;
	if (state == SCE_C_STRINGEOL)	// Does not leak onto next line
		state = SCE_C_DEFAULT;
	char chPrev = ' ';
	char chNext = styler[startPos];
	char chPrevNonWhite = ' ';
	unsigned int lengthDoc = startPos + length;
	int visibleChars = 0;
	styler.StartSegment(startPos);
	bool lastWordWasUUID = false;
	for (unsigned int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);

		if ((ch == '\r' && chNext != '\n') || (ch == '\n')) {
			// Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix)
			// Avoid triggering two times on Dos/Win
			// End of line
			if (state == SCE_C_STRINGEOL) {
				styler.ColourTo(i, state);
				state = SCE_C_DEFAULT;
			}
			if (fold) {
				int lev = levelPrev;
				if (visibleChars == 0)
					lev |= SC_FOLDLEVELWHITEFLAG;
				if ((levelCurrent > levelPrev) && (visibleChars > 0))
					lev |= SC_FOLDLEVELHEADERFLAG;
				styler.SetLevel(lineCurrent, lev);
				lineCurrent++;
				levelPrev = levelCurrent;
			}
			visibleChars = 0;
		}
		if (!isspacechar(ch))
			visibleChars++;

		if (styler.IsLeadByte(ch)) {
			chNext = styler.SafeGetCharAt(i + 2);
			chPrev = ' ';
			i += 1;
			continue;
		}

		if (state == SCE_C_DEFAULT) {
			if (ch == '@' && chNext == '\"') {
				styler.ColourTo(i-1, state);
				state = SCE_C_VERBATIM;
				i++;
				ch = chNext;
				chNext = styler.SafeGetCharAt(i + 1);
			} else if (iswordstart(ch) || (ch == '@')) {
				styler.ColourTo(i-1, state);
				if (lastWordWasUUID) {
					state = SCE_C_UUID;
					lastWordWasUUID = false;
				} else {
					state = SCE_C_IDENTIFIER;
				}
			} else if (ch == '/' && chNext == '*') {
				styler.ColourTo(i-1, state);
				if (foldComment)
					levelCurrent++;
				if (styler.SafeGetCharAt(i + 2) == '*' ||
					styler.SafeGetCharAt(i + 2) == '!')	// Support of Qt/Doxygen doc. style
					state = SCE_C_COMMENTDOC;
				else
					state = SCE_C_COMMENT;
			} else if (ch == '/' && chNext == '/') {
				styler.ColourTo(i-1, state);
				if (styler.SafeGetCharAt(i + 2) == '/' ||
					styler.SafeGetCharAt(i + 2) == '!')	// Support of Qt/Doxygen doc. style
					state = SCE_C_COMMENTLINEDOC;
				else
				state = SCE_C_COMMENTLINE;
			} else if (ch == '/' && isOKBeforeRE(chPrevNonWhite)) {
				styler.ColourTo(i-1, state);
				state = SCE_C_REGEX;
			} else if (ch == '\"') {
				styler.ColourTo(i-1, state);
				state = SCE_C_STRING;
			} else if (ch == '\'') {
				styler.ColourTo(i-1, state);
				state = SCE_C_CHARACTER;
			} else if (ch == '#' && visibleChars == 1) {
				// Preprocessor commands are alone on their line
				styler.ColourTo(i-1, state);
				state = SCE_C_PREPROCESSOR;
				// Skip whitespace between # and preprocessor word
				do {
					i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				} while (isspacechar(ch) && (i < lengthDoc));
			} else if (isoperator(ch)) {
				styler.ColourTo(i-1, state);
				styler.ColourTo(i, SCE_C_OPERATOR);
				if ((ch == '{') || (ch == '}')) {
					levelCurrent += (ch == '{') ? 1 : -1;
				}
			}
		} else if (state == SCE_C_IDENTIFIER) {
			if (!iswordchar(ch)) {
				lastWordWasUUID = classifyWordCpp(styler.GetStartSegment(), i - 1, keywords, styler);
				state = SCE_C_DEFAULT;
				if (ch == '/' && chNext == '*') {
					if (foldComment)
						levelCurrent++;
					if (styler.SafeGetCharAt(i + 2) == '*')
						state = SCE_C_COMMENTDOC;
					else
						state = SCE_C_COMMENT;
				} else if (ch == '/' && chNext == '/') {
					state = SCE_C_COMMENTLINE;
				} else if (ch == '\"') {
					state = SCE_C_STRING;
				} else if (ch == '\'') {
					state = SCE_C_CHARACTER;
				} else if (isoperator(ch)) {
					styler.ColourTo(i, SCE_C_OPERATOR);
					if ((ch == '{') || (ch == '}')) {
						levelCurrent += (ch == '{') ? 1 : -1;
					}
				}
			}
		} else {
			if (state == SCE_C_PREPROCESSOR) {
				if (stylingWithinPreprocessor) {
					if (isspacechar(ch)) {
						styler.ColourTo(i-1, state);
						state = SCE_C_DEFAULT;
					}
				} else {
					if ((ch == '\r' || ch == '\n') && !(chPrev == '\\' || chPrev == '\r')) {
						styler.ColourTo(i-1, state);
						state = SCE_C_DEFAULT;
					}
				}
			} else if (state == SCE_C_COMMENT) {
				if (ch == '/' && chPrev == '*') {
					if (((i > styler.GetStartSegment() + 2) || (
						(initStyle == SCE_C_COMMENT) &&
						(styler.GetStartSegment() == static_cast<unsigned int>(startPos))))) {
						styler.ColourTo(i, state);
						state = SCE_C_DEFAULT;
						if(foldComment)
							levelCurrent--;
					}
				}
			} else if (state == SCE_C_COMMENTDOC) {
				if (ch == '/' && chPrev == '*') {
					if (((i > styler.GetStartSegment() + 2) || (
						(initStyle == SCE_C_COMMENTDOC) &&
						(styler.GetStartSegment() == static_cast<unsigned int>(startPos))))) {
						styler.ColourTo(i, state);
						state = SCE_C_DEFAULT;
						if(foldComment)
							levelCurrent--;
					}
				}
			} else if (state == SCE_C_COMMENTLINE || state == SCE_C_COMMENTLINEDOC) {
				if (ch == '\r' || ch == '\n') {
					styler.ColourTo(i-1, state);
					state = SCE_C_DEFAULT;
				}
			} else if (state == SCE_C_STRING) {
				if (ch == '\\') {
					if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
						i++;
						ch = chNext;
						chNext = styler.SafeGetCharAt(i + 1);
					}
				} else if (ch == '\"') {
					styler.ColourTo(i, state);
					state = SCE_C_DEFAULT;
				} else if ((chNext == '\r' || chNext == '\n') && (chPrev != '\\')) {
					styler.ColourTo(i-1, SCE_C_STRINGEOL);
					state = SCE_C_STRINGEOL;
				}
			} else if (state == SCE_C_CHARACTER) {
				if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) {
					styler.ColourTo(i-1, SCE_C_STRINGEOL);
					state = SCE_C_STRINGEOL;
				} else if (ch == '\\') {
					if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
						i++;
						ch = chNext;
						chNext = styler.SafeGetCharAt(i + 1);
					}
				} else if (ch == '\'') {
					styler.ColourTo(i, state);
					state = SCE_C_DEFAULT;
				}
			} else if (state == SCE_C_REGEX) {
				if (ch == '\r' || ch == '\n' || ch == '/') {
					styler.ColourTo(i, state);
					state = SCE_C_DEFAULT;
				} else if (ch == '\\') {
					// Gobble up the quoted character
					if (chNext == '\\' || chNext == '/') {
						i++;
						ch = chNext;
						chNext = styler.SafeGetCharAt(i + 1);
					}
				}
			} else if (state == SCE_C_VERBATIM) {
				if (ch == '\"') {
					if (chNext == '\"') {
						i++;
						ch = chNext;
						chNext = styler.SafeGetCharAt(i + 1);
					} else {
						styler.ColourTo(i, state);
						state = SCE_C_DEFAULT;
					}
				}
			} else if (state == SCE_C_UUID) {
				if (ch == '\r' || ch == '\n' || ch == ')') {
					styler.ColourTo(i-1, state);
					if (ch == ')')
						styler.ColourTo(i, SCE_C_OPERATOR);
					state = SCE_C_DEFAULT;
				}
			}
		}
		chPrev = ch;
		if (ch != ' ' && ch != '\t')
			chPrevNonWhite = ch;
	}
	styler.ColourTo(lengthDoc - 1, state);

	// Fill in the real level of the next line, keeping the current flags as they will be filled in later
	if (fold) {
		int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
		//styler.SetLevel(lineCurrent, levelCurrent | flagsNext);
		styler.SetLevel(lineCurrent, levelPrev | flagsNext);

	}
}

LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc);
<commit_msg>Fixed CPP lexer to work correctly when the '{' starting a fold section that is folded is deleted. This leads to the fold being unfolded which leads to reentrant styling which failed.<commit_after>// Scintilla source code edit control
/** @file LexCPP.cxx
 ** Lexer for C++, C, Java, and Javascript.
 **/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

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

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

static bool classifyWordCpp(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {
	PLATFORM_ASSERT(end >= start);
	char s[100];
	for (unsigned int i = 0; (i < end - start + 1) && (i < 30); i++) {
		s[i] = styler[start + i];
		s[i + 1] = '\0';
	}
	bool wordIsUUID = false;
	char chAttr = SCE_C_IDENTIFIER;
	if (isdigit(s[0]) || (s[0] == '.'))
		chAttr = SCE_C_NUMBER;
	else {
		if (keywords.InList(s)) {
			chAttr = SCE_C_WORD;
			wordIsUUID = strcmp(s, "uuid") == 0;
		}
	}
	styler.ColourTo(end, chAttr);
	return wordIsUUID;
}

static bool isOKBeforeRE(char ch) {
	return (ch == '(') || (ch == '=') || (ch == ',');
}

static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
                            Accessor &styler) {

	WordList &keywords = *keywordlists[0];

	styler.StartAt(startPos);

	bool fold = styler.GetPropertyInt("fold");
	bool foldComment = styler.GetPropertyInt("fold.comment");
	bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor");
	int lineCurrent = styler.GetLine(startPos);
	int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
	int levelCurrent = levelPrev;

	int state = initStyle;
	if (state == SCE_C_STRINGEOL)	// Does not leak onto next line
		state = SCE_C_DEFAULT;
	char chPrev = ' ';
	char chNext = styler[startPos];
	char chPrevNonWhite = ' ';
	unsigned int lengthDoc = startPos + length;
	int visibleChars = 0;
	styler.StartSegment(startPos);
	bool lastWordWasUUID = false;
	for (unsigned int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);

		bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
		if (atEOL) {
			// Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix)
			// Avoid triggering two times on Dos/Win
			// End of line
			if (state == SCE_C_STRINGEOL) {
				styler.ColourTo(i, state);
				state = SCE_C_DEFAULT;
			}
		}

		if (styler.IsLeadByte(ch)) {
			chNext = styler.SafeGetCharAt(i + 2);
			chPrev = ' ';
			i += 1;
			continue;
		}

		if (state == SCE_C_DEFAULT) {
			if (ch == '@' && chNext == '\"') {
				styler.ColourTo(i - 1, state);
				state = SCE_C_VERBATIM;
				i++;
				ch = chNext;
				chNext = styler.SafeGetCharAt(i + 1);
			} else if (iswordstart(ch) || (ch == '@')) {
				styler.ColourTo(i - 1, state);
				if (lastWordWasUUID) {
					state = SCE_C_UUID;
					lastWordWasUUID = false;
				} else {
					state = SCE_C_IDENTIFIER;
				}
			} else if (ch == '/' && chNext == '*') {
				styler.ColourTo(i - 1, state);
				if (foldComment)
					levelCurrent++;
				if (styler.SafeGetCharAt(i + 2) == '*' ||
				        styler.SafeGetCharAt(i + 2) == '!')	// Support of Qt/Doxygen doc. style
					state = SCE_C_COMMENTDOC;
				else
					state = SCE_C_COMMENT;
			} else if (ch == '/' && chNext == '/') {
				styler.ColourTo(i - 1, state);
				if (styler.SafeGetCharAt(i + 2) == '/' ||
				        styler.SafeGetCharAt(i + 2) == '!')	// Support of Qt/Doxygen doc. style
					state = SCE_C_COMMENTLINEDOC;
				else
					state = SCE_C_COMMENTLINE;
			} else if (ch == '/' && isOKBeforeRE(chPrevNonWhite)) {
				styler.ColourTo(i - 1, state);
				state = SCE_C_REGEX;
			} else if (ch == '\"') {
				styler.ColourTo(i - 1, state);
				state = SCE_C_STRING;
			} else if (ch == '\'') {
				styler.ColourTo(i - 1, state);
				state = SCE_C_CHARACTER;
			} else if (ch == '#' && visibleChars == 0) {
				// Preprocessor commands are alone on their line
				styler.ColourTo(i - 1, state);
				state = SCE_C_PREPROCESSOR;
				// Skip whitespace between # and preprocessor word
				do {
					i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				} while (isspacechar(ch) && (i < lengthDoc));
			} else if (isoperator(ch)) {
				styler.ColourTo(i-1, state);
				styler.ColourTo(i, SCE_C_OPERATOR);
				if ((ch == '{') || (ch == '}')) {
					levelCurrent += (ch == '{') ? 1 : -1;
				}
			}
		} else if (state == SCE_C_IDENTIFIER) {
			if (!iswordchar(ch)) {
				lastWordWasUUID = classifyWordCpp(styler.GetStartSegment(), i - 1, keywords, styler);
				state = SCE_C_DEFAULT;
				if (ch == '/' && chNext == '*') {
					if (foldComment)
						levelCurrent++;
					if (styler.SafeGetCharAt(i + 2) == '*')
						state = SCE_C_COMMENTDOC;
					else
						state = SCE_C_COMMENT;
				} else if (ch == '/' && chNext == '/') {
					state = SCE_C_COMMENTLINE;
				} else if (ch == '\"') {
					state = SCE_C_STRING;
				} else if (ch == '\'') {
					state = SCE_C_CHARACTER;
				} else if (isoperator(ch)) {
					styler.ColourTo(i, SCE_C_OPERATOR);
					if ((ch == '{') || (ch == '}')) {
						levelCurrent += (ch == '{') ? 1 : -1;
					}
				}
			}
		} else {
			if (state == SCE_C_PREPROCESSOR) {
				if (stylingWithinPreprocessor) {
					if (isspacechar(ch)) {
						styler.ColourTo(i - 1, state);
						state = SCE_C_DEFAULT;
					}
				} else {
					if (atEOL && (chPrev != '\\')) {
						styler.ColourTo(i - 1, state);
						state = SCE_C_DEFAULT;
					}
				}
			} else if (state == SCE_C_COMMENT) {
				if (ch == '/' && chPrev == '*') {
					if (((i > styler.GetStartSegment() + 2) || (
					            (initStyle == SCE_C_COMMENT) &&
					            (styler.GetStartSegment() == static_cast<unsigned int>(startPos))))) {
						styler.ColourTo(i, state);
						state = SCE_C_DEFAULT;
						if (foldComment)
							levelCurrent--;
					}
				}
			} else if (state == SCE_C_COMMENTDOC) {
				if (ch == '/' && chPrev == '*') {
					if (((i > styler.GetStartSegment() + 2) || (
					            (initStyle == SCE_C_COMMENTDOC) &&
					            (styler.GetStartSegment() == static_cast<unsigned int>(startPos))))) {
						styler.ColourTo(i, state);
						state = SCE_C_DEFAULT;
						if (foldComment)
							levelCurrent--;
					}
				}
			} else if (state == SCE_C_COMMENTLINE || state == SCE_C_COMMENTLINEDOC) {
				if (ch == '\r' || ch == '\n') {
					styler.ColourTo(i - 1, state);
					state = SCE_C_DEFAULT;
				}
			} else if (state == SCE_C_STRING) {
				if (ch == '\\') {
					if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
						i++;
						ch = chNext;
						chNext = styler.SafeGetCharAt(i + 1);
					}
				} else if (ch == '\"') {
					styler.ColourTo(i, state);
					state = SCE_C_DEFAULT;
				} else if ((chNext == '\r' || chNext == '\n') && (chPrev != '\\')) {
					styler.ColourTo(i - 1, SCE_C_STRINGEOL);
					state = SCE_C_STRINGEOL;
				}
			} else if (state == SCE_C_CHARACTER) {
				if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) {
					styler.ColourTo(i - 1, SCE_C_STRINGEOL);
					state = SCE_C_STRINGEOL;
				} else if (ch == '\\') {
					if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
						i++;
						ch = chNext;
						chNext = styler.SafeGetCharAt(i + 1);
					}
				} else if (ch == '\'') {
					styler.ColourTo(i, state);
					state = SCE_C_DEFAULT;
				}
			} else if (state == SCE_C_REGEX) {
				if (ch == '\r' || ch == '\n' || ch == '/') {
					styler.ColourTo(i, state);
					state = SCE_C_DEFAULT;
				} else if (ch == '\\') {
					// Gobble up the quoted character
					if (chNext == '\\' || chNext == '/') {
						i++;
						ch = chNext;
						chNext = styler.SafeGetCharAt(i + 1);
					}
				}
			} else if (state == SCE_C_VERBATIM) {
				if (ch == '\"') {
					if (chNext == '\"') {
						i++;
						ch = chNext;
						chNext = styler.SafeGetCharAt(i + 1);
					} else {
						styler.ColourTo(i, state);
						state = SCE_C_DEFAULT;
					}
				}
			} else if (state == SCE_C_UUID) {
				if (ch == '\r' || ch == '\n' || ch == ')') {
					styler.ColourTo(i - 1, state);
					if (ch == ')')
						styler.ColourTo(i, SCE_C_OPERATOR);
					state = SCE_C_DEFAULT;
				}
			}
		}

		if (atEOL) {
			if (fold) {
				int lev = levelPrev;
				if (visibleChars == 0)
					lev |= SC_FOLDLEVELWHITEFLAG;
				if ((levelCurrent > levelPrev) && (visibleChars > 0))
					lev |= SC_FOLDLEVELHEADERFLAG;
				if (lev != styler.LevelAt(lineCurrent)) {
					styler.ColourTo(i, state);
					styler.Flush();
					styler.SetLevel(lineCurrent, lev);
					styler.StartAt(i + 1);
				}
				lineCurrent++;
				levelPrev = levelCurrent;
			}
			visibleChars = 0;
		}
		if (!isspacechar(ch))
			visibleChars++;

		chPrev = ch;
		if (ch != ' ' && ch != '\t')
			chPrevNonWhite = ch;
	}
	styler.ColourTo(lengthDoc - 1, state);

	// Fill in the real level of the next line, keeping the current flags as they will be filled in later
	if (fold) {
		int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
		//styler.SetLevel(lineCurrent, levelCurrent | flagsNext);
		styler.SetLevel(lineCurrent, levelPrev | flagsNext);

	}
}

LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc);
<|endoftext|>


<commit_before>#include "Matrix.h"

/* ===========================================================================================
// Basic constructor
============================================================================================*/
Matrix::Matrix()
    : m_iColumns(1)
    , m_iRows(1)
    , m_pdData(NULL)
{
    bool bSuccess = Init(m_iRows, m_iColumns);
    assert(bSuccess);
}

/* ===========================================================================================
// Matrix constructor
============================================================================================*/
Matrix::Matrix(int row, int col)
    : m_iColumns(col)
    , m_iRows(row)
    , m_pdData(NULL)
{
    bool bSuccess = Init(m_iRows, m_iColumns);
    assert(bSuccess);
}

/* ===========================================================================================
// Matrix copy constructor
============================================================================================*/
Matrix::Matrix(const Matrix& other)
    : m_iColumns(other.GetColumns())
    , m_iRows(other.GetRows())
    , m_pdData(NULL)
{
    bool bSuccess = Init(m_iRows, m_iColumns);
    assert(bSuccess);

    memcpy(m_pdData, other.m_pdData, sizeof(double)*m_iColumns*m_iRows);
}

Matrix::~Matrix()
{
    if(m_pdData != NULL)
    {
        delete [] m_pdData;
        m_pdData = NULL;
    }
}

/* ===========================================================================================
// Initialize the matrix
============================================================================================*/
bool Matrix::Init(int row, int col)
{
    if(m_pdData!=NULL)
    {
        delete [] m_pdData;
        m_pdData = NULL;
    }

    m_iRows = row;
    m_iColumns = col;
    int size = row*col;

    if(size<0)
    {
        return false;
    }

    m_pdData = new double[size];

    if(m_pdData == NULL)
    {
        return false;
    }

    memset(m_pdData, 0, sizeof(double)*size);

    return true;
}

bool Matrix::JacobiEigenv(double* dblEigenValue, Matrix& mtxEigenVector, int nMaxIt, double eps)
{
    int i = 0, j = 0, p = 0, q = 0, u = 0, w = 0, t = 0, s = 0, l = 0;
    double fm = 0.0, cn = 0.0, sn = 0.0, omega = 0.0, x = 0.0, y = 0.0, d = 0.0;

    if(!mtxEigenVector.Init(m_iColumns, m_iRows))
    {
        return false;
    }

    l = 1;

    for(i=0;i<=m_iColumns-1;i++)
    {
        mtxEigenVector.m_pdData[i*m_iColumns]=1.0;
        for(j=0;j<=m_iColumns-1;j++)
        {
            if(i!=j)
            {
                mtxEigenVector.m_pdData[i*m_iColumns] = 0.0;
            }
        }
    }

    while(true)
    {
        fm = 0.0;
        for(i=0;i<=m_iColumns-1;i++)
        {
            for(j=0;j<=i-1;j++)
            {
                d=fabs(m_pdData[i*m_iColumns+j]);
                if((i!=j) && (d>fm))
                {
                    fm=d;
                    p=i;
                    q=j;
                }
            }
        }

        // Error smaller than the eps, use values on the diagnoal as Eigen value and return true
        if(fm<eps)
        {
            for(i=0;i<m_iColumns;++i)
            {
                dblEigenValue[i] = GetElement(i, i);
            }
            return true;
        }

        if(l>nMaxIt)
        {
            return false;
        }

        l++;
        u = p*m_iColumns+q;
        w = p*m_iColumns+p;
        t = q*m_iColumns+p;
        s = q*m_iColumns+q;
        x = -m_pdData[u];
        y = (m_pdData[s]-m_pdData[w])/2.0;
        omega = x/sqrt(x*x + y*y);

        if(y<0.0)
        {
            omega = -omega;
        }

        sn = 1.0 + sqrt(1.0-omega*omega);
        sn = omega/sqrt(2.0*sn);
        cn = sqrt(1.0 - sn*sn);
        fm = m_pdData[w];
        m_pdData[w] = fm*cn*cn + m_pdData[s]*sn*sn + m_pdData[u]*omega;
        m_pdData[s] = fm*sn*sn + m_pdData[s]*cn*cn - m_pdData[u]*omega;
        m_pdData[u] = 0.0;
        m_pdData[t] = 0.0;

        for(j=0;j<=m_iColumns-1;j++)
        {
            if((j!=p) && (j!=q))
            {
                u = p*m_iColumns+j;
                w = q*m_iColumns+j;
                fm = m_pdData[u];
                m_pdData[u] = fm*cn + m_pdData[w]*sn;
                m_pdData[w] = fm*sn + m_pdData[w]*cn;
            }
        }

        for(i=0;i<=m_iColumns-1;i++)
        {
            if((i!=p) && (i!=q))
            {
                u = i*m_iColumns+p;
                w = i*m_iColumns+q;
                fm = m_pdData[u];
                m_pdData[u] = fm*cn + m_pdData[w]*sn;
                m_pdData[w] = -fm*sn + m_pdData[w]*cn;
            }
        }

        for(i=0;i<m_iColumns-1;i++)
        {
            u = i*m_iColumns+p;
            w = i*m_iColumns+q;
            fm = mtxEigenVector.m_pdData[u];
            mtxEigenVector.m_pdData[u] = fm*cn + mtxEigenVector.m_pdData[w]*sn;
            mtxEigenVector.m_pdData[w] = -fm*sn + mtxEigenVector.m_pdData[w]*cn;
        }
    }

    for(i=0;i<m_iColumns;++i)
    {
        dblEigenValue[i] = GetElement(i,i);
    }

    return true;
}

Matrix& Matrix::operator=(const Matrix& other)
{
    if(&other!=this)
    {
        bool bSuccess = Init(other.GetRows(), other.GetColumns());
        assert(bSuccess);

        memcpy(m_pdData, other.m_pdData, sizeof(double)*m_iColumns*m_iRows);
    }

    return *this;
}

bool Matrix::operator==(const Matrix& other) const
{
    int i = 0, j = 0;
    if(m_iColumns!=other.GetColumns() ||
       m_iRows!=other.GetRows())
    {
        return false;
    }

    for(i=0;i<m_iRows;++i)
    {
        for(j=0;j<m_iColumns;++j)
        {
            if(GetElement(i, j) != other.GetElement(i, j))
            {
                return false;
            }
        }
    }

    return true;
}

bool Matrix::operator!=(const Matrix& other) const
{
    return !(*this == other);
}

Matrix Matrix::operator+(const Matrix& other) const
{
    int i = 0, j = 0;
    assert(m_iColumns == other.GetColumns() &&
           m_iRows == other.GetRows());

    Matrix result(*this);

    for(i=0;i<m_iRows;++i)
    {
        for(j=0;j<m_iColumns;++j)
        {
            result.SetElement(i, j, result.GetElement(i,j) + other.GetElement(i,j));
        }
    }

    return result;
}

Matrix Matrix::operator-(const Matrix& other) const
{
    int i = 0, j = 0;
    assert(m_iColumns == other.GetColumns() &&
           m_iRows == other.GetRows());

    Matrix result(*this);

    for(i=0;i<m_iRows;++i)
    {
        for(j=0;j<m_iColumns;++j)
        {
            result.SetElement(i, j, result.GetElement(i, j) - other.GetElement(i, j));
        }
    }

    return result;
}

Matrix Matrix::operator*(double value) const
{
    int i = 0, j = 0;
    Matrix result(*this);

    for(i=0;i<m_iRows;++i)
    {
        for(j=0;j<m_iColumns;++j)
        {
            result.SetElement(i, j, result.GetElement(i, j)*value);
        }
    }

    return result;
}

Matrix Matrix::operator*(const Matrix& other) const
{
    assert(m_iColumns == other.GetRows());

    int i = 0, j = 0, k = 0;
    Matrix result(m_iRows, other.GetColumns());

    double value;
    for(i=0;i<result.GetRows();++i)
    {
        for(j=0;j<other.GetColumns();++j)
        {
            value = 0.0;
            for(k=0;k<m_iColumns;++k)
            {
                value += GetElement(i, k)*other.GetElement(k, j);
            }
            result.SetElement(i, j, value);
        }
    }

    return result;
}

/* ===========================================================================================
// Get data pointer of the matrix
============================================================================================*/
void Matrix::SetData(double* value)
{
    memset(m_pdData, 0, sizeof(double)*m_iColumns*m_iRows);
    memcpy(m_pdData, value, sizeof(double)*m_iColumns*m_iRows);
}

/* ===========================================================================================
// Get data pointer of the matrix
============================================================================================*/
double* Matrix::GetData() const
{
    return m_pdData;
}

bool Matrix::SetElement(int row, int col, double value)
{
    if(col<0 || col>=m_iColumns || row<0 || row>=m_iRows)
    {
        return false;
    }

    if(m_pdData == NULL)
    {
        return false;
    }

    m_pdData[col+row*m_iColumns] = value;
}

double Matrix::GetElement(int row, int col) const
{
    if(col<0 || col>=m_iColumns || row<0 || row>=m_iRows)
    {
        return false;
    }

    if(m_pdData == NULL)
    {
        return false;
    }

    return m_pdData[col+row*m_iColumns];
}

int Matrix::GetColumns() const
{
    return m_iColumns;
}

int Matrix::GetRows() const
{
    return m_iRows;
}
<commit_msg>Oops... Small fix for Matrix<commit_after>#include "Matrix.h"

/* ===========================================================================================
// Basic constructor
============================================================================================*/
Matrix::Matrix()
    : m_iColumns(1)
    , m_iRows(1)
    , m_pdData(NULL)
{
    bool bSuccess = Init(m_iRows, m_iColumns);
    assert(bSuccess);
}

/* ===========================================================================================
// Matrix constructor
============================================================================================*/
Matrix::Matrix(int row, int col)
    : m_iColumns(col)
    , m_iRows(row)
    , m_pdData(NULL)
{
    bool bSuccess = Init(m_iRows, m_iColumns);
    assert(bSuccess);
}

/* ===========================================================================================
// Matrix copy constructor
============================================================================================*/
Matrix::Matrix(const Matrix& other)
    : m_iColumns(other.GetColumns())
    , m_iRows(other.GetRows())
    , m_pdData(NULL)
{
    bool bSuccess = Init(m_iRows, m_iColumns);
    assert(bSuccess);

    memcpy(m_pdData, other.m_pdData, sizeof(double)*m_iColumns*m_iRows);
}

Matrix::~Matrix()
{
    if(m_pdData != NULL)
    {
        delete [] m_pdData;
        m_pdData = NULL;
    }
}

/* ===========================================================================================
// Initialize the matrix
============================================================================================*/
bool Matrix::Init(int row, int col)
{
    if(m_pdData!=NULL)
    {
        delete [] m_pdData;
        m_pdData = NULL;
    }

    m_iRows = row;
    m_iColumns = col;
    int size = row*col;

    if(size<0)
    {
        return false;
    }

    m_pdData = new double[size];

    if(m_pdData == NULL)
    {
        return false;
    }

    memset(m_pdData, 0, sizeof(double)*size);

    return true;
}

bool Matrix::JacobiEigenv(double* dblEigenValue, Matrix& mtxEigenVector, int nMaxIt, double eps)
{
    int i = 0, j = 0, p = 0, q = 0, u = 0, w = 0, t = 0, s = 0, l = 0;
    double fm = 0.0, cn = 0.0, sn = 0.0, omega = 0.0, x = 0.0, y = 0.0, d = 0.0;

    if(!mtxEigenVector.Init(m_iColumns, m_iRows))
    {
        return false;
    }

    l = 1;

    for(i=0;i<=m_iColumns-1;i++)
    {
        mtxEigenVector.m_pdData[i*m_iColumns]=1.0;
        for(j=0;j<=m_iColumns-1;j++)
        {
            if(i!=j)
            {
                mtxEigenVector.m_pdData[i*m_iColumns] = 0.0;
            }
        }
    }

    while(true)
    {
        fm = 0.0;
        for(i=0;i<=m_iColumns-1;i++)
        {
            for(j=0;j<=i-1;j++)
            {
                d=fabs(m_pdData[i*m_iColumns+j]);
                if((i!=j) && (d>fm))
                {
                    fm=d;
                    p=i;
                    q=j;
                }
            }
        }

        // Error smaller than the eps, use values on the diagnoal as Eigen value and return true
        if(fm<eps)
        {
            for(i=0;i<m_iColumns;++i)
            {
                dblEigenValue[i] = GetElement(i, i);
            }
            return true;
        }

        if(l>nMaxIt)
        {
            return false;
        }

        l++;
        u = p*m_iColumns+q;
        w = p*m_iColumns+p;
        t = q*m_iColumns+p;
        s = q*m_iColumns+q;
        x = -m_pdData[u];
        y = (m_pdData[s]-m_pdData[w])/2.0;
        omega = x/sqrt(x*x + y*y);

        if(y<0.0)
        {
            omega = -omega;
        }

        sn = 1.0 + sqrt(1.0-omega*omega);
        sn = omega/sqrt(2.0*sn);
        cn = sqrt(1.0 - sn*sn);
        fm = m_pdData[w];
        m_pdData[w] = fm*cn*cn + m_pdData[s]*sn*sn + m_pdData[u]*omega;
        m_pdData[s] = fm*sn*sn + m_pdData[s]*cn*cn - m_pdData[u]*omega;
        m_pdData[u] = 0.0;
        m_pdData[t] = 0.0;

        for(j=0;j<=m_iColumns-1;j++)
        {
            if((j!=p) && (j!=q))
            {
                u = p*m_iColumns+j;
                w = q*m_iColumns+j;
                fm = m_pdData[u];
                m_pdData[u] = fm*cn + m_pdData[w]*sn;
                m_pdData[w] = fm*sn + m_pdData[w]*cn;
            }
        }

        for(i=0;i<=m_iColumns-1;i++)
        {
            if((i!=p) && (i!=q))
            {
                u = i*m_iColumns+p;
                w = i*m_iColumns+q;
                fm = m_pdData[u];
                m_pdData[u] = fm*cn + m_pdData[w]*sn;
                m_pdData[w] = -fm*sn + m_pdData[w]*cn;
            }
        }

        for(i=0;i<m_iColumns-1;i++)
        {
            u = i*m_iColumns+p;
            w = i*m_iColumns+q;
            fm = mtxEigenVector.m_pdData[u];
            mtxEigenVector.m_pdData[u] = fm*cn + mtxEigenVector.m_pdData[w]*sn;
            mtxEigenVector.m_pdData[w] = -fm*sn + mtxEigenVector.m_pdData[w]*cn;
        }
    }

    for(i=0;i<m_iColumns;++i)
    {
        dblEigenValue[i] = GetElement(i,i);
    }

    return true;
}

Matrix& Matrix::operator=(const Matrix& other)
{
    if(&other!=this)
    {
        bool bSuccess = Init(other.GetRows(), other.GetColumns());
        assert(bSuccess);

        memcpy(m_pdData, other.m_pdData, sizeof(double)*m_iColumns*m_iRows);
    }

    return *this;
}

bool Matrix::operator==(const Matrix& other) const
{
    int i = 0, j = 0;
    if(m_iColumns!=other.GetColumns() ||
       m_iRows!=other.GetRows())
    {
        return false;
    }

    for(i=0;i<m_iRows;++i)
    {
        for(j=0;j<m_iColumns;++j)
        {
            if(GetElement(i, j) != other.GetElement(i, j))
            {
                return false;
            }
        }
    }

    return true;
}

bool Matrix::operator!=(const Matrix& other) const
{
    return !(*this == other);
}

Matrix Matrix::operator+(const Matrix& other) const
{
    int i = 0, j = 0;
    assert(m_iColumns == other.GetColumns() &&
           m_iRows == other.GetRows());

    Matrix result(*this);

    for(i=0;i<m_iRows;++i)
    {
        for(j=0;j<m_iColumns;++j)
        {
            result.SetElement(i, j, result.GetElement(i,j) + other.GetElement(i,j));
        }
    }

    return result;
}

Matrix Matrix::operator-(const Matrix& other) const
{
    int i = 0, j = 0;
    assert(m_iColumns == other.GetColumns() &&
           m_iRows == other.GetRows());

    Matrix result(*this);

    for(i=0;i<m_iRows;++i)
    {
        for(j=0;j<m_iColumns;++j)
        {
            result.SetElement(i, j, result.GetElement(i, j) - other.GetElement(i, j));
        }
    }

    return result;
}

Matrix Matrix::operator*(double value) const
{
    int i = 0, j = 0;
    Matrix result(*this);

    for(i=0;i<m_iRows;++i)
    {
        for(j=0;j<m_iColumns;++j)
        {
            result.SetElement(i, j, result.GetElement(i, j)*value);
        }
    }

    return result;
}

Matrix Matrix::operator*(const Matrix& other) const
{
    assert(m_iColumns == other.GetRows());

    int i = 0, j = 0, k = 0;
    Matrix result(m_iRows, other.GetColumns());

    double value;
    for(i=0;i<result.GetRows();++i)
    {
        for(j=0;j<other.GetColumns();++j)
        {
            value = 0.0;
            for(k=0;k<m_iColumns;++k)
            {
                value += GetElement(i, k)*other.GetElement(k, j);
            }
            result.SetElement(i, j, value);
        }
    }

    return result;
}

/* ===========================================================================================
// Get data pointer of the matrix
============================================================================================*/
void Matrix::SetData(double* value)
{
    memset(m_pdData, 0, sizeof(double)*m_iColumns*m_iRows);
    memcpy(m_pdData, value, sizeof(double)*m_iColumns*m_iRows);
}

/* ===========================================================================================
// Get data pointer of the matrix
============================================================================================*/
double* Matrix::GetData() const
{
    return m_pdData;
}

bool Matrix::SetElement(int row, int col, double value)
{
    if(col<0 || col>=m_iColumns || row<0 || row>=m_iRows)
    {
        return false;
    }

    if(m_pdData == NULL)
    {
        return false;
    }

    m_pdData[col+row*m_iColumns] = value;

    return true;
}

double Matrix::GetElement(int row, int col) const
{
    if(col<0 || col>=m_iColumns || row<0 || row>=m_iRows)
    {
        return false;
    }

    if(m_pdData == NULL)
    {
        return false;
    }

    return m_pdData[col+row*m_iColumns];
}

int Matrix::GetColumns() const
{
    return m_iColumns;
}

int Matrix::GetRows() const
{
    return m_iRows;
}
<|endoftext|>