SlideShare a Scribd company logo
Php Inspections (EA Extended)*:
If-statements optimization
* Intelligent Static Code Analyzer for JetBrains IDEs
Vladimir Reznichenko
Karlsruhe, 20 October 2016
What is Static Code Analysis about?
Static code analysis is about finding defects in source code *:
● Code Style violations (formatting, naming conventions and etc.);
● Implementation Defects (bugs, portability, performance and etc.);
● Security Issues (CVEs, API usage and etc.);
● Code Duplication;
● Code Metrics (e.g. Complexity, UTs coverage and etc.);
* and bytecode (e.g. FindBugs)
Php Inspections (EA Extended): what’s covered?
Challenges we met
● If-statements analysis:
○ Execution costs estimation;
○ Interconnected conditions; if (is_array($a) && $a[0] > 0) ;
○ Variadic constructions, booleans, identical sub-expressions detection and more;
● exceptions handling workflow analysis:
○ Simulation of the workflow for running analysis;
○ PhpDoc parsing: PHP is not supporting “throws” declarations;
○ Nested catch and finally has implementation issues in older PHP versions;
● analysis performance:
○ Concurrency (inspections are running in several independent threads);
○ GC: memory optimization (VisualVM, data structures);
○ Avoid low-performing analysis, stop as early as possible;
Challenges we met
● If-statements analysis:
○ Execution costs estimation;
○ Interconnected conditions;
○ Variadic constructions, booleans, identical sub-expressions detection and more;
If-statements analysis: patterns
● Execution costs: if ($var->method($a) && $b > 0) ;
● Identical operands: if ($a !== $a) ;
● Ambiguous type checks: if ($a instanceof Date || $a instanceof DateInterface) ;
● If ($a instanceof DateInterface && null !== $a) ;
● Variadic constructions: if (isset($a) && isset($b)) ; => if (isset($a, $b)) ;
● Hardcoded booleans: if ($a > 0 || true) ;
● Confusing conditions: if ($a > 0 || $a <= 0 && $a > $minValue) ;
● Duplicated expressions in elseif and nested ifs:
● If (is_array($a) || is_string($a)) {
● If (is_array($a) && count($a) > 0) ;
● }
Execution costs estimation: idea
The challenge has a name: “Shortest path problem” from Graphs theory (Discrete
mathematics).
Applying the problem e.g. to “if ($var->method($a) && $a > 0) ;” we have 2 paths:
● $var->method($a)
○ Method lookup ;
○ Calls stack: push and pop ;
○ Complex operation, therefore high execution costs ;
● $a > 0
○ Primitive operation, therefore low execution costs ;
Execution costs estimation: example
Let’s take more common case: if-else construct.
If (<conditions>) {
<operation 1>;
} else {
<operation 2>;
}
Formula for if-else construction cost estimation will be*:
C(<if-else>) = C(<conditions>) + max(C(<operation 1>), C(<operation 2>))
* The theory of parsing, translation, and compiling
Execution costs estimation: C() function
This is most important part: which weight to assign to different constructs?
For this you need know your compiler/interpreter internals and language
capabilities.
Example weights specific for PHP:
● Binary/Unary operations: 0 ; (primitive operations)
● Array access: +1 (hash-maps based arrays implementation) ;
● Method/function reference: +5 (call stack invocation) ;
● Lambdas: +10 (no JIT compiler, dynamically allocated) ;
● etc.
Code samples: hooking into IDE
public class NotOptimalIfConditionsInspection extends BasePhpInspection {
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new BasePhpElementVisitor() {
public void visitPhpIf(If ifStatement) {
/* we are visiting a branch of AST-tree here, analyze it */
}
/* other visitors here */
};
}
}
Code samples: processing conditions
LinkedList<PsiElement> conditions = <extraction_method>(ifStatement.getCondition(), operationHolder);
if (null != conditions ) {
allConditions.addAll(conditions);
/* invoke strategies */
conditions.clear();
}
for (ElseIf objElseIf : ifStatement.getElseIfBranches()) {
conditions = <extraction_method>(objElseIf.getCondition(), operationHolder);
if (null != conditions) {
allConditions.addAll(conditions);
/* invoke strategies */
conditions.clear();
}
}
<nested_ifs_duplicates_strategy>(allConditions, ifStatement);
Code samples: execution costs estimation
How to calculate execution costs for expression “$a->getConfig()[‘waf’]”
if (expression instanceof ArrayAccessExpression) {
final ArrayAccessExpression arrayAccess = (ArrayAccessExpression) expression;
final ArrayIndex arrayIndex = arrayAccess.getIndex();
int ownCosts = getExpressionCost(arrayAccess.getValue()); /* recursion: $a->getConfig() -> 5 */
if (null != arrayIndex) {
ownCosts += getExpressionCost(arrayIndex.getValue()); /* recursion: ‘waf’ -> 0 */
}
return (1 + ownCosts); /* -> 6 */
}
Thank you

More Related Content

What's hot

Unit iii
Unit iiiUnit iii
Unit iii
snehaarao19
 
Array strings
Array stringsArray strings
Array strings
Radhe Syam
 
Programming basics
Programming basicsProgramming basics
Programming basics
Bipin Adhikari
 
Storage classes
Storage classesStorage classes
Storage classes
Puneet Rajput
 
Exception handling
Exception handlingException handling
Exception handling
vishal choudhary
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage classkapil078
 
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
Chris Ohk
 
Storage classes in C
Storage classes in C Storage classes in C
Storage classes in C
Self employed
 
[C++ korea] effective modern c++ study item 3 understand decltype +이동우
[C++ korea] effective modern c++ study   item 3 understand decltype +이동우[C++ korea] effective modern c++ study   item 3 understand decltype +이동우
[C++ korea] effective modern c++ study item 3 understand decltype +이동우
Seok-joon Yun
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
GeorgePeterBanyard
 
Storage classes
Storage classesStorage classes
Storage classes
Leela Koneru
 
11 2. variable-scope rule,-storage_class
11 2. variable-scope rule,-storage_class11 2. variable-scope rule,-storage_class
11 2. variable-scope rule,-storage_class웅식 전
 
1 introduction to c program
1 introduction to c program1 introduction to c program
1 introduction to c program
NishmaNJ
 
Storage classes
Storage classesStorage classes
Storage classes
priyanka jain
 
Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5
Ismar Silveira
 
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source SoftwareThe Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
Andrey Karpov
 
Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2
Vasil Remeniuk
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
RichardWarburton
 
Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]
ppd1961
 

What's hot (20)

Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Array strings
Array stringsArray strings
Array strings
 
Programming basics
Programming basicsProgramming basics
Programming basics
 
Storage classes
Storage classesStorage classes
Storage classes
 
Exception handling
Exception handlingException handling
Exception handling
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage class
 
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
 
Storage classes in C
Storage classes in C Storage classes in C
Storage classes in C
 
[C++ korea] effective modern c++ study item 3 understand decltype +이동우
[C++ korea] effective modern c++ study   item 3 understand decltype +이동우[C++ korea] effective modern c++ study   item 3 understand decltype +이동우
[C++ korea] effective modern c++ study item 3 understand decltype +이동우
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
Storage classes
Storage classesStorage classes
Storage classes
 
11 2. variable-scope rule,-storage_class
11 2. variable-scope rule,-storage_class11 2. variable-scope rule,-storage_class
11 2. variable-scope rule,-storage_class
 
1 introduction to c program
1 introduction to c program1 introduction to c program
1 introduction to c program
 
Storage classes
Storage classesStorage classes
Storage classes
 
Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5
 
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source SoftwareThe Use of Static Code Analysis When Teaching or Developing Open-Source Software
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
 
Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2Scala laboratory: Globus. iteration #2
Scala laboratory: Globus. iteration #2
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]
 

Viewers also liked

PROCESO ENFERMERO DE ALZHEIMER.
PROCESO ENFERMERO DE ALZHEIMER.PROCESO ENFERMERO DE ALZHEIMER.
PROCESO ENFERMERO DE ALZHEIMER.
Teniente Fantasma
 
PROCESO ENFERMERO DE ALZHEIMER.
PROCESO ENFERMERO DE ALZHEIMER.PROCESO ENFERMERO DE ALZHEIMER.
PROCESO ENFERMERO DE ALZHEIMER.
Teniente Fantasma
 
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
Teniente Fantasma
 
EvolvingIntoNextGenerationTravelRetailing_APR_2005
EvolvingIntoNextGenerationTravelRetailing_APR_2005EvolvingIntoNextGenerationTravelRetailing_APR_2005
EvolvingIntoNextGenerationTravelRetailing_APR_2005Yannis Karmis
 
DEMOGRAFÍA DINÁMICA, VARIABLES DEMOGRÁFICAS, MORTALIDAD, FECUNDIDAD Y MOVIMIE...
DEMOGRAFÍA DINÁMICA, VARIABLES DEMOGRÁFICAS, MORTALIDAD, FECUNDIDAD Y MOVIMIE...DEMOGRAFÍA DINÁMICA, VARIABLES DEMOGRÁFICAS, MORTALIDAD, FECUNDIDAD Y MOVIMIE...
DEMOGRAFÍA DINÁMICA, VARIABLES DEMOGRÁFICAS, MORTALIDAD, FECUNDIDAD Y MOVIMIE...
Teniente Fantasma
 
15. bibliografía
15. bibliografía15. bibliografía
15. bibliografía
qrovira15
 
Notes from &quot;geology: earth history: mesozoic, cenozoic&quot;
Notes from &quot;geology: earth history: mesozoic, cenozoic&quot;Notes from &quot;geology: earth history: mesozoic, cenozoic&quot;
Notes from &quot;geology: earth history: mesozoic, cenozoic&quot;
Jennifer Wall
 
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
Teniente Fantasma
 
Tangoが切り開く MRの世界と日本における最新開発事例
Tangoが切り開く MRの世界と日本における最新開発事例Tangoが切り開く MRの世界と日本における最新開発事例
Tangoが切り開く MRの世界と日本における最新開発事例
Hirokazu Egashira
 
Slido - Audience Interaction Made Easy
Slido - Audience Interaction Made EasySlido - Audience Interaction Made Easy
Slido - Audience Interaction Made Easy
Slido
 
Space Explorations Around the World
Space Explorations Around the WorldSpace Explorations Around the World
Space Explorations Around the World
Maps of World
 
もっとデータ可視化をカジュアルに! OSSプロジェクト「E2D3」
もっとデータ可視化をカジュアルに! OSSプロジェクト「E2D3」もっとデータ可視化をカジュアルに! OSSプロジェクト「E2D3」
もっとデータ可視化をカジュアルに! OSSプロジェクト「E2D3」
Hideyuki Takeuchi
 
Arabic 3: Basics on the nominal sentence
Arabic 3: Basics on the nominal sentence Arabic 3: Basics on the nominal sentence
Arabic 3: Basics on the nominal sentence
Mohamed ZAIM
 
How to draw a water lily cach ve hoa sung
How to draw  a water lily   cach ve hoa sungHow to draw  a water lily   cach ve hoa sung
How to draw a water lily cach ve hoa sung
tieuhocvn .info
 
Aws x line x line bot awards
Aws x line x line bot awardsAws x line x line bot awards
Aws x line x line bot awards
Masatoshi Hiraoka
 
How to draw a bottle - Vẽ cái chai
How to draw a bottle - Vẽ cái chaiHow to draw a bottle - Vẽ cái chai
How to draw a bottle - Vẽ cái chai
tieuhocvn .info
 

Viewers also liked (16)

PROCESO ENFERMERO DE ALZHEIMER.
PROCESO ENFERMERO DE ALZHEIMER.PROCESO ENFERMERO DE ALZHEIMER.
PROCESO ENFERMERO DE ALZHEIMER.
 
PROCESO ENFERMERO DE ALZHEIMER.
PROCESO ENFERMERO DE ALZHEIMER.PROCESO ENFERMERO DE ALZHEIMER.
PROCESO ENFERMERO DE ALZHEIMER.
 
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
 
EvolvingIntoNextGenerationTravelRetailing_APR_2005
EvolvingIntoNextGenerationTravelRetailing_APR_2005EvolvingIntoNextGenerationTravelRetailing_APR_2005
EvolvingIntoNextGenerationTravelRetailing_APR_2005
 
DEMOGRAFÍA DINÁMICA, VARIABLES DEMOGRÁFICAS, MORTALIDAD, FECUNDIDAD Y MOVIMIE...
DEMOGRAFÍA DINÁMICA, VARIABLES DEMOGRÁFICAS, MORTALIDAD, FECUNDIDAD Y MOVIMIE...DEMOGRAFÍA DINÁMICA, VARIABLES DEMOGRÁFICAS, MORTALIDAD, FECUNDIDAD Y MOVIMIE...
DEMOGRAFÍA DINÁMICA, VARIABLES DEMOGRÁFICAS, MORTALIDAD, FECUNDIDAD Y MOVIMIE...
 
15. bibliografía
15. bibliografía15. bibliografía
15. bibliografía
 
Notes from &quot;geology: earth history: mesozoic, cenozoic&quot;
Notes from &quot;geology: earth history: mesozoic, cenozoic&quot;Notes from &quot;geology: earth history: mesozoic, cenozoic&quot;
Notes from &quot;geology: earth history: mesozoic, cenozoic&quot;
 
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
INTRODUCCIÓN Y CONCLUSIÓN DE PSICOLOGÍA SOCIAL.
 
Tangoが切り開く MRの世界と日本における最新開発事例
Tangoが切り開く MRの世界と日本における最新開発事例Tangoが切り開く MRの世界と日本における最新開発事例
Tangoが切り開く MRの世界と日本における最新開発事例
 
Slido - Audience Interaction Made Easy
Slido - Audience Interaction Made EasySlido - Audience Interaction Made Easy
Slido - Audience Interaction Made Easy
 
Space Explorations Around the World
Space Explorations Around the WorldSpace Explorations Around the World
Space Explorations Around the World
 
もっとデータ可視化をカジュアルに! OSSプロジェクト「E2D3」
もっとデータ可視化をカジュアルに! OSSプロジェクト「E2D3」もっとデータ可視化をカジュアルに! OSSプロジェクト「E2D3」
もっとデータ可視化をカジュアルに! OSSプロジェクト「E2D3」
 
Arabic 3: Basics on the nominal sentence
Arabic 3: Basics on the nominal sentence Arabic 3: Basics on the nominal sentence
Arabic 3: Basics on the nominal sentence
 
How to draw a water lily cach ve hoa sung
How to draw  a water lily   cach ve hoa sungHow to draw  a water lily   cach ve hoa sung
How to draw a water lily cach ve hoa sung
 
Aws x line x line bot awards
Aws x line x line bot awardsAws x line x line bot awards
Aws x line x line bot awards
 
How to draw a bottle - Vẽ cái chai
How to draw a bottle - Vẽ cái chaiHow to draw a bottle - Vẽ cái chai
How to draw a bottle - Vẽ cái chai
 

Similar to Php Inspections (EA Extended): if-conditions optimization

Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing Speed
Pascal-Louis Perez
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
Fwdays
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
Nikita Popov
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
Codemotion
 
Core2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdfCore2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdf
ThchTrngGia
 
Php basics
Php basicsPhp basics
Php basics
Hewitt VS
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
Rodolfo Carvalho
 
Apache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationApache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customization
Bartosz Konieczny
 
Code metrics in PHP
Code metrics in PHPCode metrics in PHP
Code metrics in PHP
Julio Martinez
 
Maintainable JavaScript
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScript
Nicholas Zakas
 
Node js
Node jsNode js
Node jshazzaz
 
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Data Con LA
 
Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...
Andreas Dewes
 
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tipsAndriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
OWASP Kyiv
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your Code
Nate Abele
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0
Nate Abele
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
RichardWarburton
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
Rowan Merewood
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
Guillaume Laforge
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
Jonathan Felch
 

Similar to Php Inspections (EA Extended): if-conditions optimization (20)

Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing Speed
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
Core2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdfCore2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdf
 
Php basics
Php basicsPhp basics
Php basics
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
Apache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customizationApache Spark in your likeness - low and high level customization
Apache Spark in your likeness - low and high level customization
 
Code metrics in PHP
Code metrics in PHPCode metrics in PHP
Code metrics in PHP
 
Maintainable JavaScript
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScript
 
Node js
Node jsNode js
Node js
 
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
Big Data Day LA 2015 - Compiling DSLs for Diverse Execution Environments by Z...
 
Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...
 
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tipsAndriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
 
Measuring Your Code
Measuring Your CodeMeasuring Your Code
Measuring Your Code
 
Measuring Your Code 2.0
Measuring Your Code 2.0Measuring Your Code 2.0
Measuring Your Code 2.0
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 

Recently uploaded

一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
SupreethSP4
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 

Recently uploaded (20)

一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Runway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptxRunway Orientation Based on the Wind Rose Diagram.pptx
Runway Orientation Based on the Wind Rose Diagram.pptx
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
H.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdfH.Seo,  ICLR 2024, MLILAB,  KAIST AI.pdf
H.Seo, ICLR 2024, MLILAB, KAIST AI.pdf
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 

Php Inspections (EA Extended): if-conditions optimization

  • 1. Php Inspections (EA Extended)*: If-statements optimization * Intelligent Static Code Analyzer for JetBrains IDEs Vladimir Reznichenko Karlsruhe, 20 October 2016
  • 2. What is Static Code Analysis about? Static code analysis is about finding defects in source code *: ● Code Style violations (formatting, naming conventions and etc.); ● Implementation Defects (bugs, portability, performance and etc.); ● Security Issues (CVEs, API usage and etc.); ● Code Duplication; ● Code Metrics (e.g. Complexity, UTs coverage and etc.); * and bytecode (e.g. FindBugs)
  • 3. Php Inspections (EA Extended): what’s covered?
  • 4. Challenges we met ● If-statements analysis: ○ Execution costs estimation; ○ Interconnected conditions; if (is_array($a) && $a[0] > 0) ; ○ Variadic constructions, booleans, identical sub-expressions detection and more; ● exceptions handling workflow analysis: ○ Simulation of the workflow for running analysis; ○ PhpDoc parsing: PHP is not supporting “throws” declarations; ○ Nested catch and finally has implementation issues in older PHP versions; ● analysis performance: ○ Concurrency (inspections are running in several independent threads); ○ GC: memory optimization (VisualVM, data structures); ○ Avoid low-performing analysis, stop as early as possible;
  • 5. Challenges we met ● If-statements analysis: ○ Execution costs estimation; ○ Interconnected conditions; ○ Variadic constructions, booleans, identical sub-expressions detection and more;
  • 6. If-statements analysis: patterns ● Execution costs: if ($var->method($a) && $b > 0) ; ● Identical operands: if ($a !== $a) ; ● Ambiguous type checks: if ($a instanceof Date || $a instanceof DateInterface) ; ● If ($a instanceof DateInterface && null !== $a) ; ● Variadic constructions: if (isset($a) && isset($b)) ; => if (isset($a, $b)) ; ● Hardcoded booleans: if ($a > 0 || true) ; ● Confusing conditions: if ($a > 0 || $a <= 0 && $a > $minValue) ; ● Duplicated expressions in elseif and nested ifs: ● If (is_array($a) || is_string($a)) { ● If (is_array($a) && count($a) > 0) ; ● }
  • 7. Execution costs estimation: idea The challenge has a name: “Shortest path problem” from Graphs theory (Discrete mathematics). Applying the problem e.g. to “if ($var->method($a) && $a > 0) ;” we have 2 paths: ● $var->method($a) ○ Method lookup ; ○ Calls stack: push and pop ; ○ Complex operation, therefore high execution costs ; ● $a > 0 ○ Primitive operation, therefore low execution costs ;
  • 8. Execution costs estimation: example Let’s take more common case: if-else construct. If (<conditions>) { <operation 1>; } else { <operation 2>; } Formula for if-else construction cost estimation will be*: C(<if-else>) = C(<conditions>) + max(C(<operation 1>), C(<operation 2>)) * The theory of parsing, translation, and compiling
  • 9. Execution costs estimation: C() function This is most important part: which weight to assign to different constructs? For this you need know your compiler/interpreter internals and language capabilities. Example weights specific for PHP: ● Binary/Unary operations: 0 ; (primitive operations) ● Array access: +1 (hash-maps based arrays implementation) ; ● Method/function reference: +5 (call stack invocation) ; ● Lambdas: +10 (no JIT compiler, dynamically allocated) ; ● etc.
  • 10. Code samples: hooking into IDE public class NotOptimalIfConditionsInspection extends BasePhpInspection { @Override public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) { return new BasePhpElementVisitor() { public void visitPhpIf(If ifStatement) { /* we are visiting a branch of AST-tree here, analyze it */ } /* other visitors here */ }; } }
  • 11. Code samples: processing conditions LinkedList<PsiElement> conditions = <extraction_method>(ifStatement.getCondition(), operationHolder); if (null != conditions ) { allConditions.addAll(conditions); /* invoke strategies */ conditions.clear(); } for (ElseIf objElseIf : ifStatement.getElseIfBranches()) { conditions = <extraction_method>(objElseIf.getCondition(), operationHolder); if (null != conditions) { allConditions.addAll(conditions); /* invoke strategies */ conditions.clear(); } } <nested_ifs_duplicates_strategy>(allConditions, ifStatement);
  • 12. Code samples: execution costs estimation How to calculate execution costs for expression “$a->getConfig()[‘waf’]” if (expression instanceof ArrayAccessExpression) { final ArrayAccessExpression arrayAccess = (ArrayAccessExpression) expression; final ArrayIndex arrayIndex = arrayAccess.getIndex(); int ownCosts = getExpressionCost(arrayAccess.getValue()); /* recursion: $a->getConfig() -> 5 */ if (null != arrayIndex) { ownCosts += getExpressionCost(arrayIndex.getValue()); /* recursion: ‘waf’ -> 0 */ } return (1 + ownCosts); /* -> 6 */ }