Commit d909aaff authored by Gerson SUNYE's avatar Gerson SUNYE
Browse files

Merge branch 'fix/correction_string_tostring' into 'master'

Correction #904 String toString

Closes #904

See merge request naomod/mde/projet-2019!159
parents 2d3a3528 a872a2f2
...@@ -91,6 +91,7 @@ helper def: allMeasures(project : java!Model): Set(smm!Measure) = ...@@ -91,6 +91,7 @@ helper def: allMeasures(project : java!Model): Set(smm!Measure) =
thisModule.integerInstantiation(), thisModule.integerInstantiation(),
-- #FIXME: -- #FIXME:
-- thisModule.startsWith(), -- thisModule.startsWith(),
thisModule.stringToString(),
thisModule.tooFewBranchesForASwitchStatement(), thisModule.tooFewBranchesForASwitchStatement(),
-- #FIXME: thisModule.useArraysAsList(), -- #FIXME: thisModule.useArraysAsList(),
thisModule.useIndexOfChar(), thisModule.useIndexOfChar(),
...@@ -152,7 +153,6 @@ helper def: allMeasures(project : java!Model): Set(smm!Measure) = ...@@ -152,7 +153,6 @@ helper def: allMeasures(project : java!Model): Set(smm!Measure) =
-- thisModule.replaceVectorToList() -- thisModule.replaceVectorToList()
-- thisModule.unusedPrivateMethod () -- thisModule.unusedPrivateMethod ()
-- thisModule.avoidThrowingNewInstanceOfSameException(), -- thisModule.avoidThrowingNewInstanceOfSameException(),
-- thisModule.stringToString(),
-- thisModule.methodWithSameNameAsEnclosingClass(), -- thisModule.methodWithSameNameAsEnclosingClass(),
-- thisModule.dontUseFloatTypeForLoopIndices(), -- thisModule.dontUseFloatTypeForLoopIndices(),
-- thisModule.methodWithSameNameAsEnclosingClass(), -- thisModule.methodWithSameNameAsEnclosingClass(),
...@@ -1895,6 +1895,25 @@ rule MesureShortVariableName(variable : java!VariableDeclaration) { ...@@ -1895,6 +1895,25 @@ rule MesureShortVariableName(variable : java!VariableDeclaration) {
} }
} }
--- Creates a new Measure when the method toString() is unnecessarily invoked.
rule MeasureStringToString(method : java!MethodInvocation) {
to
om: smm!ObservedMeasure (
measure <- noc,
measurements <- measurement
),
noc: smm!DimensionalMeasure (
name <- 'StringToString',
shortDescription <- 'Avoid calling toString() on objects already known to be string instances; this is unnecessary.'
),
measurement: smm!DirectMeasurement (
error <- 'The Object ' + method.expression.variable.name + ' is already a String in ' + method.originalCompilationUnit.name
)
do {
noc;
}
}
--- A Measure instance if the class violates the rule 'TooManyFields'. --- A Measure instance if the class violates the rule 'TooManyFields'.
-- #FIXME: Typo -- #FIXME: Typo
rule MesureTooManyFields(class : java!ClassDeclaration) { rule MesureTooManyFields(class : java!ClassDeclaration) {
...@@ -2084,7 +2103,3 @@ helper context java!FieldDeclaration def: getBodyDeclarationName() : String = ...@@ -2084,7 +2103,3 @@ helper context java!FieldDeclaration def: getBodyDeclarationName() : String =
-- ATTENTION !!! -- ATTENTION !!!
-- Before adding a new rule in the end of the file, remember that rules respect an alphabetical order. -- Before adding a new rule in the end of the file, remember that rules respect an alphabetical order.
\ No newline at end of file
library performance; library performance;
--------------------------------------------- UselessStringValueOf--------------------------------------------- --- AddEmptyString
helper def: addEmptyString() : Set(smm!Measure) =
--Goes through all the methods to check if the following rule is followed: java!InfixExpression.allInstances()
--No need to call String.valueOf to append to a string; just use the valueOf() argument directly. ->select(expression | expression.operator.name = '+')
helper def: uselessStringValueOf() : Set(smm!Measure) = ->select(expression | (expression.leftOperand.oclIsTypeOf(java!StringLiteral) and expression.rightOperand.oclIsTypeOf(java!NumberLiteral)) or (expression.leftOperand.oclIsTypeOf(java!NumberLiteral) and expression.rightOperand.oclIsTypeOf(java!StringLiteral)))
java!MethodInvocation.allInstances() ->collect(expression | thisModule.MesureAddEmptyString(expression.originalCompilationUnit))
-> select (m | m.method.name='valueOf' )
-> select (m | m.refImmediateComposite().oclIsTypeOf(java!InfixExpression))
-> collect (m | thisModule.MeasureUselessStringValueOf(m));
------------------------------------ TooFewBranchesForASwitchStatement--------------------------------------
-- Returns a set of measures for each switch statement that violates the rule : number of switch cases < 3
-- To test, use input model : tooFewBranchesForASwitchStatement.xmi
helper def: tooFewBranchesForASwitchStatement(): Set(smm!Measure) =
-- If the number of switch cases for the current switch statement is < 3 then add a new measure to the set
java!SwitchStatement.allInstances()
-> select (switchStatement | thisModule.nbBranchesOfASwitchStatement(switchStatement) < 3)
-> collect (switchStatement | thisModule.MeasureTooFewBranchesForASwitchStatement(switchStatement))
; ;
--------------------------------------------- UseIndexOfChar--------------------------------------------- --- AvoidInstantiatingObjectInLoops
helper def: avoidInstantiatingObjectsInLoops(): Set(smm!Measure) =
java!Statement.allInstances()
->select(s | s.oclIsTypeOf(java!ForStatement) or s.oclIsTypeOf(java!DoStatement) or s.oclIsTypeOf(java!WhileStatement))
->select(s | s.body.statements
->select(s2 | s2.oclIsTypeOf(java!VariableDeclarationStatement))
->select(s2 | s2.fragments->exists(f | f.oclIsTypeOf(java!VariableDeclarationFragment)))
->exists(s2 | s2.fragments->exists(f | f.initializer.oclIsTypeOf(java!ClassInstanceCreation)))
)
->collect(s | thisModule.MeasureAvoidInstantiatingObjectInLoops(s))
;
--Goes through all the MethodInvocation to check if the following rule is followed: --- AvoidRethrowingException
--Use String.indexOf(char) when checking for the index of a single character; it executes faster. -- Rule for metrics AvoidRethrowingException :
helper def: useIndexOfChar() : Set(smm!Measure) = helper def: avoidRethrowingException() : Set (smm!Measure) =
java!MethodInvocation.allInstances() -- Browse through all try statements
-> select (m | m.method.name='indexOf') java!TryStatement.allInstances() ->iterate(tryStatement; res : Set(smm!Measure) = Set{} |
-> select (m | m.arguments.size() = 1) tryStatement.catchClauses
-> select (m | not m.arguments.first().oclIsTypeOf(java!CharacterLiteral)) ->select(catchClause | catchClause.body <> OclUndefined and catchClause.body.statements.size() = 1)
-> collect (m | thisModule.MeasureUseIndexOfChar(m)) ->collect(catchClause | catchClause.body.statements)
->iterate(catchStatement; res1 : Set(smm!Measure) = Set{} |
catchStatement
->select(catchState | catchState.oclIsTypeOf(java!ThrowStatement))
->collect(catchState | thisModule.MeasureAvoidRethrowingException(catchState))
)
)
; ;
--------------------------------------------- avoidThrowingNewInstanceOfSameException --------------------------------------------- --- AvoidThrowingNewInstanceOfSameException
-- Returns a set of Measures for each catch block throws a new instance of the caught exception -- Returns a set of Measures for each catch block throws a new instance of the caught exception
helper def: avoidThrowingNewInstanceOfSameException() : Set(smm!Measure) = helper def: avoidThrowingNewInstanceOfSameException() : Set(smm!Measure) =
java!CatchClause.allInstances() ->iterate(catch; catchRes : Set(smm!Measure) = Set{} | java!CatchClause.allInstances() ->iterate(catch; catchRes : Set(smm!Measure) = Set{} |
...@@ -51,107 +54,39 @@ helper def: avoidThrowingNewInstanceOfSameException() : Set(smm!Measure) = ...@@ -51,107 +54,39 @@ helper def: avoidThrowingNewInstanceOfSameException() : Set(smm!Measure) =
) )
else catchRes else catchRes
endif endif
); )
;
--------------------------------------------- AvoidUsingShortType---------------------------------------------
--Detects the use of the primitive type 'short' for rule AvoidUsingShortType. Prefer the use of 'int' instead of 'short'. --- AvoidUsingShortType
-- Detects the use of the primitive type 'short' for rule AvoidUsingShortType. Prefer the use of 'int' instead of 'short'.
helper def: avoidUsingShortType() : Set(smm!Measure) = helper def: avoidUsingShortType() : Set(smm!Measure) =
java!VariableDeclarationStatement.allInstances() java!VariableDeclarationStatement.allInstances()
->select(variable | variable.type.type.name = 'short') ->select(variable | variable.type.type.name = 'short')
->collect(variable | thisModule.MeasureAvoidUsingShortType(variable)); ->collect(variable | thisModule.MeasureAvoidUsingShortType(variable))
;
--------------------------------------------- ShortInstantiation ---------------------------------------------
-- Rule for metrics ShortInstantiation : return the set of class Measures that violates the rule.
helper def: shortInstantiation() : Set(smm!Measure) =
-- Take all ClassInstanceCreation with allInstances()
java!ClassInstanceCreation.allInstances()
-- Select all class who declare a Short type
->select(it| it.method.oclIsTypeOf(java!ConstructorDeclaration) and it.method.name = 'Short')
-- collect every results and send an error message
->collect(it2|thisModule.MeasureShortInstantiation(it2.originalCompilationUnit))
;
--------------------------------------------- LongInstantiation ---------------------------------------------
-- Rule for metricsLongInstantiation : return the set of class Measures that violates the rule.
helper def: longInstantiation() : Set(smm!Measure) =
-- Take all ClassInstanceCreation with allInstances()
java!ClassInstanceCreation.allInstances()
-- Select all class who declare a Long type
->select(it| it.method.oclIsTypeOf(java!ConstructorDeclaration) and it.method.name = 'Long')
-- collect every results and send an error message
->collect(it2|thisModule.MeasureLongInstantiation(it2.originalCompilationUnit))
;
--------------------------------------------- AvoidRethrowingException ---------------------------------------------
-- Rule for metrics AvoidRethrowingException :
helper def: avoidRethrowingException() : Set (smm!Measure) =
-- Browse through all try statements
java!TryStatement.allInstances() ->iterate(tryStatement; res : Set(smm!Measure) = Set{} |
tryStatement.catchClauses
->select(catchClause | catchClause.body <> OclUndefined and catchClause.body.statements.size() = 1)
->collect(catchClause | catchClause.body.statements)
->iterate(catchStatement; res1 : Set(smm!Measure) = Set{} |
catchStatement
->select(catchState | catchState.oclIsTypeOf(java!ThrowStatement))
->collect(catchState | thisModule.MeasureAvoidRethrowingException(catchState))
)
);
--------------------------------------------- IntegerInstantiation ---------------------------------------------
-- Rule for metricsIntegerInstantiation : returns the set of class Measures that violates the rule.
helper def: integerInstantiation() : Set(smm!Measure) =
-- Take all ClassInstanceCreation with allInstances()
java!ClassInstanceCreation.allInstances()
-- Select all classes that declare an Integer type
->select(it|it.method.oclIsTypeOf(java!ConstructorDeclaration) and it.method.name = 'Integer')
-- collect every result and sends an error message
->collect(it2|thisModule.MeasureIntegerInstantiation(it2.originalCompilationUnit))
;
--------------------------------------------- Use ArrayList Instead Of Vector ---------------------------------------------
helper def: UseArrayListInsteadOfVector() : Set(smm!Measure) =
-- Browse through all class(CompilationUnit)
--On recupere tout les new Vector et on verifie que le Vector appelé appartient au package java.utile
java!ConstructorDeclaration.allInstances()->
collect(i|i.abstractTypeDeclaration)
->select(p|p.name='Vector')->collect(i|i.package)
->select(p|p.name='util')->collect(i|i.package)
->select(p|p.name='java')
->collect(i |thisModule.RuleUseArrayListInsteadOfVector(i));
--------------------------------------------- StringToString ---------------------------------------------
-- Rule for metrics stringToString : returns the set of class Measures that violates the rule.
helper def: stringToString() : Set(smm!Measure) =
java!MethodInvocation.allInstances()
-> select( i | i.method.name = 'toString' and i.expression.variable.variablesContainer.type.type.name = 'String')
-> collect ( i | thisModule.MeasureStringToString(i) )
;
--------------------------------------------- start with --------------------------------------------- --- InefficientEmptyStringCheck
helper def: startsWith() : Set(smm!Measure) = helper def: inefficientEmptyStringCheck() : Set(smm!Measure) =
-- Take all MethodInvocation with allInstances()
java!MethodInvocation.allInstances() java!MethodInvocation.allInstances()
->select(it| it.method.name= 'startsWith') ->select(i | i.method.name = 'isEmpty')
->select(it2| thisModule.isLengthUnder1(it2.arguments.first())) ->select(i | i.expression.oclIsTypeOf(java!MethodInvocation))
->collect(err|thisModule.MeasureStartWith(err)); ->select(i | thisModule.expressionMethodIs(i.expression,'trim'))
->collect(i | thisModule.MeasureInefficientEmptyStringCheck(i));
----- <=3 because we have to ignore '"' at begin and at end
helper def:isLengthUnder1(s:java!StringLiteral): Boolean =
s.escapedValue.size() <= 3 ;
--------------------------------------------- insufficientStringBufferDeclaration --------------------------------------------------------
helper def: inefficientEmptyStringCheck2() : Set(smm!Measure) =
java!InfixExpression.allInstances()
->select(i | i.rightOperand.oclIsTypeOf(java!NumberLiteral))
->select(i | i.rightOperand.tokenValue = '0')
->select(i | i.leftOperand.oclIsTypeOf(java!MethodInvocation))
->select(i | i.leftOperand.method.name = 'length')
->select(i | i.leftOperand.expression.oclIsTypeOf(java!MethodInvocation))
->select(i | i.leftOperand.expression.method.name = 'trim')
->collect(i | thisModule.MeasureInefficientEmptyStringCheck(i));
helper def: expressionMethodIs(expr: java!Expression,str: String) : Boolean =
expr.method.name = str;
--- InsufficientStringBufferDeclaration
helper def: insufficientStringBufferDeclaration() : Set(smm!Measure) = helper def: insufficientStringBufferDeclaration() : Set(smm!Measure) =
java!MethodInvocation.allInstances() java!MethodInvocation.allInstances()
->select(it| it.method.name = 'append') ->select(it| it.method.name = 'append')
...@@ -181,19 +116,77 @@ helper def:sizeOfLitteral(variable:java!StringLiteral): Integer = ...@@ -181,19 +116,77 @@ helper def:sizeOfLitteral(variable:java!StringLiteral): Integer =
helper def:sizeOf(variable:java!NumberLiteral): Integer = helper def:sizeOf(variable:java!NumberLiteral): Integer =
variable.tokenValue.toInteger(); variable.tokenValue.toInteger();
--- IntegerInstantiation
-- Rule for metricsIntegerInstantiation : returns the set of class Measures that violates the rule.
helper def: integerInstantiation() : Set(smm!Measure) =
-- Take all ClassInstanceCreation with allInstances()
java!ClassInstanceCreation.allInstances()
-- Select all classes that declare an Integer type
->select(it|it.method.oclIsTypeOf(java!ConstructorDeclaration) and it.method.name = 'Integer')
-- collect every result and sends an error message
->collect(it2|thisModule.MeasureIntegerInstantiation(it2.originalCompilationUnit))
;
--- LongInstantiation
-- Rule for metricsLongInstantiation : return the set of class Measures that violates the rule.
helper def: longInstantiation() : Set(smm!Measure) =
-- Take all ClassInstanceCreation with allInstances()
java!ClassInstanceCreation.allInstances()
-- Select all class who declare a Long type
->select(it| it.method.oclIsTypeOf(java!ConstructorDeclaration) and it.method.name = 'Long')
-- collect every results and send an error message
->collect(it2|thisModule.MeasureLongInstantiation(it2.originalCompilationUnit))
;
------------------------------------------- AddEmptyString ------------------------------------------------------------------------------------ --- ShortInstantiation
-- Rule for metrics ShortInstantiation : return the set of class Measures that violates the rule.
helper def: shortInstantiation() : Set(smm!Measure) =
-- Take all ClassInstanceCreation with allInstances()
java!ClassInstanceCreation.allInstances()
-- Select all class who declare a Short type
->select(it| it.method.oclIsTypeOf(java!ConstructorDeclaration) and it.method.name = 'Short')
-- collect every results and send an error message
->collect(it2|thisModule.MeasureShortInstantiation(it2.originalCompilationUnit))
;
helper def: addEmptyString() : Set(smm!Measure) = --- Start with
java!InfixExpression.allInstances() helper def: startsWith() : Set(smm!Measure) =
->select(expression | expression.operator.name = '+') -- Take all MethodInvocation with allInstances()
->select(expression | (expression.leftOperand.oclIsTypeOf(java!StringLiteral) and expression.rightOperand.oclIsTypeOf(java!NumberLiteral)) or (expression.leftOperand.oclIsTypeOf(java!NumberLiteral) and expression.rightOperand.oclIsTypeOf(java!StringLiteral))) java!MethodInvocation.allInstances()
->collect(expression | thisModule.MesureAddEmptyString(expression.originalCompilationUnit)); ->select(it| it.method.name= 'startsWith')
->select(it2| thisModule.isLengthUnder1(it2.arguments.first()))
->collect(err|thisModule.MeasureStartWith(err))
;
-- <=3 because we have to ignore '"' at begin and at end
helper def:isLengthUnder1(s:java!StringLiteral): Boolean =
s.escapedValue.size() <= 3
;
--- StringToString
-- Rule for metrics stringToString : returns the set of class Measures that violates the rule.
helper def: stringToString() : Set(smm!Measure) =
java!MethodInvocation.allInstances()
-> select( i | i.method.name = 'toString')
-> select( i | i.expression.oclIsTypeOf(java!SingleVariableAccess))
-> select( i | i.expression.variable.oclIsTypeOf(java!VariableDeclarationFragment))
-> select( i | not i.expression.variable.variablesContainer.type.oclIsUndefined())
-> select( i | not i.expression.variable.variablesContainer.type.type.oclIsUndefined())
-> select( i | i.expression.variable.variablesContainer.type.type.name = 'String')
-> collect ( i | thisModule.MeasureStringToString(i) )
;
------------------------------------------- UseArraysAsList ------------------------------------------------------------------------------------ --- TooFewBranchesForASwitchStatement
-- Returns a set of measures for each switch statement that violates the rule : number of switch cases < 3
-- To test, use input model : tooFewBranchesForASwitchStatement.xmi
helper def: tooFewBranchesForASwitchStatement(): Set(smm!Measure) =
-- If the number of switch cases for the current switch statement is < 3 then add a new measure to the set
java!SwitchStatement.allInstances()
-> select (switchStatement | thisModule.nbBranchesOfASwitchStatement(switchStatement) < 3)
-> collect (switchStatement | thisModule.MeasureTooFewBranchesForASwitchStatement(switchStatement))
;
--- UseArraysAsList
helper def: useArraysAsList() : Set(smm!Measure) = helper def: useArraysAsList() : Set(smm!Measure) =
java!ForStatement.allInstances() java!ForStatement.allInstances()
->select(st | st.body.statements.size() = 1) ->select(st | st.body.statements.size() = 1)
...@@ -205,39 +198,38 @@ helper def: useArraysAsList() : Set(smm!Measure) = ...@@ -205,39 +198,38 @@ helper def: useArraysAsList() : Set(smm!Measure) =
->select(st | st.body.statements.get(0).expression.arguments.size() = 1 ->select(st | st.body.statements.get(0).expression.arguments.size() = 1
and st.body.statements.get(0).expression.arguments.get(0).oclIsTypeOf(java!ArrayAccess)) and st.body.statements.get(0).expression.arguments.get(0).oclIsTypeOf(java!ArrayAccess))
->select(st | st.body.statements.get(0).expression.arguments.get(0).array.variable.type.type.oclIsTypeOf(java!ArrayType)) ->select(st | st.body.statements.get(0).expression.arguments.get(0).array.variable.type.type.oclIsTypeOf(java!ArrayType))
->collect(st | thisModule.MeasureUseArraysAsList(st.originalCompilationUnit)); ->collect(st | thisModule.MeasureUseArraysAsList(st.originalCompilationUnit))
;
------------------------------------------- InefficientEmptyStringCheck ------------------------------------------------------------------------------------ --- Use ArrayList Instead Of Vector
helper def: UseArrayListInsteadOfVector() : Set(smm!Measure) =
-- Browse through all class(CompilationUnit)
-- On recupere tout les new Vector et on verifie que le Vector appelé appartient au package java.utile
java!ConstructorDeclaration.allInstances()->
collect(i|i.abstractTypeDeclaration)
->select(p|p.name='Vector')->collect(i|i.package)
->select(p|p.name='util')->collect(i|i.package)
->select(p|p.name='java')
->collect(i |thisModule.RuleUseArrayListInsteadOfVector(i))
;
helper def: inefficientEmptyStringCheck() : Set(smm!Measure) = --- UseIndexOfChar
--Goes through all the MethodInvocation to check if the following rule is followed:
--Use String.indexOf(char) when checking for the index of a single character; it executes faster.
helper def: useIndexOfChar() : Set(smm!Measure) =
java!MethodInvocation.allInstances() java!MethodInvocation.allInstances()
->select(i | i.method.name = 'isEmpty') -> select (m | m.method.name='indexOf')
->select(i | i.expression.oclIsTypeOf(java!MethodInvocation)) -> select (m | m.arguments.size() = 1)
->select(i | thisModule.expressionMethodIs(i.expression,'trim')) -> select (m | not m.arguments.first().oclIsTypeOf(java!CharacterLiteral))
->collect(i | thisModule.MeasureInefficientEmptyStringCheck(i)); -> collect (m | thisModule.MeasureUseIndexOfChar(m))
;
helper def: inefficientEmptyStringCheck2() : Set(smm!Measure) =
java!InfixExpression.allInstances()
->select(i | i.rightOperand.oclIsTypeOf(java!NumberLiteral))
->select(i | i.rightOperand.tokenValue = '0')
->select(i | i.leftOperand.oclIsTypeOf(java!MethodInvocation))
->select(i | i.leftOperand.method.name = 'length')
->select(i | i.leftOperand.expression.oclIsTypeOf(java!MethodInvocation))
->select(i | i.leftOperand.expression.method.name = 'trim')
->collect(i | thisModule.MeasureInefficientEmptyStringCheck(i));
helper def: expressionMethodIs(expr: java!Expression,str: String) : Boolean =
expr.method.name = str;
--------------------------------------------- AvoidInstantiatingObjectInLoops ---------------------------------------------
helper def: avoidInstantiatingObjectsInLoops(): Set(smm!Measure) = --- UselessStringValueOf
java!Statement.allInstances() --Goes through all the methods to check if the following rule is followed:
->select(s | s.oclIsTypeOf(java!ForStatement) or s.oclIsTypeOf(java!DoStatement) or s.oclIsTypeOf(java!WhileStatement)) --No need to call String.valueOf to append to a string; just use the valueOf() argument directly.
->select(s | s.body.statements helper def: uselessStringValueOf() : Set(smm!Measure) =
->select(s2 | s2.oclIsTypeOf(java!VariableDeclarationStatement)) java!MethodInvocation.allInstances()
->select(s2 | s2.fragments->exists(f | f.oclIsTypeOf(java!VariableDeclarationFragment))) -> select (m | m.method.name='valueOf' )
->exists(s2 | s2.fragments->exists(f | f.initializer.oclIsTypeOf(java!ClassInstanceCreation))) -> select (m | m.refImmediateComposite().oclIsTypeOf(java!InfixExpression))
) -> collect (m | thisModule.MeasureUselessStringValueOf(m))
->collect(s | thisModule.MeasureAvoidInstantiatingObjectInLoops(s)); ;
\ No newline at end of file \ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment