Using Type Annotations to Improve Your Code

Similar documents
The Checker Framework: pluggable static analysis for Java

Preventing Errors Before They Happen The Checker Framework

Code verification. CSE 331 University of Washington. Michael Ernst

Preventing Errors Before They Happen The Checker Framework

Detecting and preventing null pointer errors with pluggable type-checking

CSE 331 Software Design and Implementation. Lecture 16 Checker Framework

Lecture 19 Checker Framework

Detecting and preventing null pointer errors with pluggable type-checking

Status Report. JSR-305: Annotations for Software Defect Detection. William Pugh Professor

JSR-305: Annotations for Software Defect Detection

Metadata Features in Java SE 8

Javarifier: inference of reference immutability

CS 251 Intermediate Programming Inheritance

Java Fundamentals (II)

Cascade: A Universal Programmer-assisted Type Qualifier Inference Tool

The Checker Framework Manual

Using null type annotations in practice

Java Object Oriented Design. CSC207 Fall 2014

CS 430 Spring Mike Lam, Professor. Data Types and Type Checking

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Java Enum Java, winter semester ,2018 1

Introduction to Programming Using Java (98-388)

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

CS-202 Introduction to Object Oriented Programming

Java: advanced object-oriented features

Assertions & Design-by-Contract using JML Erik Poll University of Nijmegen

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Enum Types. Built-in support for types of discrete values Advantages over C++ s enum: Type-safety Body can include methods and fields

1B1b Classes in Java Part I

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

ESC/Java2 Use and Features David Cok, Joe Kiniry, Erik Poll Eastman Kodak Company, University College Dublin, and Radboud University Nijmegen

Why OO programming? want but aren t. Ø What are its components?

Semantic Analysis and Type Checking

EMBEDDED SYSTEMS PROGRAMMING More About Languages

CS558 Programming Languages

Array. Prepared By - Rifat Shahriyar

interface MyAnno interface str( ) val( )

JML. Java Modeling Language

COMP 401 Spring 2013 Midterm 1

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

CS558 Programming Languages

Chapter 2: Java OOP I

Atelier Java - J2. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

Topic 7: Algebraic Data Types

DD2460 Software Safety and Security: Part III Exercises session 2: Type + Jif

Static Semantics. Lecture 15. (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1

September 10,

Annotation Hammer Venkat Subramaniam (Also published at

ESC/Java2 Use and Features

Class, Variable, Constructor, Object, Method Questions

CS Lecture #14

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

ESC/Java2 Use and Features

INHERITANCE. Spring 2019

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

Index COPYRIGHTED MATERIAL

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

ITI Introduction to Computing II

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

Java Classes, Inheritance, and Interfaces

Static program checking and verification

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Pierce Ch. 3, 8, 11, 15. Type Systems

CMSC 330: Organization of Programming Languages

Programming Kotlin. Familiarize yourself with all of Kotlin s features with this in-depth guide. Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Points To Remember for SCJP

Types and Type Inference

(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University

Announcements. Specifications. Outline. Specifications. HW1 is due Thursday at 1:59:59 pm

Advanced MEIC. (Lesson #18)

Chapter 5 Object-Oriented Programming

ITI Introduction to Computing II

Finding User/Kernel Pointer Bugs with Type Inference p.1

Lecture 10. Overriding & Casting About

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Topic 10. Abstract Classes. I prefer Agassiz in the abstract, rather than in the concrete.

Introducing Wybe a language for everyone

Static Analysis in Practice

CMSC 132: Object-Oriented Programming II

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

CS 302 Week 9. Jim Williams

Classes, interfaces, & documentation. Review of basic building blocks

1 Shyam sir JAVA Notes

Programming in Scala Second Edition

Universe Type System for Eiffel. Annetta Schaad

A Type System for Regular Expressions

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Compilers and computer architecture: Semantic analysis

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

1 Lexical Considerations

Transcription:

Using Type Annotations to Improve Your Code Birds-of-a-Feather Session Werner Dietl, University of Waterloo Michael Ernst, University of Washington

Open for questions Survey: Did you attend the tutorial? Which of these best describes you? Specific question / concern / feedback Specific problem / use case / tool Curious, want to learn more Please raise questions / issues

Schedule Java 8 syntax for type annotations Pluggable types: a use of type annotations Questions and discussion

Since Java 5: declaration annotations Only for declaration locations: @Deprecated class Foo { class field @Getter @Setter private String query; @SuppressWarnings( unchecked ) void foo() { } } method

Java 8 adds type annotations Annotations on all occurrences of types: @Untainted String query; List<@NonNull String> strings; mygraph = (@Immutable Graph) tmp; class UnmodifiableList<T> implements @Readonly List<T> {}

How Java 8 treats type annotations Stored in classfile Handled by javac, javap, javadoc, Writing type annotations has no effect unless you run an annotation processor

Write annotations before the element Write declaration annotations before the decl. Write type annotations before the type @Override public @NonNull String tostring() { } Don t split them up: @NonNull public String tostring() { }

Array annotations String [] [] a; An array of arrays of strings

Array annotations @English String @ReadOnly [] @NonEmpty [] a; An read-only array of non-empty arrays of English strings

Array annotations @English String @ReadOnly [] @NonEmpty [] a; A read-only array of non-empty arrays of English strings

Array annotations @English String @ReadOnly [] @NonEmpty [] a; A read-only array of non-empty arrays of English strings Rule: write the annotation before the type

Explicit method receivers class MyClass { public String tostring() {} public boolean equals(object other) {} }

Explicit method receivers class MyClass { public String tostring() {} public boolean equals(object other) {} } myval.tostring(); myval.equals(otherval);

Explicit method receivers class MyClass { public String tostring(myclass this) {} public boolean equals(myclass this, Object other) {} } myval.tostring(); myval.equals(otherval); No impact on method binding and overloading

Explicit method receivers class MyClass { public String tostring(@readonly MyClass this) {} public boolean equals(@readonly MyClass this, @ReadOnly Object other) {} } myval.tostring(); myval.equals(otherval); Rationale: need a syntactic location for type annotations

Constructor return & receiver types Every constructor has a return type class MyClass { @TReturn MyClass(@TParam String p) {...} Inner class constructors also have a receiver class Outer { class Inner { @TReturn Inner(@TRecv Outer Outer.this, @TParam String p) {...}

Why were type annotations added to Java?

Annotations are a specification More concise than English text or Javadoc Machine-readable Machine-checkable Improved documentation Improved correctness

Pluggable Type Systems Use Type Annotations to express properties Prevent errors at compile time http://checkerframework.org/ Twitter: @CheckerFrmwrk Facebook/Google+: CheckerFramework

Java's type system is too weak Type checking prevents many errors int i = hello ; Type checking doesn't prevent enough errors System.console().readLine(); Collections.emptyList().add( one );

Java's type system is too weak Type checking prevents many errors int i = hello ; Type checking doesn't prevent enough errors NullPointerException System.console().readLine(); Collections.emptyList().add( one );

Java's type system is too weak Type checking prevents many errors int i = hello ; Type checking doesn't prevent enough errors System.console().readLine(); UnsupportedOperationException Collections.emptyList().add( one );

Solution: Pluggable Type Checking 1. Design a type system to solve a specific problem 2. Write type qualifiers in code (or, use type inference) @Immutable Date date = new Date(); date.setseconds(0); // compile-time error 3. Type checker warns about violations (bugs) % javac -processor NullnessChecker MyFile.java MyFile.java:149: dereference of possibly-null reference bb2 allvars = bb2.vars; ^

Optional Type Checking No errors Source Compiler Executable Fix bugs Change types Errors

Optional Type Checking No errors Source Compiler Executable Fix bugs Change types Errors Optional Type Checker Guaranteed behavior Fix bugs Add/change annotations Warnings

Optional Type Checking No errors Source Compiler Executable Fix bugs Change types Errors Optional Optional Type Optional Type Checker Type Checker Checker Guaranteed behavior Fix bugs Add/change annotations Warnings

Example type systems Null dereferences (@NonNull) Equality tests (@Interned) Concurrency / locking (@GuardedBy) Command injection vulnerabilities (@OsTrusted) Privacy (@Source) Regular expression syntax (@Regex) printf format strings (@Format) Signature format (@FullyQualified) Compiler messages (@CompilerMessageKey) Fake enumerations (@Fenum) You can write your own checker!

CF: Java 6 & 7 compatibility (+ no dependence on Checker Framework) Annotations in comments List</*@NonNull*/ String> strings; Comments for arbitrary source code /*>>> import myquals.trecv; */... int foo(/*>>> @TRecv MyClass this,*/ @TParam String p) { }

Annotating external libraries When type-checking clients, need library spec. Can write manually or automatically infer Two syntaxes: As separate text file (stub file) Within its.jar file (from annotated partial source code)

Checker Framework facilities Full type systems: inheritance, overriding,... Generics (type polymorphism) Also qualifier polymorphism Qualifier defaults Pre-/post-conditions Warning suppression

Static type system Plug-in to the compiler Doesn t impact: method binding memory consumption execution A future tool might affect run-time behavior

Checkers are usable Type-checking is familiar to programmers Modular: fast, incremental, partial programs Annotations are not too verbose @NonNull: 1 per 75 lines @Interned: 124 annotations in 220 KLOC revealed 11 bugs @Format: 107 annotations in 2.8 MLOC revealed 104 bugs Possible to annotate part of program Fewer annotations in new code Few false positives First-year CS majors preferred using checkers to not Practical: in use in Silicon Valley, on Wall Street, etc.

What a checker guarantees The program satisfies the type property. There are: no bugs (of particular varieties) no wrong annotations Caveat 1: only for code that is checked Native methods (handles reflection!) Code compiled without the pluggable type checker Suppressed warnings Indicates what code a human should analyze Checking part of a program is still useful Caveat 2: The checker itself might contain an error

Problem: annotation effort Programmer must write type annotations on program code on libraries Very few: 1 per 100 lines, often much less depends on the type system Solution: type inference

Type inference within a method Called flow-sensitive refinement A variable can have different types on different lines of code Low overhead Always used Does not affect type signatures x.tostring(); // warning: possible NPE if (x!=null) { x.tostring(); // no warning } x.tostring(); // warning: possible NPE

Whole-program type inference Analyze all the code at once Determine the globally optimal annotations Approach: Introduce placeholder for each location Use the same type rules to generate constraints Use a solver to find a solution Available (beta) with the Checker Framework

Practicality Testing Built-in Type Systems Pluggable Type Systems Formal Verification Guarantees

Checker Framework Community Open source project: https://github.com/typetools/checker-framework Monthly release cycle >12,800 commits, 75 authors Welcoming & responsive community

Checker Framework Plans More type systems: Index-out-of-bounds Optional type Signed vs. unsigned numbers Immutability Determinism Type inference Combined static & dynamic enforcement

Present and Future of Type Annotations Java 9 Type annotation implementation improvements Java >9 What annotation-related language feature are you missing? Statement annotations More expressive annotation attributes Annotation inheritance

Conclusions Type Annotations added in Java 8 Checker Framework for creating type checkers Featureful, effective, easy to use, scalable Prevent bugs at compile time Improve your code! http://checkerframework.org/