SlideShare a Scribd company logo
Applying Compiler Techniques to Iterate at Blazing Speed @pascallouis julien@kaching.com
Engineering at kaChing TDD from day one Full regression suite runs in less than 3 minutes Deploy to production 30+ times a day People have written and launched new features during interview process
Agenda Apply Compiler Techniques ? Profit!
Seriously… (Java focused) Software Analysis Anatomy of a compiler Creating meta tests  Leveraging Types Levels of interpretation Descriptors and signatures DRY your code (less bugs, greater reach for experts, higher testability)
Software Analysis Running a series of analyses on the code base. Catch common mistakes due to distracted developers, new hires or bad APIs.
Anatomy of a Compiler Annotated Abstract Syntax Tree Semantic Analysis Intermediate Representation Generation Intermediate Representation Abstract Syntax Tree Syntactic Analysis Optimization Optimized Intermediate  Representation Tokens Lexical Analysis Machine Code Generation Target Code Source Code
int x 1;  int y x + 2; Lexical Analysis IDENT(int) IDENT(x) ASGN NUMBER(1) SEMICOLON IDENT(int) IDENT(y) ASGN IDENT(x) PLUS NUMBER(2) SEMICOLON
IDENT(int) IDENT(x) ASGN NUMBER(1) SEMICOLON IDENT(int) IDENT(y) ASGN IDENT(x) PLUS NUMBER(2) SEMICOLON Syntactic Analysis PROGRAM(   LET(x, int, 1),   LET(y, int, PLUS(x, 2)))
PROGRAM(   LET(x, int, 1),   LET(y, int, PLUS(x, 2))) Semantic Analysis: Symbols PROGRAM(   LET(x, int, 1),   LET(y, int, PLUS(x, 2)))
PROGRAM(   LET(x, int, 1),   LET(y, int, PLUS(x, 2))) Semantic Analysis: Types PROGRAM(   LET(x: int, int, 1: int),   LET(y: int, int, PLUS(x: int, 2: int): int))
Optimizations Simple optimizations can be done on the Abstract Syntax Tree Other optimizations require specialized representations Static Single Assignment form Control Flow Graph
PROGRAM(   LET(x: int, int, 1: int),   LET(y: int, int, PLUS(3: int, 2: int): int)) Constant folding PROGRAM(   LET(x: int, int, 1: int),   LET(y: int, int, 5: int))
int x1 (a1 + b1) / c1;  int y1(a1+ b1) / d1; Common sub-expression elimination int temp  a + b; int x  temp / d; inty  temp / d;
int x1 (a1 + b1) / c1; a2a1 + 1; int y1(a2+ b1) / d1; Common sub-expression elimination intx (a + b) / c; a  a + 1; inty (a + b) / d;
Anatomy of a Compiler Semantic Analysis Intermediate Representation Generation Syntactic Analysis Optimization Lexical Analysis Machine Code Generation
javac Target Code Source Code
PMD Annotated Abstract Syntax Tree Source Code
joeq Intermediate Representation Source Code
scalac Semantic Analysis Intermediate Representation Generation Syntactic Analysis Optimization Lexical Analysis Machine Code Generation
Finding bad code snippets Describe bad code snippets using regular expressions. Analysis done on the source code, before lexical analysis as information such as whitespaces are lost.  Extremely easy to implement.
@CodeSnippets({ @Check(paths = {"src", "srctest"}, snippets = { @Snippet("bif("), @Snippet("super()")     }, @Check(paths = {"srctest"}, snippets = { @Snippet("@Ignores ")     }) }) @RunWith(BadCodeSnippetsRunner.class) public classBadCodeSnippetsTest { }
for(Snippet s : snippets) { if(patterns.get(s).matcher(line).find()) { uses.get(s).add(file);     } }
Forbidden Calls scala>BigDecimal.valueOf(1).equals(BigDecimal.valueOf(1.0)) res1: Boolean = false scala>BigDecimal.valueOf(1).compareTo(BigDecimal.valueOf(1.0)) == 0 res2: Boolean = true
@ForbiddenCalls( { @Check(paths = {"bin"}, forbiddenMethods = { "java.math.BigDecimal#equals(java.lang.Object)",     }) }) @RunWith(ForbiddenCallsTestRunner.class) public class ForbiddenCallsTest { }
Finding Forbidden Calls Must be done after the typed AST is created.   a.equals(b)
voiddoStuff(BigDecimal a, BigDecimal b) { boolean c = a.equals(b);  } Code:    0:	aload_1    1:	aload_2    2:	invokevirtual	#2;    5:	astore_3   6:       return
voiddoStuff(BigDecimal a, BigDecimal b) { boolean c = a.equals(b);  } Code:    0:	aload_1    1:	aload_2 2:	invokevirtual	#2;    5:	astore_3   6:       return 2:0xb6 3:          0x00 4:          0x02
const #2   = Method                  #14.#15; const #14 = class                        #18; const #15 = NameAndType      #19:#20 const #18 = Ascizjava/math/BigDecimal; const#19 = Ascizequals; const #20 = Asciz(Ljava/lang/Object;)Z;
voiddoStuff(BigDecimal a, BigDecimal b) { boolean c = a.equals(b);  } Code:    0:	aload_1    1:	aload_2    2:	invokevirtualjava/math/BigDecimal.equals(Ljava/lang/Object;)Z    5:	astore_3   6:       return
ClassFile {     u4 magic;     u2 minor_version;    u2 major_version;     u2 constant_pool_count; cp_infoconstant_pool[constant_pool_count-1];     u2 access_flags;     u2 this_class;     u2 super_class;     u2 interfaces_count;     u2 interfaces[interfaces_count];     u2 fields_count; field_infofields[fields_count];     u2 methods_count; method_infomethods[methods_count];     u2 attributes_count; attribute_infoattributes[attributes_count]; }
ClassFile {     u4 magic;     u2 minor_version;    u2 major_version;     u2 constant_pool_count; cp_infoconstant_pool[constant_pool_count-1]; u2 access_flags;     u2 this_class;     u2 super_class;     u2 interfaces_count;     u2 interfaces[interfaces_count];     u2 fields_count; field_infofields[fields_count];     u2 methods_count; method_infomethods[methods_count];     u2 attributes_count; attribute_infoattributes[attributes_count]; } const #18 = Ascizjava/math/BigDecimal; const #19 = Ascizequals; const #20 = Asciz(Ljava/lang/Object;)Z;
ClassFile {     u4 magic;     u2 minor_version;    u2 major_version;     u2 constant_pool_count; cp_infoconstant_pool[constant_pool_count-1];     u2 access_flags;     u2 this_class;     u2 super_class;     u2 interfaces_count;     u2 interfaces[interfaces_count];     u2 fields_count; field_infofields[fields_count];     u2 methods_count; method_infomethods[methods_count]; u2 attributes_count; attribute_infoattributes[attributes_count]; } method_info {     u2 access_flags;     u2 name_index;     u2 descriptor_index;     u2 attributes_count; attribute_infoattributes[attributes_count]; }
method_info{     u2 access_flags;     u2 name_index;     u2 descriptor_index;     u2 attributes_count; attribute_info attributes[attributes_count]; } Code_attribute {     u2 attribute_name_index;     u4 attribute_length;     u2 max_stack;     u2 max_locals;     u4 code_length;     u1 code[code_length];     u2 exception_table_length;     {         u2 start_pc;         u2 end_pc;         u2 handler_pc;         u2 catch_type;     } exception_table[exception_table_length];     u2 attributes_count; attribute_infoattributes[attributes_count]; }
Code_attribute {     u2 attribute_name_index;     u4 attribute_length;     u2 max_stack;     u2 max_locals;     u4 code_length;     u1 code[code_length]; u2 exception_table_length;     {         u2 start_pc;         u2 end_pc;         u2 handler_pc;         u2 catch_type;     } exception_table[exception_table_length];     u2 attributes_count; attribute_info attributes[attributes_count]; }  0:	aload_1 1:	aload_2 2:	invokevirtual   #2; 5: 	astore_3 6:	return
ASM @Override publicvoidvisitMethodInsn( intopcode,         String owner,         String name,         String descriptor) {    …. }
ASM @Override publicvoidvisitMethodInsn( intopcode,                            0xb6        String owner, "java.math.BigDecimal"        String name,                          "equals"        String descriptor) {               "(Ljava/lang/Object;)Z"    …. }
Failed Assertion junit.framework.AssertionFailedError: com.kaching.trading.core.Trade#execute()    calls java.math.BigDecimal#equals(java.lang.Object)    on line 273
Visibility Test class Lists {    … @VisibleForTesting static intcomputeArrayListCapacity(int size) { return (int) Math.min(            5L + size + (size / 10), Integer.MAX_VALUE);   } }
Visibility Test class QuoteHttpClientimplementsQuoteClient { @Inject HttpClientclient;    Quote getQuote(Symbol<?> symbol) { return …;   } }
@Visibilities({ @Check(paths = {"bin"}, visibilities = { @Visibility(value = VisibleForTesting.class, intent = PRIVATE), @Visibility(value = Inject.class, intent = PRIVATE)    }) }) @RunWith(VisibilityTestRunner.class) public class VisibilityTest { }
Two Passes Find all classes, fields and methods annotated with the specified annotations. Find all instructions referring to these classes, fields and methods.
ASM @Override publicAnnotationVisitorvisitAnnotation(    String descriptor,  booleanvisible) {     … }
ASM @Override publicAnnotationVisitorvisitAnnotation(    String descriptor,      "Lcom/google/common/annotations/VisibleForTesting;" booleanvisible) {      false     … }
booleanisVisibleBy( ParsedElement location, ParsedClasscurrentClass) {     Annotation annotation= annotations.get(location); if(annotation != null) {        …     } else { returntrue; // let's trust the compiler :) } }
Failed Assertion junit.framework.AssertionFailedError: com.kaching.account. ApplicationUploader#upload()    refers to @VisibleForTesting method com.kaching.account.Customer#getState() on line 149
Java 5+ Type System Primitives Objects Generics Wildcards Intersection types
Erasure Object eraser() {returnnewArrayList<String>();} Object obj = eraser(); // impossible to recover that obj is a listof string
Compiled classes $ cat MustBeSerializable.java importjava.io.Serializable; interfaceMustBeSerializable<T extendsSerializable> {} $cat ExtendsMustBeSerializable.java class Value {} classExtendsMustBeSerializableimplementsMustBeSerializable<Value> {}
Compiled classes $javacMustBeSerializable.java $rm MustBeSerializable.java $ls MustBeSerializable.classExtendsMustBeSerializable.java  $javac ExtendsMustBeSerializable.java -cp . ExtendsMustBeSerializable.java:2: type parameter Value is not within its bound classExtendsMustBeSerializableimplementsMustBeSerializable<Value> {}                                                               ^ 1 error
Compiled classes Compiler must write type information in class file for proper semantics When compiling other classes, need to read those type information and check against those contracts
Taking a peek at classes $javap -v MustBeSerializable | grep -A 1 'Signature;' const #3 = Asciz        Signature; const #4 = Asciz        <T::Ljava/io/Serializable;>Ljava/lang/Object;;
Signatures
Signatures Primitives B for byte, C for char, D for double, … Objects Lclassname; such as Ljava/lang/String; Arrays [B for byte[], [[D for double[][] Void V … 8 pages of documentation
With ASM org.objectweb.asm.signature.* org.objectweb.asm.Type
With Reflection java.lang.reflect.Type Class GenericArrayType(Type component) ParametrizedType(Type raw, Type[] arguments) TypeVariable(Type[] bounds, Sting name) WildcardType(    Type[] lowerBounds, Type[] upperBounds)
Some Examples String.class          Class<String> List<Integer> ParametrizedType(List.class, Integer.class) List<int[]> ParametrizedType(List.class, GenericArrayType(int.class))
Some Examples Map<? extends Shape, ? super Area> ParametrizedType(Map.class, {WildcardType({}, Shape.class),WildcardType(Area.class, {})        })
With Reflection java.lang.Class getGenericSuperclass() getGenericInterfaces()
Concrete Examples Unification Just-In-Time Providers
Unification MyClassimplements Callable<String> { … MyClass.class    .getGenericInterfaces()[0]    .getActualTypeArguments()[0] String.class!
Unification But if we have MyClassextendsAbstractCallable<String> { …AbstractCallable<T> implements Callable<T> { … Unification.getActualTypeArgument(MyClass.class, Callable.class, 0);
Unification – Want to Try? class MergeOfIntegerAndStringextends Merge<Integer, String> {} class Merge<K, V>  implementsOneTypeParam<Map<K, V>> {}  interfaceOneTypeParam<T>
Guice class QuoteHttpClientimplementsQuoteClient { @Inject HttpClientclient;     Quote getQuote(Symbol<?> symbol) { return …;     } }
Providers bind(Repository.class)    .toProvider(new Provider<Repository>() {        Repository get() {            return new RepositoryImpl(…);        }    });
Tedious Providers bind(new TypeLiteral<Marshaller<User>>() {})    .toProvider(new Provider<…>() {        Marshaller<User> get() {            return TwoLattes                  .createMarshaller(User.class);        }    });
It’s get tedious… @Inject Marshaller<User>@Inject Marshaller<Portfolio> @Inject Marshaller<Watchlist> …. ,[object Object]
TwoLatter.createMarshaller(Foo.class),[object Object]
Just-In-Time Providers Pattern matching on typesMarshaller<?> is a pattern forMarshaller<User>, Marshaller<Portfolio>, … Can be arbitrary complex, including wildcards, intersection types etc. http://github.com/pascallouisperez/guice-jit-providers
Tools PMD http://pmd.sourceforge.net/ Javassisthttp://www.csg.is.titech.ac.jp/~chiba/javassist/ FindBugshttp://findbugs.sourceforge.net/ Joeqhttp://suif.stanford.edu/~courses/cs243/joeq/index.htmlASM http://asm.ow2.org/ Guicehttp://code.google.com/p/google-guice/
References JVM spechttp://www.amazon.com/Java-Virtual-Machine-Specification-2nd/dp/0201432943 Class File spec http://java.sun.com/docs/books/jvms/second_edition/ClassFileFormat-Java5.pdf Super Type Tokenshttp://gafter.blogspot.com/2006/12/super-type-tokens.html Unifying Type Parameters in Javahttp://eng.kaching.com/2009/10/unifying-type-parameters-in-java.html Type Safe Bit Fields Using Higher Kinded Typeshttp://eng.kaching.com/2010/08/type-safe-bit-fields-using-higher.html

More Related Content

What's hot

7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
Geshan Manandhar
 
C# 6.0 Preview
C# 6.0 PreviewC# 6.0 Preview
C# 6.0 Preview
Fujio Kojima
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
PVS-Studio
 
JAVA AND MYSQL QUERIES
JAVA AND MYSQL QUERIES JAVA AND MYSQL QUERIES
JAVA AND MYSQL QUERIES Aditya Shah
 
C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointerLei Yu
 
SeneJug java_8_prez_122015
SeneJug java_8_prez_122015SeneJug java_8_prez_122015
SeneJug java_8_prez_122015
senejug
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8
Sergiu Mircea Indrie
 
Java 8
Java 8Java 8
Fundamental of programming - مقدمات برنامه نویسی
Fundamental of programming - مقدمات برنامه نویسیFundamental of programming - مقدمات برنامه نویسی
Fundamental of programming - مقدمات برنامه نویسی
Saman Chitsazian
 
Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoPaulo Morgado
 
Verilog Lecture4 2014
Verilog Lecture4 2014Verilog Lecture4 2014
Verilog Lecture4 2014
Béo Tú
 
C programs
C programsC programs
C programs
Vikram Nandini
 
Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014
Raimon Ràfols
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2
ppd1961
 
A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrongJulien Wetterwald
 
C#.net evolution part 2
C#.net evolution part 2C#.net evolution part 2
C#.net evolution part 2
Vahid Farahmandian
 

What's hot (20)

Constructor,destructors cpp
Constructor,destructors cppConstructor,destructors cpp
Constructor,destructors cpp
 
Java generics final
Java generics finalJava generics final
Java generics final
 
informatics practices practical file
informatics practices practical fileinformatics practices practical file
informatics practices practical file
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
C# 6.0 Preview
C# 6.0 PreviewC# 6.0 Preview
C# 6.0 Preview
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 1
 
JAVA AND MYSQL QUERIES
JAVA AND MYSQL QUERIES JAVA AND MYSQL QUERIES
JAVA AND MYSQL QUERIES
 
C++11 smart pointer
C++11 smart pointerC++11 smart pointer
C++11 smart pointer
 
SeneJug java_8_prez_122015
SeneJug java_8_prez_122015SeneJug java_8_prez_122015
SeneJug java_8_prez_122015
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8
 
Java 8
Java 8Java 8
Java 8
 
Fundamental of programming - مقدمات برنامه نویسی
Fundamental of programming - مقدمات برنامه نویسیFundamental of programming - مقدمات برنامه نویسی
Fundamental of programming - مقدمات برنامه نویسی
 
Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPonto
 
Verilog Lecture4 2014
Verilog Lecture4 2014Verilog Lecture4 2014
Verilog Lecture4 2014
 
C programs
C programsC programs
C programs
 
Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014Improving Android Performance at Droidcon UK 2014
Improving Android Performance at Droidcon UK 2014
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2
 
A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrong
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
C#.net evolution part 2
C#.net evolution part 2C#.net evolution part 2
C#.net evolution part 2
 

Similar to Applying Compiler Techniques to Iterate At Blazing Speed

Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
Juan Pablo
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzer
Andrey Karpov
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
JAXLondon_Conference
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
corehard_by
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
R696
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
javaTpoint s
 
Tesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareTesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition Software
Andrey Karpov
 
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
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
shubhra chauhan
 
Attributes & .NET components
Attributes & .NET componentsAttributes & .NET components
Attributes & .NET components
Bình Trọng Án
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
Microsoft Tech Community
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
Microsoft Tech Community
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
Let's write secure Drupal code! - DrupalCamp London 2019
Let's write secure Drupal code! - DrupalCamp London 2019Let's write secure Drupal code! - DrupalCamp London 2019
Let's write secure Drupal code! - DrupalCamp London 2019
Balázs Tatár
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code Contracts
PVS-Studio
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningCarol McDonald
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
eugeniadean34240
 

Similar to Applying Compiler Techniques to Iterate At Blazing Speed (20)

Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzer
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
Tesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareTesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition Software
 
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...
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
Attributes & .NET components
Attributes & .NET componentsAttributes & .NET components
Attributes & .NET components
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Let's write secure Drupal code! - DrupalCamp London 2019
Let's write secure Drupal code! - DrupalCamp London 2019Let's write secure Drupal code! - DrupalCamp London 2019
Let's write secure Drupal code! - DrupalCamp London 2019
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code Contracts
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
 

More from Pascal-Louis Perez

Fuchsia RFCs
Fuchsia RFCsFuchsia RFCs
Fuchsia RFCs
Pascal-Louis Perez
 
Products’ Love Story with Biz
Products’ Love Story with BizProducts’ Love Story with Biz
Products’ Love Story with Biz
Pascal-Louis Perez
 
How to Send a Receipt, Topics in Concurrency and Distributed Systems
How to Send a Receipt, Topics in Concurrency and Distributed SystemsHow to Send a Receipt, Topics in Concurrency and Distributed Systems
How to Send a Receipt, Topics in Concurrency and Distributed Systems
Pascal-Louis Perez
 
Corporate Finance Primer
Corporate Finance PrimerCorporate Finance Primer
Corporate Finance Primer
Pascal-Louis Perez
 
Developing an Immune System — The Hard and Soft Skills required to avoid Outages
Developing an Immune System — The Hard and Soft Skills required to avoid OutagesDeveloping an Immune System — The Hard and Soft Skills required to avoid Outages
Developing an Immune System — The Hard and Soft Skills required to avoid Outages
Pascal-Louis Perez
 
SLL Conf - Continuous Deployment
SLL Conf - Continuous DeploymentSLL Conf - Continuous Deployment
SLL Conf - Continuous DeploymentPascal-Louis Perez
 
Alchemist Startup Primer - Lean Development Practices
Alchemist Startup Primer - Lean Development PracticesAlchemist Startup Primer - Lean Development Practices
Alchemist Startup Primer - Lean Development PracticesPascal-Louis Perez
 
Database compatibility
Database compatibilityDatabase compatibility
Database compatibility
Pascal-Louis Perez
 
Iterate Like a Whirling Dervish
Iterate Like a Whirling DervishIterate Like a Whirling Dervish
Iterate Like a Whirling Dervish
Pascal-Louis Perez
 
Extreme Testing at kaChing
Extreme Testing at kaChingExtreme Testing at kaChing
Extreme Testing at kaChing
Pascal-Louis Perez
 
Type Checking JavaScript
Type Checking JavaScriptType Checking JavaScript
Type Checking JavaScript
Pascal-Louis Perez
 
Xignite's Dedicate kaChing Api
Xignite's Dedicate kaChing ApiXignite's Dedicate kaChing Api
Xignite's Dedicate kaChing ApiPascal-Louis Perez
 
Add (Syntactic) Sugar To Your Java
Add (Syntactic) Sugar To Your JavaAdd (Syntactic) Sugar To Your Java
Add (Syntactic) Sugar To Your Java
Pascal-Louis Perez
 
kaChing's API garage event
kaChing's API garage eventkaChing's API garage event
kaChing's API garage event
Pascal-Louis Perez
 

More from Pascal-Louis Perez (14)

Fuchsia RFCs
Fuchsia RFCsFuchsia RFCs
Fuchsia RFCs
 
Products’ Love Story with Biz
Products’ Love Story with BizProducts’ Love Story with Biz
Products’ Love Story with Biz
 
How to Send a Receipt, Topics in Concurrency and Distributed Systems
How to Send a Receipt, Topics in Concurrency and Distributed SystemsHow to Send a Receipt, Topics in Concurrency and Distributed Systems
How to Send a Receipt, Topics in Concurrency and Distributed Systems
 
Corporate Finance Primer
Corporate Finance PrimerCorporate Finance Primer
Corporate Finance Primer
 
Developing an Immune System — The Hard and Soft Skills required to avoid Outages
Developing an Immune System — The Hard and Soft Skills required to avoid OutagesDeveloping an Immune System — The Hard and Soft Skills required to avoid Outages
Developing an Immune System — The Hard and Soft Skills required to avoid Outages
 
SLL Conf - Continuous Deployment
SLL Conf - Continuous DeploymentSLL Conf - Continuous Deployment
SLL Conf - Continuous Deployment
 
Alchemist Startup Primer - Lean Development Practices
Alchemist Startup Primer - Lean Development PracticesAlchemist Startup Primer - Lean Development Practices
Alchemist Startup Primer - Lean Development Practices
 
Database compatibility
Database compatibilityDatabase compatibility
Database compatibility
 
Iterate Like a Whirling Dervish
Iterate Like a Whirling DervishIterate Like a Whirling Dervish
Iterate Like a Whirling Dervish
 
Extreme Testing at kaChing
Extreme Testing at kaChingExtreme Testing at kaChing
Extreme Testing at kaChing
 
Type Checking JavaScript
Type Checking JavaScriptType Checking JavaScript
Type Checking JavaScript
 
Xignite's Dedicate kaChing Api
Xignite's Dedicate kaChing ApiXignite's Dedicate kaChing Api
Xignite's Dedicate kaChing Api
 
Add (Syntactic) Sugar To Your Java
Add (Syntactic) Sugar To Your JavaAdd (Syntactic) Sugar To Your Java
Add (Syntactic) Sugar To Your Java
 
kaChing's API garage event
kaChing's API garage eventkaChing's API garage event
kaChing's API garage event
 

Recently uploaded

Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 

Recently uploaded (20)

Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 

Applying Compiler Techniques to Iterate At Blazing Speed

  • 1. Applying Compiler Techniques to Iterate at Blazing Speed @pascallouis julien@kaching.com
  • 2. Engineering at kaChing TDD from day one Full regression suite runs in less than 3 minutes Deploy to production 30+ times a day People have written and launched new features during interview process
  • 3. Agenda Apply Compiler Techniques ? Profit!
  • 4. Seriously… (Java focused) Software Analysis Anatomy of a compiler Creating meta tests Leveraging Types Levels of interpretation Descriptors and signatures DRY your code (less bugs, greater reach for experts, higher testability)
  • 5. Software Analysis Running a series of analyses on the code base. Catch common mistakes due to distracted developers, new hires or bad APIs.
  • 6. Anatomy of a Compiler Annotated Abstract Syntax Tree Semantic Analysis Intermediate Representation Generation Intermediate Representation Abstract Syntax Tree Syntactic Analysis Optimization Optimized Intermediate Representation Tokens Lexical Analysis Machine Code Generation Target Code Source Code
  • 7. int x 1; int y x + 2; Lexical Analysis IDENT(int) IDENT(x) ASGN NUMBER(1) SEMICOLON IDENT(int) IDENT(y) ASGN IDENT(x) PLUS NUMBER(2) SEMICOLON
  • 8. IDENT(int) IDENT(x) ASGN NUMBER(1) SEMICOLON IDENT(int) IDENT(y) ASGN IDENT(x) PLUS NUMBER(2) SEMICOLON Syntactic Analysis PROGRAM( LET(x, int, 1), LET(y, int, PLUS(x, 2)))
  • 9. PROGRAM( LET(x, int, 1), LET(y, int, PLUS(x, 2))) Semantic Analysis: Symbols PROGRAM( LET(x, int, 1), LET(y, int, PLUS(x, 2)))
  • 10. PROGRAM( LET(x, int, 1), LET(y, int, PLUS(x, 2))) Semantic Analysis: Types PROGRAM( LET(x: int, int, 1: int), LET(y: int, int, PLUS(x: int, 2: int): int))
  • 11. Optimizations Simple optimizations can be done on the Abstract Syntax Tree Other optimizations require specialized representations Static Single Assignment form Control Flow Graph
  • 12. PROGRAM( LET(x: int, int, 1: int), LET(y: int, int, PLUS(3: int, 2: int): int)) Constant folding PROGRAM( LET(x: int, int, 1: int), LET(y: int, int, 5: int))
  • 13. int x1 (a1 + b1) / c1; int y1(a1+ b1) / d1; Common sub-expression elimination int temp  a + b; int x  temp / d; inty  temp / d;
  • 14. int x1 (a1 + b1) / c1; a2a1 + 1; int y1(a2+ b1) / d1; Common sub-expression elimination intx (a + b) / c; a  a + 1; inty (a + b) / d;
  • 15. Anatomy of a Compiler Semantic Analysis Intermediate Representation Generation Syntactic Analysis Optimization Lexical Analysis Machine Code Generation
  • 16. javac Target Code Source Code
  • 17. PMD Annotated Abstract Syntax Tree Source Code
  • 19. scalac Semantic Analysis Intermediate Representation Generation Syntactic Analysis Optimization Lexical Analysis Machine Code Generation
  • 20. Finding bad code snippets Describe bad code snippets using regular expressions. Analysis done on the source code, before lexical analysis as information such as whitespaces are lost. Extremely easy to implement.
  • 21. @CodeSnippets({ @Check(paths = {"src", "srctest"}, snippets = { @Snippet("bif("), @Snippet("super()") }, @Check(paths = {"srctest"}, snippets = { @Snippet("@Ignores ") }) }) @RunWith(BadCodeSnippetsRunner.class) public classBadCodeSnippetsTest { }
  • 22. for(Snippet s : snippets) { if(patterns.get(s).matcher(line).find()) { uses.get(s).add(file); } }
  • 23. Forbidden Calls scala>BigDecimal.valueOf(1).equals(BigDecimal.valueOf(1.0)) res1: Boolean = false scala>BigDecimal.valueOf(1).compareTo(BigDecimal.valueOf(1.0)) == 0 res2: Boolean = true
  • 24. @ForbiddenCalls( { @Check(paths = {"bin"}, forbiddenMethods = { "java.math.BigDecimal#equals(java.lang.Object)", }) }) @RunWith(ForbiddenCallsTestRunner.class) public class ForbiddenCallsTest { }
  • 25. Finding Forbidden Calls Must be done after the typed AST is created. a.equals(b)
  • 26. voiddoStuff(BigDecimal a, BigDecimal b) { boolean c = a.equals(b); } Code: 0: aload_1 1: aload_2 2: invokevirtual #2; 5: astore_3 6: return
  • 27. voiddoStuff(BigDecimal a, BigDecimal b) { boolean c = a.equals(b); } Code: 0: aload_1 1: aload_2 2: invokevirtual #2; 5: astore_3 6: return 2:0xb6 3: 0x00 4: 0x02
  • 28. const #2 = Method #14.#15; const #14 = class #18; const #15 = NameAndType #19:#20 const #18 = Ascizjava/math/BigDecimal; const#19 = Ascizequals; const #20 = Asciz(Ljava/lang/Object;)Z;
  • 29. voiddoStuff(BigDecimal a, BigDecimal b) { boolean c = a.equals(b); } Code: 0: aload_1 1: aload_2 2: invokevirtualjava/math/BigDecimal.equals(Ljava/lang/Object;)Z 5: astore_3 6: return
  • 30. ClassFile { u4 magic; u2 minor_version; u2 major_version; u2 constant_pool_count; cp_infoconstant_pool[constant_pool_count-1]; u2 access_flags; u2 this_class; u2 super_class; u2 interfaces_count; u2 interfaces[interfaces_count]; u2 fields_count; field_infofields[fields_count]; u2 methods_count; method_infomethods[methods_count]; u2 attributes_count; attribute_infoattributes[attributes_count]; }
  • 31. ClassFile { u4 magic; u2 minor_version; u2 major_version; u2 constant_pool_count; cp_infoconstant_pool[constant_pool_count-1]; u2 access_flags; u2 this_class; u2 super_class; u2 interfaces_count; u2 interfaces[interfaces_count]; u2 fields_count; field_infofields[fields_count]; u2 methods_count; method_infomethods[methods_count]; u2 attributes_count; attribute_infoattributes[attributes_count]; } const #18 = Ascizjava/math/BigDecimal; const #19 = Ascizequals; const #20 = Asciz(Ljava/lang/Object;)Z;
  • 32. ClassFile { u4 magic; u2 minor_version; u2 major_version; u2 constant_pool_count; cp_infoconstant_pool[constant_pool_count-1]; u2 access_flags; u2 this_class; u2 super_class; u2 interfaces_count; u2 interfaces[interfaces_count]; u2 fields_count; field_infofields[fields_count]; u2 methods_count; method_infomethods[methods_count]; u2 attributes_count; attribute_infoattributes[attributes_count]; } method_info { u2 access_flags; u2 name_index; u2 descriptor_index; u2 attributes_count; attribute_infoattributes[attributes_count]; }
  • 33. method_info{ u2 access_flags; u2 name_index; u2 descriptor_index; u2 attributes_count; attribute_info attributes[attributes_count]; } Code_attribute { u2 attribute_name_index; u4 attribute_length; u2 max_stack; u2 max_locals; u4 code_length; u1 code[code_length]; u2 exception_table_length; { u2 start_pc; u2 end_pc; u2 handler_pc; u2 catch_type; } exception_table[exception_table_length]; u2 attributes_count; attribute_infoattributes[attributes_count]; }
  • 34. Code_attribute { u2 attribute_name_index; u4 attribute_length; u2 max_stack; u2 max_locals; u4 code_length; u1 code[code_length]; u2 exception_table_length; { u2 start_pc; u2 end_pc; u2 handler_pc; u2 catch_type; } exception_table[exception_table_length]; u2 attributes_count; attribute_info attributes[attributes_count]; } 0: aload_1 1: aload_2 2: invokevirtual #2; 5: astore_3 6: return
  • 35. ASM @Override publicvoidvisitMethodInsn( intopcode, String owner, String name, String descriptor) { …. }
  • 36. ASM @Override publicvoidvisitMethodInsn( intopcode, 0xb6 String owner, "java.math.BigDecimal" String name, "equals" String descriptor) { "(Ljava/lang/Object;)Z" …. }
  • 37. Failed Assertion junit.framework.AssertionFailedError: com.kaching.trading.core.Trade#execute() calls java.math.BigDecimal#equals(java.lang.Object) on line 273
  • 38. Visibility Test class Lists { … @VisibleForTesting static intcomputeArrayListCapacity(int size) { return (int) Math.min( 5L + size + (size / 10), Integer.MAX_VALUE); } }
  • 39. Visibility Test class QuoteHttpClientimplementsQuoteClient { @Inject HttpClientclient; Quote getQuote(Symbol<?> symbol) { return …; } }
  • 40. @Visibilities({ @Check(paths = {"bin"}, visibilities = { @Visibility(value = VisibleForTesting.class, intent = PRIVATE), @Visibility(value = Inject.class, intent = PRIVATE) }) }) @RunWith(VisibilityTestRunner.class) public class VisibilityTest { }
  • 41. Two Passes Find all classes, fields and methods annotated with the specified annotations. Find all instructions referring to these classes, fields and methods.
  • 42. ASM @Override publicAnnotationVisitorvisitAnnotation( String descriptor, booleanvisible) { … }
  • 43. ASM @Override publicAnnotationVisitorvisitAnnotation( String descriptor, "Lcom/google/common/annotations/VisibleForTesting;" booleanvisible) { false … }
  • 44. booleanisVisibleBy( ParsedElement location, ParsedClasscurrentClass) { Annotation annotation= annotations.get(location); if(annotation != null) { … } else { returntrue; // let's trust the compiler :) } }
  • 45. Failed Assertion junit.framework.AssertionFailedError: com.kaching.account. ApplicationUploader#upload() refers to @VisibleForTesting method com.kaching.account.Customer#getState() on line 149
  • 46. Java 5+ Type System Primitives Objects Generics Wildcards Intersection types
  • 47. Erasure Object eraser() {returnnewArrayList<String>();} Object obj = eraser(); // impossible to recover that obj is a listof string
  • 48. Compiled classes $ cat MustBeSerializable.java importjava.io.Serializable; interfaceMustBeSerializable<T extendsSerializable> {} $cat ExtendsMustBeSerializable.java class Value {} classExtendsMustBeSerializableimplementsMustBeSerializable<Value> {}
  • 49. Compiled classes $javacMustBeSerializable.java $rm MustBeSerializable.java $ls MustBeSerializable.classExtendsMustBeSerializable.java $javac ExtendsMustBeSerializable.java -cp . ExtendsMustBeSerializable.java:2: type parameter Value is not within its bound classExtendsMustBeSerializableimplementsMustBeSerializable<Value> {} ^ 1 error
  • 50. Compiled classes Compiler must write type information in class file for proper semantics When compiling other classes, need to read those type information and check against those contracts
  • 51. Taking a peek at classes $javap -v MustBeSerializable | grep -A 1 'Signature;' const #3 = Asciz Signature; const #4 = Asciz <T::Ljava/io/Serializable;>Ljava/lang/Object;;
  • 53. Signatures Primitives B for byte, C for char, D for double, … Objects Lclassname; such as Ljava/lang/String; Arrays [B for byte[], [[D for double[][] Void V … 8 pages of documentation
  • 54. With ASM org.objectweb.asm.signature.* org.objectweb.asm.Type
  • 55. With Reflection java.lang.reflect.Type Class GenericArrayType(Type component) ParametrizedType(Type raw, Type[] arguments) TypeVariable(Type[] bounds, Sting name) WildcardType( Type[] lowerBounds, Type[] upperBounds)
  • 56. Some Examples String.class Class<String> List<Integer> ParametrizedType(List.class, Integer.class) List<int[]> ParametrizedType(List.class, GenericArrayType(int.class))
  • 57. Some Examples Map<? extends Shape, ? super Area> ParametrizedType(Map.class, {WildcardType({}, Shape.class),WildcardType(Area.class, {}) })
  • 58. With Reflection java.lang.Class getGenericSuperclass() getGenericInterfaces()
  • 59. Concrete Examples Unification Just-In-Time Providers
  • 60. Unification MyClassimplements Callable<String> { … MyClass.class .getGenericInterfaces()[0] .getActualTypeArguments()[0] String.class!
  • 61. Unification But if we have MyClassextendsAbstractCallable<String> { …AbstractCallable<T> implements Callable<T> { … Unification.getActualTypeArgument(MyClass.class, Callable.class, 0);
  • 62. Unification – Want to Try? class MergeOfIntegerAndStringextends Merge<Integer, String> {} class Merge<K, V> implementsOneTypeParam<Map<K, V>> {} interfaceOneTypeParam<T>
  • 63. Guice class QuoteHttpClientimplementsQuoteClient { @Inject HttpClientclient; Quote getQuote(Symbol<?> symbol) { return …; } }
  • 64. Providers bind(Repository.class) .toProvider(new Provider<Repository>() { Repository get() { return new RepositoryImpl(…); } });
  • 65. Tedious Providers bind(new TypeLiteral<Marshaller<User>>() {}) .toProvider(new Provider<…>() { Marshaller<User> get() { return TwoLattes .createMarshaller(User.class); } });
  • 66.
  • 67.
  • 68. Just-In-Time Providers Pattern matching on typesMarshaller<?> is a pattern forMarshaller<User>, Marshaller<Portfolio>, … Can be arbitrary complex, including wildcards, intersection types etc. http://github.com/pascallouisperez/guice-jit-providers
  • 69. Tools PMD http://pmd.sourceforge.net/ Javassisthttp://www.csg.is.titech.ac.jp/~chiba/javassist/ FindBugshttp://findbugs.sourceforge.net/ Joeqhttp://suif.stanford.edu/~courses/cs243/joeq/index.htmlASM http://asm.ow2.org/ Guicehttp://code.google.com/p/google-guice/
  • 70. References JVM spechttp://www.amazon.com/Java-Virtual-Machine-Specification-2nd/dp/0201432943 Class File spec http://java.sun.com/docs/books/jvms/second_edition/ClassFileFormat-Java5.pdf Super Type Tokenshttp://gafter.blogspot.com/2006/12/super-type-tokens.html Unifying Type Parameters in Javahttp://eng.kaching.com/2009/10/unifying-type-parameters-in-java.html Type Safe Bit Fields Using Higher Kinded Typeshttp://eng.kaching.com/2010/08/type-safe-bit-fields-using-higher.html

Editor's Notes

  1. A token is a string of characters, categorized according to the rules as a symbol.
  2. Abstract interpretation
  3. n compiler design, static single assignment form (often abbreviated as SSA form or simply SSA) is an intermediate representation (IR) in which every variable is assigned exactly once. Existing variables in the original IR are split into versions, new variables typically indicated by the original name with a subscript, so that every definition gets its own version
  4. In functional language compilers, such as those for Scheme, ML and Haskell, continuation-passing style (CPS) is generally used where one might expect to find SSA in a compiler for Fortran or C. SSA is formally equivalent to a well-behaved subset of CPS
  5. A token is a string of characters, categorized according to the rules as a symbol.
  6. A token is a string of characters, categorized according to the rules as a symbol.
  7. A token is a string of characters, categorized according to the rules as a symbol.
  8. A token is a string of characters, categorized according to the rules as a symbol.
  9. A token is a string of characters, categorized according to the rules as a symbol.
  10. Internal name of the method’s owner class, method’s name and method’s descriptor.
  11. Pretty tricky