spindle Documentation

Size: px
Start display at page:

Download "spindle Documentation"

Transcription

1 spindle Documentation Release Jorge Ortiz, Jason Liszka May 19, 2014

2

3 Contents i

4 ii

5 spindle Documentation, Release Spindle is a library and code generation tool developed at Foursquare for representing data stored in MongoDB. It s based heavily on Apache Thrift, so understanding some Thrift fundamentals is important. However, most of Spindle is custom Scala code generation developed to work with Thrift models. Contents: Contents 1

6 spindle Documentation, Release Contents

7 CHAPTER 1 Thrift Thrift is a framework that allows you to define serializable datatypes in a language-independent manner. These datatypes are described in.thrift files which conform to the Thrift Interface Description Language (IDL). The standard Thrift compiler will read Thrift IDLs and generate code for many different languages: Java, Python, JavaScript, C++, etc. We ve built a custom Thrift compiler (documented here) which generates Scala code. 1.1 Data Model Thrift s data model has the following base types: bool - true/false boolean value (Java s boolean) byte - 8-bit signed integer (Java s byte) i16-16-bit signed integer (Java s short) i32-32-bit signed integer (Java s int) i64-64-bit signed integer (Java s long) double - 64 bit IEEE 754 double precision floating point number (Java s double) string - UTF-8 encoded text string (Java s string) binary - sequence of unencoded bytes (Java s Array[Byte] or ByteBuffer) Thrift s data model includes an enum type (equivalent to Java s enum). On the wire, enums are represented as 32-bit integers. Thrift s data model also has the following parametrized container types. The parameters <a> and <b> can be primitives, enum s, or struct s. list<a> - ordered list of elements (Java s List<A>) set<a> - unordered list of unique elements (Java s Set<A>) map<a, b> - a map of unique keys to values (Java s Map<A, B>). Warning: non-string map keys will fail at runtime if you try to use TBSONObjectProtocol. Thrift includes three class types: struct - numbered fields, with a type and an optional default value union - tagged union types exception - like struct s, but can be used in the throws clause of a service 3

8 spindle Documentation, Release Finally, Thrift allows you to define constants and typedefs. A constant is a value of any Thrift type. A typedef is an alias of any Thrift type. 1.2 Interface Definition Language (IDL) Thrift data structures are described in.thrift files which conform to the Thrift IDL grammar. You can see the Thrift Tutorial for an example, or reference the formal grammar. 1.3 Serialization Formats There are four serialization formats we use. TBinaryProtocol - The original binary encoding included with Thrift. It is not well-documented, but is fairly simple. Field names are ommitted (only integer field identifiers are used), types are encoded as byte identifiers, sizes are prepended as integers. TCompactProtocol - A more compact binary encoding. Also not well-documented, but somewhat described here TReadableJSONProtocol - Reads and writes human-readable JSON. Unlike TJSONProtocol, ituses actual field names for keys, rather than field identifiers. If the field has a wire_name annotation, will use that instead of the name. Includes special handling for ObjectId. TBSONObjectProtocol - Reads and writes BSON DBObject s. It uses field names for keys. If the field has a wire_name annotation, will use that instead of the name. Includes special handling for ObjectId and DateTime. 4 Chapter 1. Thrift

9 CHAPTER 2 Records 2.1 Creating a Record There are three ways to create a Record apply method The easiest way to create a Record is to use the companion object s apply method. This method only works if you know the value of all of the Record s fields, even optional fields. This is useful for structs that have a small, usually fixed number of fields. (Note that if you add another field to your struct, any existing calls to apply will fail due to insufficient arguments.) Example (Thrift file): struct LatLong { 1: optional double lat 2: optional double long Example (Scala file): val ll = LatLong(40.65, ) Builder If you need to omit optional fields, or if you want to pass around a partially-constructed Record before you know all its fields, you will want to use a Builder. Builders are created using the newbuilder method on a Record s companion object. Fields on the builder are set using methods with the same name as the field. Field setter methods can be passed either a value or an Option value. To finish constructing a Builder, call result or resultmutable (returns a Record that conforms to the Mutable trait). Builders enforce that all required fields are set before result can be called. Example: val v = (Venue.newBuilder.id(new ObjectId()).venuename(Some("Foursquare HQ")).likeCount(None).result()) 5

10 spindle Documentation, Release Raw If for whatever reason a Builder is not flexible enough to do what you want, you can always instantiate a Raw class. You can use the createrawrecord method on the Record s companion object or you can call new directly on the Record s Raw class. This is unsafe, as it will not verify that required fields are set and can seriously corrupt data. Make sure you know what you re doing before you use Raw constructors. 2.2 Reading/Writing Records All records have read and write methods that take one argument: a TProtocol. We use a number of protocols, depending on the serialization format you want to read from or write to. See the section on Serialization Formats. Each protocol has a particular way in which it s constructed. Refer to the documentation for each protocol on how to use them. If you re reading in a record, it s acceptable to use the createrawrecord method on the MetaRecord companion object to instantiate a record that you can call read on. 2.3 Traits Every record has a trait of the same name that defines a mostly immutable interface to that record (the exception being some mutable methods for priming foreign keys). Methods that modify the record are generally only available as part of the Mutable trait Field Access The record s trait has a bunch of methods for field access. Not all of them are always available. Given a field named foo, the following field access methods may be available: foo - Returns the value of the field. Only available if a default is available (in which case it aliases fooordefault), or if the field is required (in which case it aliases fooorthrow). foooption - Returns an Option with the value of the field, or None if the field is not set. Always available. fooordefault - Returns the value of the field, or the default value if the field is not set. Only available if a default is available (either there s an explicit default in the.thrift file, or the field is a primitive or a collection, in which case the default is 0/0.0/false/empty/etc). fooornull - Returns the value of the field, or null if the field is not set. For primitives, typed to return the boxed type (e.g., java.lang.integer instead of scala.int) so that null is valid. In general, avoid using fooornull. Prefer foooption in general and fooorthrow if you want to fail fast (such as in tests, etc). Only use fooornull if you re writing performance-sensitive code that can t afford to allocate an Option. fooorthrow - Returns the value of the field, or throws an exception if the field is not set. fooisset - Returns true if the field is set, false otherwise Special Field Access Some field types have special access methods: foobytearray - if the field is of the binary thrift type, this method will exist and return an Array[Byte] (instead of the more efficient java.nio.bytebuffer) 6 Chapter 2. Records

11 spindle Documentation, Release foostruct - if the field has a bitfield_struct or bitfield_struct_no_setbits annotation, this method will exist and return a populated bitfield struct. (See: Bitfields) foofk - if the field is a foreign_key field, this method will exist and return the foreign object. (See: Priming) 2.4 Other Methods Other methods on the record trait: tostring - uses TReadableJSONProtocol to create a pretty-printed JSON string representation of the record hashcode - uses scala.util.murmurhash to produce a hash code from all the already-set fields on the record equals - compares two records to make sure that all their fields have the same set state, and if they re both set that they have the same value compare - compares two records by their set state for each field and their value for each field copy - similar to case class copy, creates a shallow copy of a record; has method arguments with default values so you can override the value of a single field or many fields when copying deepcopy - creates a deep copy of a record; doesn t take arguments mutablecopy - creates a shallow copy of a record, with the Mutable trait as its return type mutable - if the underlying implementation is mutable, return this typed as a Mutable trait, otherwise make a mutablecopy tobuilder - creates a new builder that has been initialized to have the same state as this record 2.5 Mutable Trait TODO: the Mutable trait interface is likely to change before being finalized 2.6 Raw Class TODO 2.7 Priming The only way to prime records is through the prime method on DatabaseService, which takes a sequence of records, the field to be primed on those records, and the model to be primed on that field. It optionally takes a sequence of already known foreign records and a Mongo ReadPreference. For example: val checkins: List[Checkin] =... services.db.prime(checkins, Checkin.venueId, Venue) To access the primed foreign object on field foo, use the foofk method on the record, which takes the model of the foreign object as an argument and returns an Option of the foreign object: 2.4. Other Methods 7

12 spindle Documentation, Release val venues: List[Venue] = checkins.flatmap(_.venueidfk(venue)) (This is somewhat clunky, mostly because of having to pass around the model of the foreign object (in this case, Venue) everywhere. This is necessary in order to decouple foreign key fields from the models they point to and so avoid dependency hairballs.) 2.8 Proxies TODO 2.9 Reflection TODO 2.10 Field Descriptors TODO 8 Chapter 2. Records

13 CHAPTER 3 Custom Types In addition to all of the standard Thrift types, Spindle codegen makes available a few extras. 3.1 Enhanced Types Enhanced types are types tagged with an annotation so as to produce either a custom protocol format or a custom Scala type. Enhanced types are defined with the enhanced_types annotation on a Thrift typedef, along with custom logic in the code generator to deal with the enhanced type. For example: // A BSON ObjectId, stored as a binary blob. typedef binary (enhanced_types="bson:objectid") ObjectId // A UTC datetime, stored as millis since the epoch. typedef i64 (enhanced_types="bson:datetime") DateTime Without the enhanced types mechanism, an ObjectId would be serialized as binary over the wire and represented as a ByteBuffer or an Array[Byte] in Scala code. With the enhanced types mechanism, this will be serialized as binary in the binary protocols (TBinaryProtocol, TCompactProtocol) but receive special handling in TBSONObjectProtocol (using the native ObjectId type) and in TReadableJSONProtocol (using a custom ObjectId encoding). In the Scala code, it will be represented as an instance of ObjectId. 3.2 Bitfields In order to use space more efficiently, sometimes you want to store several boolean values into a single integer (i32) or long (i64) value. Spindle calls these fields bitfields. Bitfields come in two variants, with and without set bits. (With set bits, a single boolean value will take two bits, one to determine whether or not the boolean is set, and another for the boolean value itself.) Spindle has some features to make working with bitfields more convenient. You can associate a i32 or i64 field with a bitfield struct. A bitfield struct is a Thrift struct with only boolean fields. If a field foo is marked with a bitfield_struct or bitfield_struct_no_setbits annotation, then an additional foostruct method will be generated which returns a populated boolean struct. Bitfield annotations are applied directly to a class field (not through a typedef), as follows: struct Checkin { 1: optional i32 flags (bitfield_struct="checkinflags") 9

14 spindle Documentation, Release struct CheckinFlags { 1: optional bool sendtotwitter 2: optional bool sendtofacebook 3: optional bool geocheat In this example, the Checkin struct will have all the normal methods for dealing with flags as an i32, as well as a flagsstruct method that returns an instance of CheckinFlags. 3.3 Type-safe IDs You often use BSON ObjectIds as primary keys in Mongo collections. This means common collectons like Checkin and Venue would use the same type as their primary key. In order to avoid errors (such as passing a List[ObjectId] of checkin IDs to a method expecting a List[ObjectId] of venue IDs), Spindle includes a mechanism for tagging common types so they have distinct type-safe version. This behavior is triggered by using the new_type="true" annotation on a typedef. In Scala code, this will turn the type alias into a tagged type, which means it s a new subtype of the aliased type. For example, CheckinId is a tagged ObjectId (unique subtype of ObjectId). Because it s a subtype, you can use CheckinId anywhere you would expect an ObjectId. In order to use an ObjectId where a CheckinId is required, you will need to cast it. A convenience method (with the same name as the type) will be generated to perform this cast. For example: CheckinId(new ObjectId()). Sample usage, in Thrift (ids.thrift): package com.foursquare.types.gen typedef ObjectId CheckinId (new_type="true") typedef ObjectId VenueId (new_type="true") struct Checkin { 1: optional CheckinId id (wire_name="_id") struct Venue { 1: optional VenueId id (wire_name="_id") And in Scala: import com.foursquare.types.gen.idstypedefs.{checkinid, VenueId // cast a regular ObjectId to CheckinId val checkinid: CheckinId = CheckinId(new ObjectId()) // cast a regular ObjectId to VenueId val venueid: VenueId = VenueId(new ObjectId()) // compile error, this won t work because VenueId and CheckinId are different subtypes of ObjectId val checkinid2: CheckinId = venueid // works, because CheckinId is a subtype of ObjectId and can be automatically upcast val unsafecheckinid: ObjectId = checkinid Note that the tagged types live in an object with the same name as the thrift file with Typedefs appended to the end. 10 Chapter 3. Custom Types

15 CHAPTER 4 Enums Enumerations in Thrift are defined with the enum keyword. Enumeration values have names and integer identifiers. When compiled to Scala code, enumerations are represented by a class (of the same name as the enumeration), a companion object, and objects for each of the enumeration values (defined inside the companion object). 4.1 Enum value methods The following methods are available on each value of an enumeration: id - integer id of the enum value name - string name of the enum value, as represented in Thrift source (not intended to be stable) stringvalue - string value of the enum value, as represented by string_value annotation in Thrift (intended to be stable); if there is no annotation, the name is used compare - compare two enum values by their ids meta - access the companion object for the enum 4.2 Companion object methods The following methods are availabel on an enumeration s companion object: findbyid - given an integer id, return an Option of the enum value with that id, or None findbyidornull - given an integer id, return the enum value with that id, or null findbyname - given a string name, return an Option of the enum value with that name, or None findbynameornull - given a string name, return the enum value with that name, or null findbystringvalue - given an string value, return an Option of the enum value with that string value, or None findbystringvalueornull - given an string value, return the enum value with that string value, or null unapply - alias for findbyname (TODO: should be findbystringvalue) 11

16 spindle Documentation, Release Examples Example thrift: enum ClientType { android = 1 blackberry = 2 iphone = 3 web = 4 unknown = 5 Example Scala: val client: ClientType = ClientType.web 12 Chapter 4. Enums

17 CHAPTER 5 Working with Mongo 5.1 Annotations In order to use Spindle structs with Mongo, they must have the required Mongo annotations. mongo_collection - name of the Mongo collection mongo_identifier - name of the Mongo instance There are also a number of optional Mongo annotations: primary_key - the name of the primary key field foreign_key - one or more annotations with names of foreign key fields index - one or more annotations with indexed fields Example: struct Checkin { 1: optional ids.checkinid id (wire_name="_id") 2: optional ids.userid userid (wire_name="uid") 2: optional ids.venueid venueid (wire_name="venueid") (primary_key="id", foreign_key="userid", foreign_key="venueid", index="userid: asc", index="venueid: asc", mongo_collection="checkins", mongo_identifier="foursquare") 5.2 Rogue Queries There are two main differences between Lift Record and Spindle when it comes to creating and executing Rogue queries. First, queries are not created by calling Rogue methods on a model. Queries must be created explicitly by wrapping a model in a SpindleQuery (which we recommend aliasing to Q). Second, queries are not executed by called an execution method on the query, the query must be sent to a SpindleDatabaseService object to execute it. For example: 13

18 spindle Documentation, Release import com.foursquare.rogue.spindle.{spindlequery => Q import com.foursquare.rogue.spindle.spindlerogue._ val q = Q(Checkin).where(_.userId eqs 646).and(_.photoCount > 0) val checkins = db.fetch(q) Here is a basic SpindleDatabaseService implementation: import com.foursquare.rogue.spindle.{spindledbcollectionfactory, SpindleDatabaseService import com.foursquare.spindle.untypedmetarecord import com.mongodb.{db, Mongo, MongoClient, MongoURI object db extends SpindleDatabaseService(ConcreteDBCollectionFactory) object ConcreteDBCollectionFactory extends SpindleDBCollectionFactory { lazy val db: DB = { val mongourl = System.getenv("MONGOHQ_URL") if (mongourl == null) { // For local testing new MongoClient("localhost", 27017).getDB("mydatabase") else { // Connect using the MongoHQ connection string val mongouri = new MongoURI(mongoUrl) val mongo = mongouri.connectdb if (mongouri.getusername!= null && mongouri.getusername.nonempty) { mongo.authenticate(mongouri.getusername, mongouri.getpassword) mongo override def getprimarydb(meta: UntypedMetaRecord) = db override def indexcache = None 14 Chapter 5. Working with Mongo

19 CHAPTER 6 Indices and tables genindex modindex search 15

spindle Documentation

spindle Documentation spindle Documentation Release 2.0.0 Jorge Ortiz, Jason Liszka November 13, 2014 Contents 1 Thrift 3 1.1 Data model................................................ 3 1.2 Interface definition language (IDL)...................................

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Armide Documentation. Release Kyle Mayes

Armide Documentation. Release Kyle Mayes Armide Documentation Release 0.3.1 Kyle Mayes December 19, 2014 Contents 1 Introduction 1 1.1 Features.................................................. 1 1.2 License..................................................

More information

CPSC 3740 Programming Languages University of Lethbridge. Data Types

CPSC 3740 Programming Languages University of Lethbridge. Data Types Data Types A data type defines a collection of data values and a set of predefined operations on those values Some languages allow user to define additional types Useful for error detection through type

More information

Thrift specification - Remote Procedure Call

Thrift specification - Remote Procedure Call Erik van Oosten Revision History Revision 1.0 2016-09-27 EVO Initial version v1.1, 2016-10-05: Corrected integer type names. Small changes to section headers. Table of Contents 1.

More information

The Typed Racket Guide

The Typed Racket Guide The Typed Racket Guide Version 5.3.6 Sam Tobin-Hochstadt and Vincent St-Amour August 9, 2013 Typed Racket is a family of languages, each of which enforce

More information

Type Checking and Type Equality

Type Checking and Type Equality Type Checking and Type Equality Type systems are the biggest point of variation across programming languages. Even languages that look similar are often greatly different when it comes to their type systems.

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Overview. Elements of Programming Languages. Objects. Self-Reference

Overview. Elements of Programming Languages. Objects. Self-Reference Overview Elements of Programming Languages Lecture 10: James Cheney University of Edinburgh October 23, 2017 Last time: programming in the large Programs, packages/namespaces, importing Modules and interfaces

More information

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words. , ean, arithmetic s s on acters Comp Sci 1570 Introduction to C++ Outline s s on acters 1 2 3 4 s s on acters Outline s s on acters 1 2 3 4 s s on acters ASCII s s on acters ASCII s s on acters Type: acter

More information

Typed Racket: Racket with Static Types

Typed Racket: Racket with Static Types Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type

More information

CSCI-GA Scripting Languages

CSCI-GA Scripting Languages CSCI-GA.3033.003 Scripting Languages 12/02/2013 OCaml 1 Acknowledgement The material on these slides is based on notes provided by Dexter Kozen. 2 About OCaml A functional programming language All computation

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

Motivation was to facilitate development of systems software, especially OS development.

Motivation was to facilitate development of systems software, especially OS development. A History Lesson C Basics 1 Development of language by Dennis Ritchie at Bell Labs culminated in the C language in 1972. Motivation was to facilitate development of systems software, especially OS development.

More information

CS 2340 Objects and Design - Scala

CS 2340 Objects and Design - Scala CS 2340 Objects and Design - Scala Objects and Operators Christopher Simpkins chris.simpkins@gatech.edu Chris Simpkins (Georgia Tech) CS 2340 Objects and Design - Scala Objects and Operators 1 / 13 Classes

More information

Lecture 12: Data Types (and Some Leftover ML)

Lecture 12: Data Types (and Some Leftover ML) Lecture 12: Data Types (and Some Leftover ML) COMP 524 Programming Language Concepts Stephen Olivier March 3, 2009 Based on slides by A. Block, notes by N. Fisher, F. Hernandez-Campos, and D. Stotts Goals

More information

Distributed Programming and Remote Procedure Calls (RPC): Apache Thrift. George Porter CSE 124 February 19, 2015

Distributed Programming and Remote Procedure Calls (RPC): Apache Thrift. George Porter CSE 124 February 19, 2015 Distributed Programming and Remote Procedure Calls (RPC): Apache Thrift George Porter CSE 124 February 19, 2015 End-to-end RPC protocol RPC Components Defines messages, message exchange behavior, Programming

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

September 10,

September 10, September 10, 2013 1 Bjarne Stroustrup, AT&T Bell Labs, early 80s cfront original C++ to C translator Difficult to debug Potentially inefficient Many native compilers exist today C++ is mostly upward compatible

More information

Motivation was to facilitate development of systems software, especially OS development.

Motivation was to facilitate development of systems software, especially OS development. A History Lesson C Basics 1 Development of language by Dennis Ritchie at Bell Labs culminated in the C language in 1972. Motivation was to facilitate development of systems software, especially OS development.

More information

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University

G Programming Languages Spring 2010 Lecture 6. Robert Grimm, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 6 Robert Grimm, New York University 1 Review Last week Function Languages Lambda Calculus SCHEME review 2 Outline Promises, promises, promises Types,

More information

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309 A Arithmetic operation floating-point arithmetic, 11 12 integer numbers, 9 11 Arrays, 97 copying, 59 60 creation, 48 elements, 48 empty arrays and vectors, 57 58 executable program, 49 expressions, 48

More information

Using Scala in CS241

Using Scala in CS241 Using Scala in CS241 Winter 2018 Contents 1 Purpose 1 2 Scala 1 3 Basic Syntax 2 4 Tuples, Arrays, Lists and Vectors in Scala 3 5 Binary output in Scala 5 6 Maps 5 7 Option types 5 8 Objects and Classes

More information

Avro Specification

Avro Specification Table of contents 1 Introduction...2 2 Schema Declaration... 2 2.1 Primitive Types... 2 2.2 Complex Types...2 2.3 Names... 5 2.4 Aliases... 6 3 Data Serialization...6 3.1 Encodings... 7 3.2 Binary Encoding...7

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Values and Types We divide the universe of values according to types A type is a set of values and

More information

Typed Scheme: Scheme with Static Types

Typed Scheme: Scheme with Static Types Typed Scheme: Scheme with Static Types Version 4.1.1 Sam Tobin-Hochstadt October 5, 2008 Typed Scheme is a Scheme-like language, with a type system that supports common Scheme programming idioms. Explicit

More information

Static Semantics. Winter /3/ Hal Perkins & UW CSE I-1

Static Semantics. Winter /3/ Hal Perkins & UW CSE I-1 CSE 401 Compilers Static Semantics Hal Perkins Winter 2009 2/3/2009 2002-09 Hal Perkins & UW CSE I-1 Agenda Static semantics Types Symbol tables General ideas for now; details later for MiniJava project

More information

Data Types. Every program uses data, either explicitly or implicitly to arrive at a result.

Data Types. Every program uses data, either explicitly or implicitly to arrive at a result. Every program uses data, either explicitly or implicitly to arrive at a result. Data in a program is collected into data structures, and is manipulated by algorithms. Algorithms + Data Structures = Programs

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

interface MyAnno interface str( ) val( )

interface MyAnno interface str( ) val( ) Unit 4 Annotations: basics of annotation-the Annotated element Interface. Using Default Values, Marker Annotations. Single-Member Annotations. The Built-In Annotations-Some Restrictions. 1 annotation Since

More information

Overview. Elements of Programming Languages. Objects. Self-Reference

Overview. Elements of Programming Languages. Objects. Self-Reference Overview Elements of Programming Languages Lecture 11: James Cheney University of Edinburgh November 3, 2015 Last time: programming in the large Programs, packages/namespaces, importing Modules and interfaces

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Type Inference Some statically typed languages, like ML (and to a lesser extent Scala), offer alternative

More information

Piqi-RPC. Exposing Erlang services via JSON, XML and Google Protocol Buffers over HTTP. Friday, March 25, 2011

Piqi-RPC. Exposing Erlang services via JSON, XML and Google Protocol Buffers over HTTP. Friday, March 25, 2011 Piqi-RPC Exposing Erlang services via JSON, XML and Google Protocol Buffers over HTTP 1 Anton Lavrik http://piqi.org http://www.alertlogic.com 2 Overview Call Erlang functions using HTTP POST : Server

More information

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

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

C# and Java. C# and Java are both modern object-oriented languages

C# and Java. C# and Java are both modern object-oriented languages C# and Java C# and Java are both modern object-oriented languages C# came after Java and so it is more advanced in some ways C# has more functional characteristics (e.g., anonymous functions, closure,

More information

Question No: 1 ( Marks: 1 ) - Please choose one One difference LISP and PROLOG is. AI Puzzle Game All f the given

Question No: 1 ( Marks: 1 ) - Please choose one One difference LISP and PROLOG is. AI Puzzle Game All f the given MUHAMMAD FAISAL MIT 4 th Semester Al-Barq Campus (VGJW01) Gujranwala faisalgrw123@gmail.com MEGA File Solved MCQ s For Final TERM EXAMS CS508- Modern Programming Languages Question No: 1 ( Marks: 1 ) -

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering CSC40232: SOFTWARE ENGINEERING Professor: Jane Cleland Huang Canonical Form sarec.nd.edu/courses/se2017 Department of Computer Science and Engineering Canonical Form Canonical form is a practice that conforms

More information

8 Understanding Subtyping

8 Understanding Subtyping Object-Oriented Design Lecture 8 CS 3500 Fall 2010 (Pucella) Friday/Tuesday, Oct 8/12, 2010 8 Understanding Subtyping Subtpying is a great way to enable client-side reuse, requiring a client to write a

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2018 Lecture 7b Andrew Tolmach Portland State University 1994-2018 Dynamic Type Checking Static type checking offers the great advantage of catching errors early And

More information

PART I SQLAlchemy Core

PART I SQLAlchemy Core PART I SQLAlchemy Core Now that we can connect to databases, let s begin looking at how to use SQLAlchemy Core to provide database services to our applications. SQLAlchemy Core is a Pythonic way of representing

More information

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) CSE 413 Languages & Implementation Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) 1 Goals Representing programs as data Racket structs as a better way to represent

More information

Project 6 Due 11:59:59pm Thu, Dec 10, 2015

Project 6 Due 11:59:59pm Thu, Dec 10, 2015 Project 6 Due 11:59:59pm Thu, Dec 10, 2015 Updates None yet. Introduction In this project, you will add a static type checking system to the Rube programming language. Recall the formal syntax for Rube

More information

Connexion Documentation

Connexion Documentation Connexion Documentation Release 0.5 Zalando SE Nov 16, 2017 Contents 1 Quickstart 3 1.1 Prerequisites............................................... 3 1.2 Installing It................................................

More information

CS321 Languages and Compiler Design I Winter 2012 Lecture 13

CS321 Languages and Compiler Design I Winter 2012 Lecture 13 STATIC SEMANTICS Static Semantics are those aspects of a program s meaning that can be studied at at compile time (i.e., without running the program). Contrasts with Dynamic Semantics, which describe how

More information

The Decaf Language. 1 Lexical considerations

The Decaf Language. 1 Lexical considerations The Decaf Language In this course, we will write a compiler for a simple object-oriented programming language called Decaf. Decaf is a strongly-typed, object-oriented language with support for inheritance

More information

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

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

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

CS 430 Spring Mike Lam, Professor. Data Types and Type Checking CS 430 Spring 2015 Mike Lam, Professor Data Types and Type Checking Type Systems Type system Rules about valid types, type compatibility, and how data values can be used Benefits of a robust type system

More information

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

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

IntWritable w1 = new IntWritable(163); IntWritable w2 = new IntWritable(67); assertthat(comparator.compare(w1, w2), greaterthan(0));

IntWritable w1 = new IntWritable(163); IntWritable w2 = new IntWritable(67); assertthat(comparator.compare(w1, w2), greaterthan(0)); factory for RawComparator instances (that Writable implementations have registered). For example, to obtain a comparator for IntWritable, we just use: RawComparator comparator = WritableComparator.get(IntWritable.class);

More information

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14 C introduction Variables Variables 1 / 14 Contents Variables Data types Variable I/O Variables 2 / 14 Usage Declaration: t y p e i d e n t i f i e r ; Assignment: i d e n t i f i e r = v a l u e ; Definition

More information

Protocol Buffers, grpc

Protocol Buffers, grpc Protocol Buffers, grpc Szolgáltatásorientált rendszerintegráció Service-Oriented System Integration Dr. Balázs Simon BME, IIT Outline Remote communication application level vs. transport level protocols

More information

CSCI S-Q Lecture #12 7/29/98 Data Structures and I/O

CSCI S-Q Lecture #12 7/29/98 Data Structures and I/O CSCI S-Q Lecture #12 7/29/98 Data Structures and I/O Introduction The WRITE and READ ADT Operations Case Studies: Arrays Strings Binary Trees Binary Search Trees Unordered Search Trees Page 1 Introduction

More information

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml COSE212: Programming Languages Lecture 3 Functional Programming in OCaml Hakjoo Oh 2017 Fall Hakjoo Oh COSE212 2017 Fall, Lecture 3 September 18, 2017 1 / 44 Why learn ML? Learning ML is a good way of

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

Avro Specification

Avro Specification Table of contents 1 Introduction...2 2 Schema Declaration... 2 2.1 Primitive Types... 2 2.2 Complex Types...2 2.3 Names... 5 3 Data Serialization...6 3.1 Encodings... 6 3.2 Binary Encoding...6 3.3 JSON

More information

Announcements/Follow-ups

Announcements/Follow-ups Announcements/Follow-ups Midterm #2 Friday Everything up to and including today Review section tomorrow Study set # 6 online answers posted later today P5 due next Tuesday A good way to study Style omit

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

Data Types. Outline. In Text: Chapter 6. What is a type? Primitives Strings Ordinals Arrays Records Sets Pointers 5-1. Chapter 6: Data Types 2

Data Types. Outline. In Text: Chapter 6. What is a type? Primitives Strings Ordinals Arrays Records Sets Pointers 5-1. Chapter 6: Data Types 2 Data Types In Text: Chapter 6 1 Outline What is a type? Primitives Strings Ordinals Arrays Records Sets Pointers Chapter 6: Data Types 2 5-1 Data Types Two components: Set of objects in the type (domain

More information

Apache Avro. Sharing and managing data efficiently

Apache Avro. Sharing and managing data efficiently Apache Avro Sharing and managing data efficiently Scott Carey Apache Avro PMC Chair Principal Architect, RichRelevance scottcarey@apache.org March 6, 2012 What is Apache Avro? "Apache Avro is a data serialization

More information

Overloading, Type Classes, and Algebraic Datatypes

Overloading, Type Classes, and Algebraic Datatypes Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827

More information

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003 Data abstractions: ADTs Invariants, Abstraction function Lecture 4: OOP, autumn 2003 Limits of procedural abstractions Isolate implementation from specification Dependency on the types of parameters representation

More information

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

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

Ruby: Objects and Dynamic Types

Ruby: Objects and Dynamic Types Ruby: Objects and Dynamic Types Computer Science and Engineering College of Engineering The Ohio State University Lecture 5 Primitive vs Reference Types Recall Java type dichotomy: Primitive: int, float,

More information

CSE 431S Type Checking. Washington University Spring 2013

CSE 431S Type Checking. Washington University Spring 2013 CSE 431S Type Checking Washington University Spring 2013 Type Checking When are types checked? Statically at compile time Compiler does type checking during compilation Ideally eliminate runtime checks

More information

Framework Fundamentals

Framework Fundamentals Questions Framework Fundamentals 1. Which of the following are value types? (Choose all that apply.) A. Decimal B. String C. System.Drawing.Point D. Integer 2. Which is the correct declaration for a nullable

More information

JSR-305: Annotations for Software Defect Detection

JSR-305: Annotations for Software Defect Detection JSR-305: Annotations for Software Defect Detection William Pugh Professor Univ. of Maryland pugh@cs.umd.edu http://www.cs.umd.edu/~pugh/ 1 Why annotations? Static analysis can do a lot can even analyze

More information

Scala. Fernando Medeiros Tomás Paim

Scala. Fernando Medeiros Tomás Paim Scala Fernando Medeiros fernfreire@gmail.com Tomás Paim tomasbmp@gmail.com Topics A Scalable Language Classes and Objects Basic Types Functions and Closures Composition and Inheritance Scala s Hierarchy

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

17 From Delegation to Inheritance

17 From Delegation to Inheritance Object-Oriented Design Lecture 17 CS 3500 Spring 2011 (Pucella) Friday, Mar 18, 2011 17 From Delegation to Inheritance Last time, we saw how to reuse code from the implementation of Point in CPoint via

More information

Data Types In Text: Ch C apter 6 1

Data Types In Text: Ch C apter 6 1 Data Types In Text: Chapter 6 1 Outline What is a type? Primitives Strings Ordinals Arrays Records Sets Pointers 2 Data Types Two components: Set of objects in the type (domain of values) Set of applicable

More information

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

From C++ to Java. Duke CPS

From C++ to Java. Duke CPS From C++ to Java Java history: Oak, toaster-ovens, internet language, panacea What it is O-O language, not a hybrid (cf. C++) compiled to byte-code, executed on JVM byte-code is highly-portable, write

More information

Googles Approach for Distributed Systems. Slides partially based upon Majd F. Sakr, Vinay Kolar, Mohammad Hammoud and Google PrototBuf Tutorial

Googles Approach for Distributed Systems. Slides partially based upon Majd F. Sakr, Vinay Kolar, Mohammad Hammoud and Google PrototBuf Tutorial Protocol Buffers Googles Approach for Distributed Systems Slides partially based upon Majd F. Sakr, Vinay Kolar, Mohammad Hammoud and Google PrototBuf Tutorial https://developers.google.com/protocol-buffers/docs/tutorials

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 7a Andrew Tolmach Portland State University 1994-2016 Values and Types We divide the universe of values according to types A type is a set of values and a

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2016 Lecture 4a Andrew Tolmach Portland State University 1994-2016 Pragmatics of Large Values Real machines are very efficient at handling word-size chunks of data (e.g.

More information

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors

More information

Structure of Programming Languages Lecture 10

Structure of Programming Languages Lecture 10 Structure of Programming Languages Lecture 10 CS 6636 4536 Spring 2017 CS 6636 4536 Lecture 10: Classes... 1/23 Spring 2017 1 / 23 Outline 1 1. Types Type Coercion and Conversion Type Classes, Generics,

More information

COMP-520 GoLite Tutorial

COMP-520 GoLite Tutorial COMP-520 GoLite Tutorial Alexander Krolik Sable Lab McGill University Winter 2019 Plan Target languages Language constructs, emphasis on special cases General execution semantics Declarations Types Statements

More information

Types and Programming Languages. Lecture 5. Extensions of simple types

Types and Programming Languages. Lecture 5. Extensions of simple types Types and Programming Languages Lecture 5. Extensions of simple types Xiaojuan Cai cxj@sjtu.edu.cn BASICS Lab, Shanghai Jiao Tong University Fall, 2016 Coming soon Simply typed λ-calculus has enough structure

More information

COS 140: Foundations of Computer Science

COS 140: Foundations of Computer Science COS 140: Foundations of Computer Science Variables and Primitive Data Types Fall 2017 Introduction 3 What is a variable?......................................................... 3 Variable attributes..........................................................

More information

pybdg Documentation Release 1.0.dev2 Outernet Inc

pybdg Documentation Release 1.0.dev2 Outernet Inc pybdg Documentation Release 1.0.dev2 Outernet Inc April 17, 2016 Contents 1 Source code 3 2 License 5 3 Documentation 7 Python Module Index 15 i ii Bitloads, or bit payloads, are compact payloads containing

More information

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 4 Professional Program: Data Administration and Management JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) AGENDA

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

SNU Programming Language Theory

SNU Programming Language Theory SNU 4541.574 Programming Language Theory Polymorphism Polymorphism We encountered the concept of polymorphism very briefly last time. Let s look at it now in a bit more detail. # let rec last l = match

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

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

Status Report. JSR-305: Annotations for Software Defect Detection. William Pugh Professor JSR-305: Annotations for Software Defect Detection William Pugh Professor Status Report Univ. of Maryland pugh@cs.umd.edu http://www.cs.umd.edu/~pugh/ 1 This JSR is under active development Slides have

More information

Inductive Data Types

Inductive Data Types Inductive Data Types Lars-Henrik Eriksson Functional Programming 1 Original slides by Tjark Weber Lars-Henrik Eriksson (UU) Inductive Data Types 1 / 42 Inductive Data Types Today Today New names for old

More information

The story so far. Elements of Programming Languages. Pairs in various languages. Pairs

The story so far. Elements of Programming Languages. Pairs in various languages. Pairs Elements of Programming Languages Lecture 6: Data structures James Cheney University of Edinburgh October 9, 2017 The story so far We ve now covered the main ingredients of any programming language: Abstract

More information

13 Subtyping Multiple Types

13 Subtyping Multiple Types Object-Oriented Design Lecture 13 CS 3500 Spring 2011 (Pucella) Tuesday, Feb 22, 2011 13 Subtyping Multiple Types The goal in this lecture is to look at creating types that are subtypes of multiple types

More information

CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Dan Grossman Spring 2011

CS152: Programming Languages. Lecture 11 STLC Extensions and Related Topics. Dan Grossman Spring 2011 CS152: Programming Languages Lecture 11 STLC Extensions and Related Topics Dan Grossman Spring 2011 Review e ::= λx. e x e e c v ::= λx. e c τ ::= int τ τ Γ ::= Γ, x : τ (λx. e) v e[v/x] e 1 e 1 e 1 e

More information

A brief introduction to C programming for Java programmers

A brief introduction to C programming for Java programmers A brief introduction to C programming for Java programmers Sven Gestegård Robertz September 2017 There are many similarities between Java and C. The syntax in Java is basically

More information

// the current object. functioninvocation expression. identifier (expressionlist ) // call of an inner function

// the current object. functioninvocation expression. identifier (expressionlist ) // call of an inner function SFU CMPT 379 Compilers Spring 2015 Assignment 4 Assignment due Thursday, April 9, by 11:59pm. For this assignment, you are to expand your Bunting-3 compiler from assignment 3 to handle Bunting-4. Project

More information

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University

CS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University CS558 Programming Languages Winter 2018 Lecture 4a Andrew Tolmach Portland State University 1994-2018 Pragmatics of Large Values Real machines are very efficient at handling word-size chunks of data (e.g.

More information

Software Construction

Software Construction Lecture 7: Type Hierarchy, Iteration Abstraction Software Construction in Java for HSE Moscow Tom Verhoeff Eindhoven University of Technology Department of Mathematics & Computer Science Software Engineering

More information

Boolean expressions. Elements of Programming Languages. Conditionals. What use is this?

Boolean expressions. Elements of Programming Languages. Conditionals. What use is this? Boolean expressions Elements of Programming Languages Lecture 3: Booleans, conditionals, and types James Cheney So far we ve considered only a trivial arithmetic language L Arith Let s extend L Arith with

More information

The Typed Racket Reference

The Typed Racket Reference The Typed Racket Reference Version 5.1 Sam Tobin-Hochstadt February 14, 2011 #lang typed/racket/base #lang typed/racket 1 1 Type Reference Any Any Racket value. All other types are subtypes of Any. Nothing

More information

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information

The Pyth Language. Administrivia

The Pyth Language. Administrivia Administrivia The Pyth Language Lecture 5 Please make sure you have registered your team, created SSH keys as indicated on the admin page, and also have electronically registered with us as well. Prof.

More information