SlideShare una empresa de Scribd logo
1 de 70
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

Más contenido relacionado

La actualidad más candente

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 codeGeshan Manandhar
 
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 1PVS-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_122015senejug
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8Sergiu Mircea Indrie
 
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 2014Béo Tú
 
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 2014Raimon 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 2ppd1961
 
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
 

La actualidad más candente (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 a 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 abstractionIntro 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 analyzerAndrey Karpov
 
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 Doumlercorehard_by
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003R696
 
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 SoftwareAndrey 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 JavascriptJulie Iskander
 
Attributes & .NET components
Attributes & .NET componentsAttributes & .NET components
Attributes & .NET componentsBì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++ CodeMicrosoft 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++ CodeMicrosoft 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 2019Balázs Tatár
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsPVS-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.docxeugeniadean34240
 

Similar a 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
 

Más de Pascal-Louis Perez

Products’ Love Story with Biz
Products’ Love Story with BizProducts’ Love Story with Biz
Products’ Love Story with BizPascal-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 SystemsPascal-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 OutagesPascal-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
 
Iterate Like a Whirling Dervish
Iterate Like a Whirling DervishIterate Like a Whirling Dervish
Iterate Like a Whirling DervishPascal-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 JavaPascal-Louis Perez
 

Más de 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
 

Último

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 

Último (20)

UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 

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

Notas del editor

  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