Skip to content

Commit

Permalink
Code linting: modify "if ( foo() ) { foo()->bar }"-like constructs
Browse files Browse the repository at this point in the history
cppcheck sometimes detects this as a potential null pointer dereference.
This makes sense, although it is quite unlikely that the return a foo()
might change in between.

To avoid such warnings, and also repeated method calls which can have some
cost, I've run the following refactoring script to store the result of
foo() in a local variable.

```shell
for i in `find ../src -name "*.cpp"`; do python analyze.py $i > $i.tmp; diff $i.tmp $i >/dev/null || (echo "Paching $i"; mv $i.tmp $i); rm -f $i.tmp; done
```

with analyze.py being

```python
import re
import sys

lines = [l[0:-1] if l[-1] == '\n' else l for l in open(sys.argv[1], "rt").readlines()]

if_pattern = re.compile("(^[ ]*)if \( ([a-zA-Z0-9_\.]+)\(\) \)$")

i = 0
while i < len(lines):
    line = lines[i]
    modified = False

    m = if_pattern.match(line)
    if m:
        next_line = lines[i+1]
        indent = m.group(1)
        s = m.group(2) + "()"
        tmpVar = m.group(2).split('.')[-1]
        tmpVar = 'l' + tmpVar[0].upper() + tmpVar[1:]

        if next_line == indent + '{':
            found = False

            # Look in the block after the if() for a pattern where we dereference
            # "foo()"
            j = i + 1
            while lines[j] != indent + '}':
                if lines[j].find(s + '->') >= 0 or lines[j].find('*' + s) >= 0 or lines[j].find(s + '[') >= 0:
                    found = True
                    break
                j += 1

            if found:
                print(indent + 'if ( auto *' + tmpVar + ' = ' + s +  ' )')
                j = i + 1
                while lines[j] != indent + '}':
                    print(lines[j].replace(' ' + s, ' ' + tmpVar).replace('.' + s, '.' + tmpVar).replace('*' + s, '*' + tmpVar).replace('!' + s, '!' + tmpVar))
                    j += 1
                print(lines[j])
                modified = True
                i = j

        else:
            if next_line.find(s) >= 0:
                print(indent + 'if ( auto *' + tmpVar + ' = ' + s +  ' )')
                print(next_line.replace(' ' + s, ' ' + tmpVar).replace('.' + s, '.' + tmpVar).replace('*' + s, '*' + tmpVar).replace('!' + s, '!' + tmpVar))
                modified = True
                i += 1

    if not modified:
        print(line)
    i += 1
```
  • Loading branch information
rouault authored and nyalldawson committed Oct 5, 2020
1 parent a3c4fe4 commit 44466a3
Show file tree
Hide file tree
Showing 74 changed files with 321 additions and 321 deletions.
16 changes: 8 additions & 8 deletions src/app/qgisapp.cpp
Expand Up @@ -4186,10 +4186,10 @@ void QgisApp::setupConnections()
{
canvas->setCanvasColor( backgroundColor );
}
if ( mapOverviewCanvas() )
if ( auto *lMapOverviewCanvas = mapOverviewCanvas() )
{
mapOverviewCanvas()->setBackgroundColor( backgroundColor );
mapOverviewCanvas()->refresh();
lMapOverviewCanvas->setBackgroundColor( backgroundColor );
lMapOverviewCanvas->refresh();
}
} );

Expand Down Expand Up @@ -7300,13 +7300,13 @@ void QgisApp::dxfExport()
flags = flags | QgsDxfExport::FlagNoMText;
dxfExport.setFlags( flags );

if ( mapCanvas() )
if ( auto *lMapCanvas = mapCanvas() )
{
//extent
if ( d.exportMapExtent() )
{
QgsCoordinateTransform t( mapCanvas()->mapSettings().destinationCrs(), d.crs(), QgsProject::instance() );
dxfExport.setExtent( t.transformBoundingBox( mapCanvas()->extent() ) );
QgsCoordinateTransform t( lMapCanvas->mapSettings().destinationCrs(), d.crs(), QgsProject::instance() );
dxfExport.setExtent( t.transformBoundingBox( lMapCanvas->extent() ) );
}
}

Expand Down Expand Up @@ -16272,9 +16272,9 @@ void QgisApp::showSystemNotification( const QString &title, const QString &messa
if ( !result.successful )
{
// fallback - use message bar if available, otherwise use a message log
if ( messageBar() )
if ( auto *lMessageBar = messageBar() )
{
messageBar()->pushInfo( title, message );
lMessageBar->pushInfo( title, message );
}
else
{
Expand Down
8 changes: 4 additions & 4 deletions src/app/qgsmaptooloffsetcurve.cpp
Expand Up @@ -86,19 +86,19 @@ void QgsMapToolOffsetCurve::canvasReleaseEvent( QgsMapMouseEvent *e )
QgsPointLocator::Types( QgsPointLocator::Edge | QgsPointLocator::Area ) );
}

if ( match.layer() )
if ( auto *lLayer = match.layer() )
{
mSourceLayer = match.layer();
mSourceLayer = lLayer;
QgsFeature fet;
if ( match.layer()->getFeatures( QgsFeatureRequest( match.featureId() ) ).nextFeature( fet ) )
if ( lLayer->getFeatures( QgsFeatureRequest( match.featureId() ) ).nextFeature( fet ) )
{
mSourceFeature = fet;
mCtrlHeldOnFirstClick = ( e->modifiers() & Qt::ControlModifier ); //no geometry modification if ctrl is pressed
prepareGeometry( match, fet );
mRubberBand = createRubberBand();
if ( mRubberBand )
{
mRubberBand->setToGeometry( mManipulatedGeometry, match.layer() );
mRubberBand->setToGeometry( mManipulatedGeometry, lLayer );
}
mModifiedFeature = fet.id();
createUserInputWidget();
Expand Down
16 changes: 8 additions & 8 deletions src/app/qgsmaptooltrimextendfeature.cpp
Expand Up @@ -60,9 +60,9 @@ static bool getPoints( const QgsPointLocator::Match &match, QgsPoint &p1, QgsPoi
const QgsFeatureId fid = match.featureId();
const int vertex = match.vertexIndex();

if ( match.layer() )
if ( auto *lLayer = match.layer() )
{
const QgsGeometry geom = match.layer()->getGeometry( fid );
const QgsGeometry geom = lLayer->getGeometry( fid );

if ( !( geom.isNull() || geom.isEmpty() ) )
{
Expand Down Expand Up @@ -250,18 +250,18 @@ void QgsMapToolTrimExtendFeature::canvasReleaseEvent( QgsMapMouseEvent *e )
filter.setLayer( mVlayer );
match = mCanvas->snappingUtils()->snapToMap( mMapPoint, &filter, true );

if ( match.layer() )
if ( auto *lLayer = match.layer() )
{

match.layer()->beginEditCommand( tr( "Trim/Extend feature" ) );
match.layer()->changeGeometry( match.featureId(), mGeom );
lLayer->beginEditCommand( tr( "Trim/Extend feature" ) );
lLayer->changeGeometry( match.featureId(), mGeom );
if ( QgsProject::instance()->topologicalEditing() )
{
match.layer()->addTopologicalPoints( mIntersection );
lLayer->addTopologicalPoints( mIntersection );
mLimitLayer->addTopologicalPoints( mIntersection );
}
match.layer()->endEditCommand();
match.layer()->triggerRepaint();
lLayer->endEditCommand();
lLayer->triggerRepaint();

emit messageEmitted( tr( "Feature trimmed/extended." ) );
}
Expand Down
Expand Up @@ -197,12 +197,12 @@ QList<QgsVectorLayerRef> QgsRelationReferenceFieldFormatter::layerDependencies(
QVariantList QgsRelationReferenceFieldFormatter::availableValues( const QVariantMap &config, int countLimit, const QgsFieldFormatterContext &context ) const
{
QVariantList values;
if ( context.project() )
if ( auto *lProject = context.project() )
{
const QgsVectorLayer *referencedLayer = context.project()->relationManager()->relation( config[QStringLiteral( "Relation" )].toString() ).referencedLayer();
const QgsVectorLayer *referencedLayer = lProject->relationManager()->relation( config[QStringLiteral( "Relation" )].toString() ).referencedLayer();
if ( referencedLayer )
{
int fieldIndex = context.project()->relationManager()->relation( config[QStringLiteral( "Relation" )].toString() ).referencedFields().first();
int fieldIndex = lProject->relationManager()->relation( config[QStringLiteral( "Relation" )].toString() ).referencedFields().first();
values = qgis::setToList( referencedLayer->uniqueValues( fieldIndex, countLimit ) );
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/core/fieldformatter/qgsvaluerelationfieldformatter.cpp
Expand Up @@ -213,9 +213,9 @@ QVariantList QgsValueRelationFieldFormatter::availableValues( const QVariantMap
{
QVariantList values;

if ( context.project() )
if ( auto *lProject = context.project() )
{
const QgsVectorLayer *referencedLayer = qobject_cast<QgsVectorLayer *>( context.project()->mapLayer( config[QStringLiteral( "Layer" )].toString() ) );
const QgsVectorLayer *referencedLayer = qobject_cast<QgsVectorLayer *>( lProject->mapLayer( config[QStringLiteral( "Layer" )].toString() ) );
if ( referencedLayer )
{
int fieldIndex = referencedLayer->fields().indexOf( config.value( QStringLiteral( "Key" ) ).toString() );
Expand Down
4 changes: 2 additions & 2 deletions src/core/geometry/qgscurvepolygon.cpp
Expand Up @@ -417,9 +417,9 @@ QDomElement QgsCurvePolygon::asGml3( QDomDocument &doc, int precision, const QSt
json QgsCurvePolygon::asJsonObject( int precision ) const
{
json coordinates( json::array( ) );
if ( exteriorRing() )
if ( auto *lExteriorRing = exteriorRing() )
{
std::unique_ptr< QgsLineString > exteriorLineString( exteriorRing()->curveToLine() );
std::unique_ptr< QgsLineString > exteriorLineString( lExteriorRing->curveToLine() );
QgsPointSequence exteriorPts;
exteriorLineString->points( exteriorPts );
coordinates.push_back( QgsGeometryUtils::pointsToJson( exteriorPts, precision ) );
Expand Down
6 changes: 3 additions & 3 deletions src/core/labeling/qgsvectorlayerlabelprovider.cpp
Expand Up @@ -557,10 +557,10 @@ void QgsVectorLayerLabelProvider::drawLabelPrivate( pal::LabelPosition *label, Q
QString txt = lf->text( label->getPartId() );
QFontMetricsF *labelfm = lf->labelFontMetrics();

if ( context.maskIdProvider() )
if ( auto *lMaskIdProvider = context.maskIdProvider() )
{
int maskId = context.maskIdProvider()->maskId( label->getFeaturePart()->layer()->provider()->layerId(),
label->getFeaturePart()->layer()->provider()->providerId() );
int maskId = lMaskIdProvider->maskId( label->getFeaturePart()->layer()->provider()->layerId(),
label->getFeaturePart()->layer()->provider()->providerId() );
context.setCurrentMaskId( maskId );
}

Expand Down
8 changes: 4 additions & 4 deletions src/core/layertree/qgslayertreemodellegendnode.cpp
Expand Up @@ -253,8 +253,8 @@ QgsSymbolLegendNode::QgsSymbolLegendNode( QgsLayerTreeLayer *nodeLayer, const Qg
connect( qobject_cast<QgsVectorLayer *>( nodeLayer->layer() ), &QgsVectorLayer::symbolFeatureCountMapChanged, this, &QgsSymbolLegendNode::updateLabel );
connect( nodeLayer, &QObject::destroyed, this, [ = ]() { mLayerNode = nullptr; } );

if ( mItem.symbol() )
mSymbolUsesMapUnits = ( mItem.symbol()->outputUnit() != QgsUnitTypes::RenderMillimeters );
if ( auto *lSymbol = mItem.symbol() )
mSymbolUsesMapUnits = ( lSymbol->outputUnit() != QgsUnitTypes::RenderMillimeters );
}

Qt::ItemFlags QgsSymbolLegendNode::flags() const
Expand Down Expand Up @@ -402,8 +402,8 @@ QgsRenderContext *QgsLayerTreeModelLegendNode::createTemporaryRenderContext() co
double scale = 0.0;
double mupp = 0.0;
int dpi = 0;
if ( model() )
model()->legendMapViewData( &mupp, &dpi, &scale );
if ( auto *lModel = model() )
lModel->legendMapViewData( &mupp, &dpi, &scale );

if ( qgsDoubleNear( mupp, 0.0 ) || dpi == 0 || qgsDoubleNear( scale, 0.0 ) )
return nullptr;
Expand Down
4 changes: 2 additions & 2 deletions src/core/layout/qgslayoutitem.cpp
Expand Up @@ -576,8 +576,8 @@ void QgsLayoutItem::setScenePos( const QPointF destinationPos )
//since setPos does not account for item rotation, use difference between
//current scenePos (which DOES account for rotation) and destination pos
//to calculate how much the item needs to move
if ( parentItem() )
setPos( pos() + ( destinationPos - scenePos() ) + parentItem()->scenePos() );
if ( auto *lParentItem = parentItem() )
setPos( pos() + ( destinationPos - scenePos() ) + lParentItem->scenePos() );
else
setPos( pos() + ( destinationPos - scenePos() ) );
}
Expand Down
10 changes: 5 additions & 5 deletions src/core/layout/qgslayoutitemmarker.cpp
Expand Up @@ -64,20 +64,20 @@ QIcon QgsLayoutItemMarker::icon() const

void QgsLayoutItemMarker::refreshSymbol()
{
if ( layout() )
if ( auto *lLayout = layout() )
{
QgsRenderContext rc = QgsLayoutUtils::createRenderContextForLayout( layout(), nullptr, layout()->renderContext().dpi() );
QgsRenderContext rc = QgsLayoutUtils::createRenderContextForLayout( lLayout, nullptr, lLayout->renderContext().dpi() );

std::unique_ptr< QgsMarkerSymbol > sym( mShapeStyleSymbol->clone() );
sym->setAngle( sym->angle() + mNorthArrowRotation );
sym->startRender( rc );
QRectF bounds = sym->bounds( QPointF( 0, 0 ), rc );
sym->stopRender( rc );
mPoint = QPointF( -bounds.left() * 25.4 / layout()->renderContext().dpi(),
-bounds.top() * 25.4 / layout()->renderContext().dpi() );
mPoint = QPointF( -bounds.left() * 25.4 / lLayout->renderContext().dpi(),
-bounds.top() * 25.4 / lLayout->renderContext().dpi() );
bounds.translate( mPoint );

QgsLayoutSize newSizeMm = QgsLayoutSize( bounds.size() * 25.4 / layout()->renderContext().dpi(), QgsUnitTypes::LayoutMillimeters );
QgsLayoutSize newSizeMm = QgsLayoutSize( bounds.size() * 25.4 / lLayout->renderContext().dpi(), QgsUnitTypes::LayoutMillimeters );
mFixedSize = mLayout->renderContext().measurementConverter().convert( newSizeMm, sizeWithUnits().units() );

attemptResize( mFixedSize );
Expand Down
6 changes: 3 additions & 3 deletions src/core/layout/qgslayoutitempolygon.cpp
Expand Up @@ -80,10 +80,10 @@ void QgsLayoutItemPolygon::createDefaultPolygonStyleSymbol()

void QgsLayoutItemPolygon::refreshSymbol()
{
if ( layout() )
if ( auto *lLayout = layout() )
{
QgsRenderContext rc = QgsLayoutUtils::createRenderContextForLayout( layout(), nullptr, layout()->renderContext().dpi() );
mMaxSymbolBleed = ( 25.4 / layout()->renderContext().dpi() ) * QgsSymbolLayerUtils::estimateMaxSymbolBleed( mPolygonStyleSymbol.get(), rc );
QgsRenderContext rc = QgsLayoutUtils::createRenderContextForLayout( lLayout, nullptr, lLayout->renderContext().dpi() );
mMaxSymbolBleed = ( 25.4 / lLayout->renderContext().dpi() ) * QgsSymbolLayerUtils::estimateMaxSymbolBleed( mPolygonStyleSymbol.get(), rc );
}

updateSceneRect();
Expand Down
6 changes: 3 additions & 3 deletions src/core/layout/qgslayoutitempolyline.cpp
Expand Up @@ -109,10 +109,10 @@ void QgsLayoutItemPolyline::createDefaultPolylineStyleSymbol()

void QgsLayoutItemPolyline::refreshSymbol()
{
if ( layout() )
if ( auto *lLayout = layout() )
{
QgsRenderContext rc = QgsLayoutUtils::createRenderContextForLayout( layout(), nullptr, layout()->renderContext().dpi() );
mMaxSymbolBleed = ( 25.4 / layout()->renderContext().dpi() ) * QgsSymbolLayerUtils::estimateMaxSymbolBleed( mPolylineStyleSymbol.get(), rc );
QgsRenderContext rc = QgsLayoutUtils::createRenderContextForLayout( lLayout, nullptr, lLayout->renderContext().dpi() );
mMaxSymbolBleed = ( 25.4 / lLayout->renderContext().dpi() ) * QgsSymbolLayerUtils::estimateMaxSymbolBleed( mPolylineStyleSymbol.get(), rc );
}

updateSceneRect();
Expand Down
6 changes: 3 additions & 3 deletions src/core/layout/qgslayoutitemshape.cpp
Expand Up @@ -119,10 +119,10 @@ void QgsLayoutItemShape::setShapeType( QgsLayoutItemShape::Shape type )

void QgsLayoutItemShape::refreshSymbol()
{
if ( layout() )
if ( auto *lLayout = layout() )
{
QgsRenderContext rc = QgsLayoutUtils::createRenderContextForLayout( layout(), nullptr, layout()->renderContext().dpi() );
mMaxSymbolBleed = ( 25.4 / layout()->renderContext().dpi() ) * QgsSymbolLayerUtils::estimateMaxSymbolBleed( mShapeStyleSymbol.get(), rc );
QgsRenderContext rc = QgsLayoutUtils::createRenderContextForLayout( lLayout, nullptr, lLayout->renderContext().dpi() );
mMaxSymbolBleed = ( 25.4 / lLayout->renderContext().dpi() ) * QgsSymbolLayerUtils::estimateMaxSymbolBleed( mShapeStyleSymbol.get(), rc );
}

updateBoundingRect();
Expand Down
10 changes: 5 additions & 5 deletions src/core/layout/qgsreportsectionfieldgroup.cpp
Expand Up @@ -125,12 +125,12 @@ QgsLayout *QgsReportSectionFieldGroup::nextBody( bool &ok )
// no features left for this iteration
mFeatures = QgsFeatureIterator();

if ( footer() )
if ( auto *lFooter = footer() )
{
footer()->reportContext().blockSignals( true );
footer()->reportContext().setLayer( mCoverageLayer.get() );
footer()->reportContext().blockSignals( false );
footer()->reportContext().setFeature( mLastFeature );
lFooter->reportContext().blockSignals( true );
lFooter->reportContext().setLayer( mCoverageLayer.get() );
lFooter->reportContext().blockSignals( false );
lFooter->reportContext().setFeature( mLastFeature );
}
ok = false;
return nullptr;
Expand Down
4 changes: 2 additions & 2 deletions src/core/mesh/qgsmeshlayer.cpp
Expand Up @@ -712,8 +712,8 @@ QgsMeshDatasetIndex QgsMeshLayer::staticVectorDatasetIndex() const

void QgsMeshLayer::setReferenceTime( const QDateTime &referenceTime )
{
if ( dataProvider() )
mTemporalProperties->setReferenceTime( referenceTime, dataProvider()->temporalCapabilities() );
if ( auto *lDataProvider = dataProvider() )
mTemporalProperties->setReferenceTime( referenceTime, lDataProvider->temporalCapabilities() );
else
mTemporalProperties->setReferenceTime( referenceTime, nullptr );
}
Expand Down

0 comments on commit 44466a3

Please sign in to comment.