Subjective-C 2.0. Multithreaded Context-Oriented Programming with Objective-C

Size: px
Start display at page:

Download "Subjective-C 2.0. Multithreaded Context-Oriented Programming with Objective-C"

Transcription

1 UNIVERSITÉ CATHOLIQUE DE LOUVAIN LOUVAIN SCHOOL OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Subjective-C 2.0 Multithreaded Context-Oriented Programming with Objective-C Promoter: Co-advisor: Reader: Kim MENS Sebastián GONZÁLEZ Peter VAN ROY Thesis submitted in partial fulfillment of the requirements for the degree M.Sc. in Computer Science option Software Engineering and Programming Systems by Damien RAMBOUT Louvain-la-Neuve Academic year

2 Acknowledgments First and foremost, I want to thank Dr. Sebastián GONZÁLEZ for all the time he devoted to me and my thesis. He s been such a great inspiration and has been really good at giving advice. I would not have been able to achieve such a work without his help. I am also grateful to Prof. Kim MENS who proposed me this interesting subject. Even with his tight schedule, he always found time to plan meetings. This brought me a very good follow-up which helped me to make a thesis that I can be proud of. He has always been a friendly and open-minded teacher and promoter. I also want to thank Prof. Peter VAN ROY for accepting to be a reader for my thesis. This is much appreciated as I know it takes some of his precious time. I thank the members of my family for all the support they brought me through these years. They always helped me through the best and the worst and I am really thankful for that. I want to thank Julian for all his encouragements and his friendship. Somehow, he made these years easier by being always in such a good mood. I have one thing to say: we did it! I also thank my friends for all the support and encouragements they provided me through these years. Finally, I am grateful to my pet dog Kirby for the encouraging barks while I needed concentration. Damien Rambout i

3 Contents Preface vii Typographical Conventions vii Case Study vii Benchmark Operating Procedures ix I Preliminaries 1 1 Introduction Motivation Problem Objectives Approach Contributions Roadmap Background Context-Oriented Programming Main Concepts ContextL Ambience Summary Objective-C and Subjective-C Objective-C as Base Language Concepts Used to Implement Subjective-C Subjective-C Context Context Method Context Manager Method Dispatcher Context Declaration Subjective-C 1.0 Parser Limitations of Subjective-C II Subjective-C Overview Basic Syntax of Subjective-C Context Method Declaration ii

4 CONTENTS iii Context Manager and Method Dispatcher Interaction with Contexts Local Context ECDL Extension Activating a Local Context Retrieving a Local Context Resend Mechanism Context Activation and Deactivation Callback Context Activation Event Notifications Registering for a Notification Context Activation Event Details Subjective-C Class Diagram Conclusion Local Dispatch Overview Limitations of Global Dispatch Characteristics of a Local Dispatch System Implementation Requirements General Architecture of the Local Dispatch System Local Dispatcher Algorithm Return Type Specific Dispatcher Motivation Definition of Local Dispatchers as C Functions Reference to a Local Dispatcher Method Argument Processors Motivation Definition of Argument Processors as C functions Reference to a List of Argument Processors Dynamic Method Invocation Method Signature Information Filling Method Arguments Definition of Dynamic Method Invocation Discussion Performance Local Dispatch at Compile Time Fault Tolerance Conclusion Local Contexts Overview Limitations of Global Contexts Characteristics of a Local Context Implementation Requirements Local Context Representation Local Context Data Structure Thread-Local Information Cleaning Process of Thread-Local Information Thread-Local Context State Activation Events

5 CONTENTS iv Modifying Context State External Activation Events Activation Event Effect Discussion Performance Pending activation queue Using the Thread Dictionary Conclusion Resend Mechanism Problems of the Supercontext Mechanism Resend Calls History Principle Motivation Multiple Histories Recursive Calls within Context Methods Inter-Method Calls Multiple Histories in Subjective-C Definition Resend Algorithm Definition of Resend Call NSObject Class Extension Discussion Performance Fault Tolerance Conclusion Context Method Finder New Context Method Precedence Properties Context Activation Age Local Context Presence Property Precedence Order Algorithms Find Best Context Method Find Next Context Method Discussion Time Spent for Retrieving the Activation Age of a Context Time Spent for Knowing if a Context Method is a Candidate Time Spent for Finding the Best Context Method Time Spent for Finding the Next Context Method Conclusion Subjective-C Parser Keyword Translations Keywords EBNF Grammar Translation Phase Parser State Machine Whole File Translation Example Conclusion

6 CONTENTS v III Validation Case Study Implementation Entity-relationship Diagram Triangle Entity Moving a Triangle Checking if a Triangle is Out of Bounds Reversing a Triangle Controller Entity Changing a Triangle Orientation Pausing Triangles Toggling Dashed Lines Logging Triangle Moves View Entity Drawing Dashed Lines Conclusion IV Conclusion Future Work Parameters and Return Types of Locally Dispatched Methods Context Method Finder s Additional Disambiguity Rules Advanced Context-method Ordering Context Ordering Optimizations Cached Search Results Subjective-C Core in Plain C Metaobject Protocol (MOP) Advanced Context Methods Declarations Contextual Blocks Improving the Subjective-C Parser Context Inference Engine Improving the Thread Information Cleaning Process Xcode Integration Conclusion Discussion Thesis Context Key Aspects of the Developed Solution Advantages and Limitations of the Developed Solution Achievement of Objectives Conclusion V Appendixes 149 A Subjective-C and Xcode 150 A.1 Requirements Creation Step by Step A.2 Project Creation Step by Step

7 CONTENTS vi Bibliography 154 Glossary 156 Acronyms 158 Index 159

8 Preface Typographical Conventions To make the dissertation easier to comprehend, I have used several typographical conventions. In particular, I used different colors and fonts for representing classes, variables, methods, macros or context-oriented programming (COP) concepts such as contexts. These conventions are described in Table 1. Concept Variable Method Class C Macro Keyword Relation Context Constant Primitive type Representation acontext contextwithname: NSString Exclusion Happy SCContextDidActivate unsigned int Table 1: Typographical conventions Case Study To ease the reading of this thesis, an ios case study application was developed in Subjective-C. Code snippets used throughout this dissertation are taken from this case study so that the whole dissertation seems more coherent to the reader. Note that Part I of this text uses a version of this case study written in Subjective-C 1.0 because the Subjective-C 2.0 syntax is not introduced yet. The next parts use a version written in Subjective-C 2.0. In the Subjective-C 1.0 s version, only one moving triangle is allowed 1 while the application is running. Description The application developed as a case study is called Triangles 2. A triangle has several properties: An orientation: up, down, left or right. 1 This is due to the fact that Subjective-C 1.0 is not thread-safe and therefore it is not recommended to create several threads dealing with contexts. 2 In the Subjective-C 1.0 s version, it is simply made of one moving triangle. vii

9 CONTENTS viii A color: depending on its orientation. A line type: dashed or not. In additional to these properties, the user has the possibility to temporarily pause the triangle and to log its movements. The triangle automatically changes its direction to the opposite one when it hits one of the screen boundaries. Figure 1: Triangles case study explanatory screenshot Figure 1 illustrates the application with a triangle moving upwards, drawn with dashed cyan lines. Contexts The application is made of several contexts: Orientation: used to define the orientation of each triangle. Pause: used to pause the triangles moves.

10 CONTENTS ix Logging: used to log a selected triangle s moves. Dashed: used to dash the triangles lines. The context Orientation is refined into two sub-levels. The first sub-level is made of the contexts Horizontal and Vertical representing the orientation of a triangle as horizontal or vertical. The second sub-level is made of the contexts Left, Right, Up and Right. Left and Right refine Horizontal by representing the concrete orientations left or right. On the other side, Up and Down refine Vertical by representing the concrete orientation up or down. The more general contexts can be useful when one needs to define a more general action. It can also be powerful for deactivating an orientation context without knowing what is the triangle current orientation. Figure 2 illustrates the context graph of Triangles. Further information about the notation used in this graph is given in Section For the moment, keep in mind that this graph mainly Logging Dashed Pause Orientation Legend: Vertical Horizontal Context Local context Context Global context Inclusion Up Down Left Right Exclusion Figure 2: Triangles case study context graph specifies that none of Up, Down, Left and Right can be active at the same time for a same triangle. The graph also specifies the refinement levels between the orientation contexts. Benchmark Operating Procedures This dissertation contains several benchmarks in order to quantify the performance of Subjective- C 2.0. The benchmarks have been executed on a MacBook with a 2.4 GHz C2D processor with 2 GB of RAM, running under Mac OS X Except if explicitly indicated, those benchmarks have been performed with Xcode Instruments by repeating a same experiment between and times and using the average resulting value. Xcode Instruments provide simple tools for measuring or profiling programs with few overhead.

11 Part I Preliminaries 1

12 Chapter 1 Introduction Contents 1.1 Motivation Problem Objectives Approach Contributions Roadmap Motivation Nowadays, people are using more and more mobile devices that provide them a way to access information about the surrounding world, the people they are connected to, the place where they are at a specific moment, and so on. These applications require some configuration or acceptation to provide information that is relevant to the user. These configuration steps might occur either at first launch time or at various times while using the application. The first case is often specific to the user because most of the time it is about giving information about the user to the application (e.g. user account login and password) so that the application is able to create a default environment. But the second case might be about adapting the application corresponding to the user environment or the events that have occurred in the past. These adaptation steps can be easily solved thanks to context-oriented programming (COP). 1.2 Problem Popular programming languages do not provide simple mechanisms to deal with changing environments. While it is easy to create a program responding to external events, it is much more complicated to adapt the behavior of this program depending on the information received from these events. The typical strategy used for adapting the behavior of a program to incoming information is to process this information through a series of conditional statements. This has the effect to produce a less readable and therefore less maintainable software. Even though it is possible to solve this problem thanks to various design patterns such as State pattern [GHJV94], it quickly becomes difficult to design a software that should change its behavior corresponding to heterogeneous contexts. 2

13 CHAPTER 1. INTRODUCTION 3 Subjective-C [MGLG10], introduced in 2010, provides a simple and convenient way to create adaptive softwares in Objective-C for Cocoa Touch 1 applications. Subjective-C 1.0 allows to easily design softwares adapting their behavior to a given set of global contexts, that is, contexts having an impact on the whole software. This usually reify situations happening in the logical and physical environment in which the application is executing. This environment is external to the application (e.g. the current temperature, the availability of a Wi-fi connection,... ). However, Subjective-C 1.0 was no designed for being used with multi-threaded applications and therefore lacks a notion of contexts that are local to a selected set of threads or to a block of instructions. This excludes adaptation to scenarios such as enabling a logging mode for a thread, activating a tracing mode for a downloading thread or easily implementing a concurrent program using state pattern. These internal contexts are called local contexts. For instance, a parser could be implemented by using local contexts. When a parser analyzes a file, it goes through several different states depending on the words encountered in the file. All these states can be represented by a set of exclusive contexts 2. If several files need be parsed at the same time (i.e. concurrently), one parsing thread can be created per file. Given that several threads can be in a different parsing state at a same moment, it implies that several different contexts can be active at the same time. In this case, global contexts are unsuitable because their state is global to the whole set of threads and therefore a context activation in one thread would have an impact on every other threads. This violates the rules stating that the set of contexts should be exclusive to each other. This problem can be solved by using thread-local contexts for which the activation would only have an impact for the thread they are activated. By using local contexts, each context is exclusive to each other inside a single thread. 1.3 Objectives The main objective of this thesis is to investigate how it is possible to add support for local contexts to Subjective-C. This objective implies to find a way to make Subjective-C threadsafe so that it could be used with multi-threaded applications. Furthermore, this dissertation measures the impact of using these local contexts on the global performance of an application. More importantly, a comparison with global contexts is made to evaluate the advantages and the limitations of local contexts in an application written in Subjective-C. A secondary objective is to improve the way a Subjective-C application adapts its behavior to the currently active contexts. In its current implementation, Subjective-C adapts the behavior of a program by checking the state of the contexts defined for this program. Subjective-C 2.0 goes one step further by taking the age 3 of a context into account to infer an importance level between contexts. Therefore, a context that has been activated after another one is considered as more important. This modification implies the reimplementation of the mechanism in charge of determining what behavior the program should adopt. These objectives have brought a lot of refactoring and therefore a better implementation of Subjective-C s platform. This will simplify future modifications of this platform and this is therefore an important side-objective of this work. 1 Cocoa Touch is the main framework used to create applications on ios system. 2 Two contexts are exclusive to each other when both contexts cannot be active at the same time. 3 The age of a context provides information to determine whether a context has been activated before another context.

14 CHAPTER 1. INTRODUCTION 4 A last objective is to simplify the use of Subjective-C and make Subjective-C compliant sources even clearer by introducing simple and expressive keywords. These keywords are supposed to simplify the use of the main concepts brought by Subjective-C. ios platform was chosen for Subjective-C 1.0 for obvious reasons such as platform popularity or an exposure to several external context changes. Indeed, using a platform designed for mobile devices implies better chances to observe context changes. Nevertheless, Subjective- C 2.0 should be compatible with Mac OS X platform too. Using a desktop-class platform makes sense given that thread-local contexts are more often related to an internal state of the application and are therefore not influenced by a changing external environment. 1.4 Approach As described in Section 1.3, the main objective is to allow the use of thread-local contexts. To achieve this goal, the strategy used to solve this problem was to make every mechanism work without the help of the Subjective-C Parser but rather by enhancing the library that handles contexts at runtime. The reason to this approach is that every feature of Subjective-C 2.0 should be available by using the core of this language, that is, the library written in Objective- C. The purpose of the parser is to translate a special Subjective-C syntax that is provided for simplifying the creation of Subjective-C applications. Therefore the parser should never become mandatory to Subjective-C. The implementation of local contexts should take advantage of the existing implementation for global contexts. Therefore, the context class has been subclassed to only redefine the bare minimum which needs to be redefined for storing and using information related to the current thread. The Subjective-C Parser has been reimplemented to allow the use of new syntactic keywords that ease the use of Subjective-C. A proof-of-concept was developed to test the new mechanisms implemented in Subjective- C 2.0. A qualitative analysis has been made from this case study in order to present the benefits and weaknesses of using Subjective-C 2.0. This analysis serves to validate the work achieved through this thesis. Subjective-C 2.0 has been designed by focusing on the conception rather than on the optimization. This principle is based on the fact that a simple and elegant design is often easy to optimize. The development of Subjective-C 2.0 tried to stick to the following principles: Objective-C s conventions (i.e. naming, structure and pattern conventions) must be respected as much as possible. The global performance must be good. Subjective-C 1.0 s capabilities must remain a subset of Subjective-C 2.0 s capabilities. In other words, Subjective-C 2.0 can add features but cannot remove the ones present in Subjective-C 1.0. Nevertheless, Subjective-C 2.0 can improve existing features 4. 4 Nevertheless, there won t be full backward compatibility because of syntax changes between the two versions of Subjective-C.

15 CHAPTER 1. INTRODUCTION 5 Delegate less to the Subjective-C Parser and more to the Subjective-C s library. A parser that would transform numerous symbols is less maintainable than a library that would offer the same functionalities. Only the library should be used for adding new features to Subjective-C. The parser should never become mandatory to use this context-oriented language. Most of Subjective-C s complexity must be hidden to the user. Therefore, main Subjective- C mechanisms should be accessible through an easy and intuitive syntax. 1.5 Contributions This thesis offers the following contributions: Implementation of a notion of local contexts that are only active inside defined threads. A new method dispatching system is introduced to adapt the behavior of an application to these local contexts at method call time. A new resend mechanism that allows to call another context-specific version of a same original method 5. Mac OS X compatibility to allow to use Subjective-C on a non-mobile development platform. A set of intuitive keywords that ease the use of Subjective-C 2.0 capabilities. These keywords allow to use Subjective-C 2.0 s features without making explicit calls to the core of this language. A case study providing an application of main Subjective-C s features. A validation of the work achieved through this thesis by analyzing the case study developed for this thesis. A manual that explains how to create and compile Subjective-C applications with Xcode Roadmap The thesis is organized as follows: The thesis starts with presenting the prerequisites to the understanding of Subjective- C 2.0 s concepts. It explores the COP paradigm: existing COP languages and paradigm possibilities. This part continues with an explanation of the choice of Objective-C as a base language. It also gives a good overview of Subjective-C 1.0 s capabilities and internals. The second part is about Subjective-C 2.0. It is divided into six chapters: Chapter 3 is a description of the capabilities of Subjective-C 2.0. It presents the changes that have been made in the architecture and the new possibilities with respect to Subjective-C 1.0. Chapter 4 presents the principle and implementation of the local dispatch system that is a prerequisite to the implementation of local contexts. Chapter 5 explains the underlying mechanisms of the notion of local contexts, how it works and how it is implemented. Chapter 6 describes the new resend mechanism. It gives details about its implementation and discusses its performance. 5 An original method is a method for which one or several context-specific definitions are provided. In some other context-oriented languages, it is also referred as a base method. 6 Xcode is the most used environment to develop Mac OS X and ios applications on Mac OS X system.

16 CHAPTER 1. INTRODUCTION 6 Chapter 7 is a description of the Context Method Finder s algorithms. The module presented in this chapter is the most important one in Subjective-C as it is used for finding appropriate context methods with respect to currently active contexts. It is therefore the module that is in charge of defining the behavior that a program should adopt when a set of contexts is active. Chapter 8 explains the parsing details of the new Subjective-C Parser. The third part is the validation and is made of one chapter. Chapter 9 makes a comparison of the case study with a similar application developed in plain Objective-C in terms of maintainability, readability and performance. This chapter aims to find the advantages and limitations of Subjective-C compared to Objective-C. The last part is the conclusion. It provides a summary of this thesis and talks about interesting future work for Subjective-C.

17 Chapter 2 Background Contents 2.1 Context-Oriented Programming Main Concepts ContextL Ambience Summary Objective-C and Subjective-C Objective-C as Base Language Concepts Used to Implement Subjective-C Subjective-C Context Context Method Context Manager Method Dispatcher Context Declaration Subjective-C 1.0 Parser Limitations of Subjective-C This chapter provides the necessary background to understand the concepts introduced in Part II of this dissertation. Section 2.1 introduces the COP paradigm with its basic concepts and precursor languages. Section 2.2 explains the choice of Objective-C as base language for Subjective-C. Finally, Section 2.3 is a complete summary of Subjective-C 1.0 s concepts. 2.1 Context-Oriented Programming Programming paradigms have always been improved to include more and more information with the actions performed through a program. This additional information helps designing adaptive programs. Hirschfeld et al. [HCH07] presents this evolution as an addition of dimensions to procedural programming. In procedural programming, an action is defined through a procedure. Object-oriented programming adds a dimension to procedural programming by 7

18 CHAPTER 2. BACKGROUND 8 including the receiver in the dispatch system and therefore varying the result of an action depending on its receiver. Subjective programming adds another dimension by including the source (sender) of the action. These paradigms lack information dedicated to easily create programs that adapt their behavior to their environment. Context-oriented programming (COP) is an emerging paradigm that aims to ease the creation of dynamic programs with capabilities to adapt their behavior to the context they are facing. An adaptive behavior may imply varying the reaction of a program to similar actions or restricting the access to certain data depending on the current context Main Concepts The separation of crosscutting concerns is an important issue of modern program language design ([AHHM09]). COP is a new approach to the dynamic composition of crosscutting concerns by easing the design of programs adapting their behavior to an environment or a context. Behavioral variations are represented by partial method definitions that can dynamically override or extend their respective base methods. Hirschfeld et al. [HCH07] identifies the main properties of a context-oriented language: Behavioral variations: The design of a context-oriented program is based on behavioral variations. Typically, these variations are based on partial definitions of modules of the underlying programming model such as procedures, methods, or classes. Context: According to González et al. [GCM + 10], a context is an abstraction of the particular state of affairs or set of circumstances for which specialized application behavior can be defined. In COP, an object is viewed in different ways depending on the current context ([CH05]). Layers: There needs to be a way to regroup the behavioral variations of a program. Most of the time, these groups are called layers. In some context-oriented languages, no distinction is made between a context and a layer. Context-oriented languages also allow to create compositions of layers. Activation/deactivation: A context-oriented language provides a way to modify the state of a layer. Explicit control should be provided to the programmer to activate or deactivate a layer at runtime. These activation events are the keys to behavioral variations of a running program. Scope: The scope of a layer activation or deactivation can be controlled explicitly by the programmer to limit the impact of an activation event. Depending on the programming language, the impact of a layer activation event will be local to a thread, local to an instruction block or global to the whole application. Most of the time, a context-oriented language is an extension to an existing language with the properties of COP. For instance, ContextL is an extension to Common Lisp, ContextS is an extension to Smalltalk and ContextJ is an extension to Java. The extension of an existing language can be about creating a specific context-oriented syntax or simply provide an Application Programming Interface (API) giving access to COP concepts. The concrete definition of COP properties may differ from one context-oriented language to another. For instance, some languages only allow partial definition of methods because of limitations of the programming language they are relying on. Less restrictive base programming languages allow to vary the access to variables too.

19 CHAPTER 2. BACKGROUND 9 As said previously, extending an existing programming language implies different approaches to implement COP concepts: Creating a new syntax and translating a COP program source code at compile-time to make it compliant with a base language. Taking advantage of reflective possibilities of the base language. Smalltalk is an example of a highly reflective language. Using a proxy approach for intercepting messages and adapting the program behavior by analyzing the current situation. The next sections present two context-oriented languages, ContextL and Ambience. ContextL is based on Common List Object System (CLOS) and is a language using layers with an activation impact local to an instruction block whereas Ambience is based on Common Lisp and is a language using contexts (i.e. layers) with a global activation impact ContextL ContextL [CH05], introduced in 2005, is considered as the first context-oriented language. It is an extension to CLOS and works by using macros and reflection. This section gives an overview of this language. ContextL extends object-oriented concepts such as classes and methods by introducing the notion of layer. These concepts must be declared as layered for being able to extend their definition for various layers. Layers are created by using the macro deflayer. Declaring a layer in ContextL ( deflayer logging- layer ) Once a layer is defined, it is possible to activate it for an instruction block with the macro with-active-layer so that this layer is only active during the execution of the wrapped block. Several layers can be activated at once. This layer activation strategy has a thread-local impact (i.e. scope) on the behavioral variations of the program. Declaring a context in ContextL ( with- active- layer ( logging- layer )... contained code...) A layer named t defines the root layer. This layer is always active and is used to defined default behaviors. The macro defined-layered-class allows to declare layered classes. Once a class is declared as layered, it can be extended with additional partial definitions. Each of these partial definitions is related to a specific layer. This means that a partial definition related to a specific layer becomes accessible within a certain scope as soon as this layer is activated for this scope.

20 CHAPTER 2. BACKGROUND 10 Defining a layered class in ContextL ( define- layered- class person : in- layer logging- layer ()...) A generic function can be layered by using the macro define-layered-function: Defining a layered function in ContextL ( define- layered- function display- object ( object )) Using this macro declares the function as layered and allows to extend its definition with partial methods by using the macro define-layered-method: Defining a layered method in ContextL ( define- layered- method display- object : in- layer t (( object person ))... method body...) Here, the root layer t is used to define a variation of the method that is used when no other layer is active. It can be seen as the default method definition. Additional definitions (partial methods) can be provided to extend the existing definitions of the method display-object with various layers (e.g. the layer logging-layer). In ContextL, only the most specific method is invoked for a given call. There exists a mechanism that lets more specific methods invoke less specific methods. For instance if the method display-object is called with the layer logging-layer activated, the partial definition related to logging-layer will be invoked. This partial definition can decide to invoke a less specific method such as the one defined for the root layer t. Activating a layer locally to an instruction block in ContextL ( defvar * chewbacca * ( make-instance person...) ) ( with- active- layers ( logging- layer ) ( display- object * chewbacca *)) In this example, logging-layer is only active in the block calling display-object on chewbacca. Therefore, its activation impact is local to the thread executing the instruction block Ambience Ambience [GMH07, Gon08, GMC08] is a context-oriented language based on a Common Lisp. Ambience defines an extension to CommonLisp named Ambience Object System (AmOS) that allows prototype-based and context-oriented programming. It is different from ContextL on several sides but mainly because a layer activation has a global impact. In Ambience, layers are called contexts and partial method definitions are called multimethods. Most of messages (i.e. method calls) are delegated to the current context in which multimethod context-oriented specializations are defined.

21 CHAPTER 2. BACKGROUND 11 A context in Ambience can be declared through the macro defcontext: Declaring a context in Ambience ( off- hook ) Once a context is declared, it can be used to define a context method with with-context which is the analogous of with-active-layer in ContextL. Both switch the context, and the code they contain is executed in that context. In Ambience, a method definition holds for the current context in which that definition is found. That is, when a method is defined, it is specialized on its context of definition Defining a context method in Ambience ( with- off- hook ( defmethod receive (( phone- call ) ( ))... context method body...) ) This partial definition of the method receive will only be executed when the is active. A context can be activated with the method active. On the other hand, it can be deactivated with the method deactivate. Declaring a context in Ambience ( ) ( ) Ambience sees contexts as objects representing physical or logical properties of the environment in which the system is running. Transient contexts represent changing states of the environment Contexts that have a more permanent nature are named features. Transient contexts are parts of features (in the previous is part Contexts are therefore part of a context graph in which messages are delegated. This graph is used to define the current context, which is a composition of all active contexts. In Ambience, only the most specific method is invoked for a given call. All applicable methods are linearized, and more specific methods can decide to invoke less specific methods by means of a resend mechanism. Ambience is also based on a specific parser because the language provides a Smalltalk-like surface syntax to ease the design of context-oriented applications. Using Ambience Smalltalk-like surface syntax in - context : logging do: [ receive : call ( phone - call ) on: phone ( mobile - phone ) [... method body... ]. ] The previous example defines a context method with the selector receive:on: for the context logging. The Ambience parser would translate this into the following piece of Common Lisp source code.

22 CHAPTER 2. BACKGROUND 12 Ambience parser translation ( with- context logging ( defmethod receive : on; (( call ( phone-call )) ( phone ( mobile-phone )))... method body...) ) Summary The main properties of a context-oriented language are always the same: behavioral variations, contexts, layers and activation events. A context in Ambience is a first-class reification of a situation taking place in the execution environment of the application (i.e. Off-hook, Belgium,...). That is, contexts in this kind of languages are objects that represent situations, and these contexts are then used to create dynamic programs. In contrast, ContextL does not think of layers as reifications of anything. Conceptually, layers are purely a composition mechanism. The intention of a layer is not to reify something in the execution environment. In the majority of context-oriented languages (ContextL and its derivates), the layer activation scope is local to a thread and to an instruction block. In other languages like Ambience, an activation has an impact on the whole application (i.e. a global impact). Section 2.3 shows that Subjective-C 1.0 is inspired from Ambience on several sides. Every context in Subjective-C 1.0 is global and therefore its activation has an impact on the whole application. Subjective-C is also based on a precompilation phase for translating a specific syntax into calls to the core of Subjective-C. Nevertheless, the design of those two languages is radically different. Ambience s design uses multiple dispatch and delegation-based inheritance to achieve COP. Subjective-C 1.0 uses global pre-dispatch through implementation switching, and context relationships instead of any form of inheritance. Part II of this dissertation presents Subjective-C 2.0. This new version of Subjective-C implements the notion of local contexts which adds an additional thread-local scope to partial method definitions. This dissertation therefore shows how a context-oriented language can reconcile global contexts and local contexts at the same time. 2.2 Objective-C and Subjective-C Subjective-C is a context-oriented language being an extension to Objective-C. This section explains the choice of Objective-C as a base language and what main concepts of this base langauge are used to design a context-oriented language like Subjective-C Objective-C as Base Language Objective-C is an object-oriented layer added to the C language. It includes all the objectoriented principles such as inheritance, encapsulation, abstraction and polymorphism. Inspired by Smalltalk, it is designed as a very dynamic language. For instance, it is possible to send a message 1 to an objet that does not handle this kind of message. In this case, the Objective-C s runtime system ask the target object if the message should be forwarded to another object 2. 1 A message is a bit similar to a method call in other languages like Java. 2 By default, an exception is thrown.

23 CHAPTER 2. BACKGROUND 13 This comes from the fact that the runtime system of Objective-C always checks whether an object can handle the messages that are sent to this object. The dynamic side of this language provides an advanced reflection layer 3 (or Metaobject Protocol (MOP)). This reflection layer is made of an introspection part and an intercession part. The introspection part provides utility functions for retrieving meta-information about Objective-C objects such as classes, methods, method implementations, instance variables,... The intercession part allows to add object-oriented abstractions such as classes, protocols or methods at runtime. It also allows to modify existing information such as a method implementation. This advanced reflection layer is one of the main reason of Objective-C choice as the Subjective- C s base language. This is due to the fact that Subjective-C s core is mainly based on method implementation replacements. This makes things transparent to the user and very efficient in practice. A less reflective language like Java 4 requires to either modify the compiled sources (i.e. the byte code) or to use a proxy mechanism for redirecting method calls. Another reason is that Objective-C is supported by the ios mobile platform which is running on devices like the iphone or the ipad. Mobile devices a more exposed to context variations because of their mobility property. A third reason about choosing Objective-C is that this language is a superset of C language. As a superset of C, it is possible to build highly optimized code, if needed, to improve some costly mechanisms. This combination of an advanced high-level reflective language together with the possibility of deploying this new COP paradigm on real mobile devices and the high performance possibilities provided by C is what influenced the choice of this platform and language. Nevertheless, there is one reason against Objective-C as a base language. Objective-C doesn t use a pure message-passing model (i.e. there are C function calls, direct variable accesses, structure field accesses, and other mechanisms that bypass message passing). If all mechanisms were strictly implemented through message passing, like in Smalltalk, every possible action in the system would be adaptable to a context. In contrast, in Objective-C only the parts that use message passing are adaptable Concepts Used to Implement Subjective-C Several concepts from the Objective-C s MOP are used to implement Subjective-C s functionalities. The concept of method replacement is extensively used throughout this dissertation. This concept comes from the intercession part of the Objective-C s reflection layer and is the main mechanism that allows Subjective-C to transparently modify application behavior at runtime. This method replacement concept combined with the ability of retrieving the implementation of certain methods allows to implement a mechanism for exchanging the implementation of a method with another one, at runtime. Subjective-C is therefore mainly based on the Objective-C s reflection layer for implementing the COP aspects of the language. 3 See Objective-C Runtime Reference. 4 Java does not provide an intercession part in its reflection layer.

24 Context-Oriented Programming (COP) is an emerging programming paradigm in which contextual information plays a central role in the definition of application behaviour [9,12,19]. The core of context-oriented programming consists in the ability to overlay adapted behaviour on top of existing default behaviour, according to the circumstances in which the software is being used. Such adaptations 2. are BACKGROUND meant to gracefully adjust the service level of the application, fol- 14 CHAPTER lowing detected changes in the execution environment. COP languages provide dedicated programming abstractions to enable this behavioural adaptability to 2.3 Subjective-C changing contexts. 1.0 This section presents the COP core on which Subjective-C is based. The language is introduced progressively, as these core mechanisms are This section is a summary of the capabilities of Subjective-C 1.0. It discusses the concept of explained. context in Subjective-C and the roles of the Context Manager and the Method Dispatcher. It also presents the Subjective-C compilation process. The information is taken from [GCM + 10] 2.1 General System Architecture and [MGLG10]. Subjective-C has been conceived for a fairly straightforward system architecture, Figure 2.1 illustrated [GCM + in 10] Fig. illustrates 1. Context the general information architecture is received of Subjective-C mainly from and two shows sources. that context information may come from mainly two sources. World Sensors Actuators Context Discovery external context information internal Context Management Application Behaviour arbitrated context changes context effect Active Context Fig. 1. Figure General 2.1: architecture General system for context-aware architecture systems. There is Firstly, a Context therediscovery a context module discovery thatmodule is in charge whichof collects collecting sensor data datacoming to make from the physical world thanks to several sensors, and from the logical world such as network data. This module may differ from one platform to another but is generally mainly assured by the host Operating System (OS). For instance, under ios, the event loop takes care of collecting external data updates such as Global Positioning System (GPS) or compass data. These data are then processed by the application to extract context information from them. The application can also provide internal context information. This information is more about logical contexts such as the logging mode in the case study. These context data are collected by a Context Management module (see Section and Section 2.3.4) which makes an analysis of the current situation and commits a coherent set of changes to the active context representation. The coherence is assured thanks to context relations (see Section ). The application s behavior is adapted dynamically thanks to a context method mechanism (see Section 2.3.2) Context In Subjective-C 1.0, contexts can be used to define multiple methods sharing a same base method signature but defining a different behavior. Each method behavior should be related to the contexts assigned to their corresponding method. For instance, a method defined for a logging context should log something. All these methods are called context methods and each context method denotes one variation 5 of an original method 6. Snippet 2.1 shows two 5 A variation of an original method is a synonym for context method. In other words, it is a context-specific partial definition of an original method. 6 An original method is a method for which several context-specific variations are defined. An original method does not define a specific implementation but rather defines the method called by the user (a context method is

25 CHAPTER 2. BACKGROUND 15 Snippet 2.1: First Subjective-C 1.0 example - ( void ) move { // Default version // Move triangle # context Logging - ( void ) move { // Log triangle s move variations of a same method move. The first variation of the method move has no context assigned. Its implementation therefore acts as the default method 7 for the original method move (see Section 2.3.2). The second variation of this method is defined for the Logging context and is in charge of logging the move of a triangle. Logging is said to be part of the related contexts of the context method it is associated to Context Activation Events A context is always in one of the two following states: active or inactive. A context activation or deactivation is called an activation event. Figure 2.2 illustrates the state machine of a context. As shown in this state machine, a context is always inactive when it is created. Activating a deactivate inactive deactivate activate activate active Figure 2.2: Context state machine context when it is already active keeps it in the same state. But one deactivation is enough for changing a context state back to inactive. Deactivating an inactive context has no effect. A context can be activated by calling the Context Manager (see Section 2.3.3) as shown in Snippet 2.2 with the context Pause. The name of the context must be provided in an Objective- C string form. A context deactivation follows the same principle as shown in Snippet 2.3. Note that in Snippet 2.3, the method pausetriangles: has been divided into two context-specific variations. The first variation is called when the context Pause is active (i.e. to unpause the game), otherwise the second variation is called. never used through a direct call). In other context-oriented languages, an original method is also referred as a base method. 7 A default method should not be confused with an original method. A method is referred as the default method because its implementation is not define for a set of contexts. On the other side, an original method represents the method called by the user. See Section for further details about implementation replacement of an original method.

26 CHAPTER 2. BACKGROUND 16 Snippet 2.2: Activating a context - ( IBAction ) pausetriangles :( id) sender { [ CONTEXT activatecontextwithname :@" Pause "]; Snippet 2.3: Deactivating a context # context Pause - ( IBAction ) pausetriangles :( id) sender { // Unpause game [ CONTEXT deactivatecontextwithname :@" Pause "]; # context! Pause - ( IBAction ) pausetriangles :( id) sender { // Pause game [ CONTEXT activatecontextwithname :@" Pause "]; Although these explicit activation and deactivation requests work fine, ideally most of these should be handled implicitly by the Context Manager, as in Ambience [Gon08] for instance. See Chapter 10 for details about the implementation of such a mechanism as a future work Contexts Relations Sometimes the state of a context might become inconsistent with regard to other context states. For instance, The context Up should not be active when Vertical is not active anymore. Context relations ensure that all the properties defined between several contexts are always verified. Besides the Not relation (see Section 2.3.2), used for declaring a link between a context and its opposite, there exists 4 binary relations: Exclusion, Strong inclusion, Weak inclusion and Requirement. Finally, there exists one n-ary relation called Composition. The following figures and tables are taken from [GCM + 10]. Here are the meanings of the table rows: canactivate, when the source or target context of the relation can be activated. YES means that it can always be activated from the studied relation. Otherwise, the result of the operation is the result of a message sent to the source or target context of the relation. candeactivate, when the source or target context of the relation can be deactivated. YES means that it can always be deactivated. NO means that is can never be deactivated from the studied relation. Otherwise, the result of the operation is the result of a message sent to the source or target context of the relation. activate, the impact of activating the source or target context of the relation. The use of the character means that the operation has no impact. deactivate, the impact of deactivating the source or target context of the relation. The use of the character means that the operation has no impact. Assuming that A and B are two different contexts:

27 CHAPTER 2. BACKGROUND 17 Exclusion Between A and B means that both contexts cannot be active at the same time. In other words, if A is active, then B cannot be activated, and vice versa. Note that both contexts can be inactivate at the same time. Figure 2.3 shows how this relation is visually represented. Vertical Horizontal Figure 2.3: Exclusion relation Table 2.1 shows the specification of this relation. message source context target context canactivate target isinactive source isinactive candeactivate YES YES activate deactivate Table 2.1: Exclusion specification Inclusion From A to B means that the activation of A implies the activation of B. There exists two types of Inclusion relation. The first one is called Weak inclusion and means that A can still remain active if B is deactivated. But if A is deactivated, then so must B. Figure 2.4 shows an example representation of this relation. Cafeteria Noisy Figure 2.4: Weak inclusion relation Table 2.2 shows the specification of this relation. message source context target context canactivate YES YES candeactivate YES YES activate target activate deactivate target deactivate Table 2.2: Weak inclusion specification The second type of inclusion is called Strong inclusion and means that if B is deactivated, then A must be deactivated too. In this type of inclusion, A can only be activated if B can be activated (see row canactivate ). Figure 2.5 shows how this relation is visually represented. Table 2.3 shows the specification of this relation. Requirement From A to B means that A cannot be activated when B is inactive. Figure 2.6 shows how this relation is visually represented.

28 CHAPTER 2. BACKGROUND 18 Up Vertical Figure 2.5: Strong inclusion relation message source context target context canactivate target canactivate YES candeactivate YES source candeactivate activate target activate deactivate target deactivate source deactivate Table 2.3: Strong inclusion specification Logging Triangle Selected Figure 2.6: Requirement relation Table 2.4 shows the specification of this relation. message source context target context canactivate target isactive YES candeactivate YES source candeactivate activate deactivate source deactivate Table 2.4: Requirement specification Composition From A to several contexts means that the activation of A is implied when all the target contexts in the same Composition are active at the same time. On the other side, as soon as one of the target contexts is deactivated, A is asked for being deactivated too. Figure 2.7 shows how this relation is visually represented. Moonsoon Season Asia Summer Figure 2.7: Composition relation Table 2.5 shows the specification of this relation. All these relations are sufficient for defining basic relations between contexts. These properties must be seen like predicates that are always verified thanks to Subjective-C internal automatic mechanisms working at runtime (i.e. when trying to activate or deactivate a context, Subjective- C s runtime system will check these constraints and execute the corresponding activations and deactivations when needed). It is important to note that activating or deactivating of a context

29 CHAPTER 2. BACKGROUND 19 message source context target context canactivate target isactive YES candeactivate NO YES activate source activate deactivate source deactivate Table 2.5: Composition specification c does only successfully happen if every context in relation with c accepts 8 this activation or deactivation. As explained in this section, a context is the most basic abstraction in Subjective-C. Its state can either be active or inactive and properties can be defined between several contexts, thanks to relations, to have a finer control on variations of context states. The next section explains the concept of context method which is another very important abstraction in Subjective-C Context Method The concept of context method is used to define various behaviors for a base same method signature, but for different contexts. Technically speaking, a context method is thus a method for which contexts have been associated. The behavior of each context method is supposed to be specific to the contexts they are related to. All context methods sharing the same method signature are said to be extending the same original method. Each context method is said to be a variation of its respective original method Candidate Context Method Snippet 2.4 shows the definition of two context methods for the original method move. The first variation is defined for no contexts whereas the second variation is defined for contexts Pause and Logging. A context method is said to be a candidate for its respective original Snippet 2.4: Associating several contexts with a method - ( void ) move { // Move triangle //... # context Pause Logging - ( void ) move { NSLog (@" Game is paused "); // Do nothing method when all its related contexts are active at the same time. A candidate context method is a context method that is likely to be used when its respective original method is called. The Context Method Finder is in charge of finding the most appropriate (i.e. the best) context 8 The acceptance of a context to an activation event of another context is defined by the relations existing between these two contexts.

30 CHAPTER 2. BACKGROUND 20 method among a set of candidates (see Section 2.3.4). For instance, the second variation of the method move shown in Snippet 2.4 becomes a candidate for this original method as soon as Pause and Logging contexts are active at the same time. The first variation is always a candidate (see Section ) Precedence Order Between Context Methods Several context methods might be candidates for the same original method at the same time. This case is called a context methods conflict. A notion of context method priority exists in Subjective-C to determine what variation of a method should be called when several variations are conflicting. The context method with the highest priority takes precedences over all the other context methods extending the same original method. Snippet 2.5 shows an example with the two variations of the original method move that are ordered thanks to the priority of the second variation. When contexts are not exclusive to each other (i.e. when no Exclusion re- Snippet 2.5: Defining a priority for a context method - ( void ) move { // Move triangle # context Logging # priority ( void ) move { // Log triangle s move # context Pause # priority ( void ) move { // Do nothing lation is defined between them), a precedence order must be defined between context methods. This precedence order is redefined every time a new context method is added at runtime with a specific priority. Note that if no priority is explicitly defined, a context method is assigned the lowest possible priority. Section gives further details about context method structures and context method precedence order rules Default method It is sometimes needed to have a method with a default behavior, that is, a method that would be called when no candidate exists for its respective original method. This method is called the default method and corresponds to a method with no related contexts. For instance, in Snippet 2.5, the first method definition acts as the default method for the original method move. It is important to specify that a default method denotes the default behavior of an original method. An original method simply denotes the structure used for method implementation

31 CHAPTER 2. BACKGROUND 21 replacements. The default method is like a context method but with no contexts assigned 9. It is therefore always a candidate for its respective original method. Note that an error occurs at call time when there exists no candidate for the original method called and no default method has been defined for this original method. Section gives further details about the role of a default method Context Methods Specific to Inactive Contexts A context method might want to become a candidate for its respective original method when several contexts are inactive. A Subjective-C program can refer to the inactive state of a context thanks to the not notation. It is said there exists a Not relation between the context and its opposite 10. Snippet 2.6 shows a variation of the method pausetriangles: that can become a candidate as soon as the context Pause becomes inactive. Snippet 2.6: Associating the opposite of a context with a method # context! Pause - ( IBAction ) pausetriangles :( id) sender { // Pause game [ CONTEXT activatecontextwithname :@" Pause "]; Now that the concepts of context, context method, method priority and not notation have been introduced, the general Extended Backus Naur Form (EBNF) syntax for context-specific method definitions can be defined as follows: Context method definition EBNF syntax # context ([!] contextname )+ # priority < number >] methoddefinition Supercontext Mechanism It is possible to call, from a context method, another candidate method variation with a lower precedence thanks to supercontext mechanism. This mechanism calls the next context method for the original method for which the source context method is defined. In Subjective-C 1.0, the next context method is the candidate context method that follows the source context method of the supercontext call in an ordered array of context methods related to the same original method. Figure 2.8 shows an array of context methods in which cm 4 is the next context method corresponding to cm 1, and cm 7 is the next context method corresponding to cm 4. Note that because the candidate status of a context method is variable, the chain of next context methods changes as soon as a context method becomes or stops being a candidate. Figure 2.9 shows how a supercontext call works in the background: 9 Nevertheless, in Subjective-C 1.0, it is not exactly seen as a context method, contrary to Subjective-C The Not relation must not be confused with the Exclusion relation. With the Not relation, two contexts cannot be inactive at the same time. There is always one of both that is active.

32 CHAPTER 2. BACKGROUND 22 Ascending priority Priority 1000 Priority 800 Priority 0 cm1 cm2 cm3 cm4 cm5... cm6 cm7... next next Figure 2.8: Context methods ordered by priority in Subjective-C The source calls the Method Dispatcher (see Section 2.3.4) to prepare the supercontext call. 2. The source calls the context method, like it would call any other method. 3. The source calls the Method Dispatcher to restore thecontext method. Source MethodDispatcher 1. prepare supercontext method for "move" 2. call "move" 3. restore context method find supercontext method change method implementation find source context method change method implementation Figure 2.9: Supercontext call sequence diagram The example of Snippet 2.7 shows a case where a logging context is defined to log the triangle s moves. Given that Loging is active, when a call is made to the method move, Subjective- C first makes a call to the variation defined for this context, because of the higher priority defined for this context method. Then, the supercontext call redirects this call to the default implementation 11. Subjective-C 1.0 allows to store the result of a supercontext call into a variable with a very specific syntax: [supercontext isoutofbound] => aboolean; The result of this supercontext call is then stored in the variable aboolean. Snippet 2.8 shows the supercontext call translated into standard Objective-C code. 11 A default method has always a lower priority than the other context methods.

33 CHAPTER 2. BACKGROUND 23 Snippet 2.7: Calling the supercontext method - ( void ) move { movepoint (&a, xoffset, yoffset ); movepoint (&b, xoffset, yoffset ); movepoint (&c, xoffset, yoffset ); movepoint (& center, xoffset, yoffset ); if ([ self isoutofbounds ]) { [ self reverse ]; # context Logging # priority ( void ) move { NSLog (@" Moving from %@", self ); [ supercontext move ]; Snippet 2.8: Supercontext call translated in Objective-C [ MANAGER callsupercontextmethod selector ( isoutofbound ) forclass :[ self class ]]; aboolean = [ self isoutofbound ]; [ MANAGER restorecontextmethod selector ( isoutofbound ) forclass :[ self class ]]; Context Manager The Context Manager has the job to manage the creation of contexts. It can be called with the C macro CONTEXT. Its responsibilities are: Adding contexts to the system Removing contexts from the system Activating a context from its name Deactivating a context from its name Adding or removing links between groups of contexts Giving information about a context state Method Dispatcher Subjective-C is made of an important method dispatching module. This module can be called with the C macro MANAGER. In Subjective-C, dispatching a method consists in mapping the calls of this method to a specific implementation. This can be achieved in two different ways, either by method implementation replacements or by dynamic invocations at method call time. In Subjective-C 1.0, the contextoriented messages (i.e. context method calls) sent to an object are dispatched by using the implementation replacement strategy, as shown in Section

34 CHAPTER 2. BACKGROUND 24 All these context-oriented method implementations are stored in data structures that are updated by this method dispatching module. It is possible to define or delete context methods thanks to this module, as shown in Section This module is made of a submodule that is in charge of finding the best method implementation 12 corresponding to a specific original method. This submodule is called the Context Method Finder. It is called every time a context activation or deactivation occurs in view to replace the implementation of concerned original method. Details about the Context Method Finder are shown in Section Figure 2.10 illustrates the general architecture of the method dispatching module. Note that Method Dispatcher Context Method Finder Context Methods Storage Context Activations Handler Supercontext calls handler Figure 2.10: Method dispatcher architecture the Method Dispatcher is also in charge of handling supercontext calls, as already explained in Section Data Structures The context methods defined in a context-oriented application are stored in a three-levels structure as shown on Figure The first level is a dictionary for which keys are class names and values are a second level dictionary. The classes used as values are the ones containing context methods. The second level is a dictionary for which keys are original selectors and values are a third level array. An original selector is the selector of an original method for which context methods are defined (e.g. In Snippet 2.7, move is the original selector). This distinction is made because the context method selectors are renamed by Subjective-C Parser 13 at compilation time. For instance, the method move would be renamed Context Logging move if a variant of this original method was defined for the context Logging. The third level is an ordered array of context methods. This array is ordered by context method priority so that the context methods with a higher priority take precedence over the ones with a lower priority. If two methods have the same priority then the order between these two methods is the one in which the context methods are registered at runtime. 12 This is also called the best context method 13 See Section for further details about Subjective-C parser.

35 CHAPTER 2. BACKGROUND 25 Level 1 Level 2 Level 3 Dictionary Dictionary Array<ContextMethod *> Class Dictionary Selector Array ContextMethodA ClassA ClassB SelectorA SelectorB ContextMethodB... Array<ContextMethod *> ContextMethodC Dictionary ContextMethodD Selector Array... SelectorC SelectorD priority priority Figure 2.11: Three-level context methods data structure Figure 2.12 shows another structure that stores all the context methods defined for a specific context. It is a dictionary where keys are context names and values are arrays of context methods that are associated to the key context. The purpose of this structure is to speed up the context updates with fast access to corresponding context methods. Dictionary Context Dictionary ContextA ContextB Array<ContextMethod *> ContextMethodA ContextMethodB... Array<ContextMethod *> ContextMethodC ContextMethodD... Figure 2.12: Structure that stores all the context methods associated to specific context Finally, there is a last structure that stores the default method implementation, as shown in Figure The default method implementation is the initial implementation of an original method. Note that if no default implementation is explicitly provided, Subjective-C will use a generic implementation which simply generates an error. Dictionary Method IMP OriginalMethodA ImplementationA OriginalMethodB ImplementationB Figure 2.13: Structure that stores default methods implementation

36 CHAPTER 2. BACKGROUND Method Implementations Replacement System The Method Dispatcher relies on Objective-C s reflection capabilities to handle context activation events. The initial original method implementation becomes the default method implementation and is stored in the structure shown in Figure When a context is activated, Subjective-C looks for all methods defined for this context, get the implementation of the most relevant context method (i.e. the one with the highest priority and with all related contexts active) for each of these methods and use these implementations to replace the current ones. This job is actually delegated to the Context Method Finder introduced in the next section. A context deactivation has the exact same effect as Subjective-C always look for the currently active contexts to find the most relevant methods. The implementation of an original method is always replaced when a context activation event occurs. Figure 2.14 shows the Method Dispatcher behavior at startup. When a context-oriented pro- Default Variation 1 Original Variation 1 Original Version 2 Variation 2 (a) Startup (b) Default implementation storage Figure 2.14: Method dispatcher behavior at startup gram starts up, the Method Dispatcher is not aware of any context method, as shown on Figure 2.14a. The first step is for Subjective-C to register them in the corresponding data structures (see Figure 2.11 and 2.12). When the first context variation of an original method is registered to the Method Dispatcher, the default method implementation is stored for later use (see Figure 2.13). This is what Figure 2.14b represents. The arrow represents the storage of the default method implementation, based on the original method starting implementation. Figure 2.15 shows the Method Dispatcher reactions to context activation events. A dashed arrow represents a method implementation replacement. Figure 2.15a shows that whenever a context is activated, the Method Dispatcher checks whether the context methods related to this context became a candidate for their respective original method and whether the Method Dispatcher should use their implementation for an implementation replacement. Figure 2.15b shows the opposite case. As soon as no more context method are candidate for their respective original method, the default implementation is used for an implementation replacement. As explained in this section, the original method implementation changes every time a context activation event occurs. The aim of this property is to always ensure that all the original method implementations correspond to their respective best context method (or default method) implementation. This job is achieved thanks to the Context Method Finder. Next section explains in details the algorithm used by the Context Method Finder.

37 CHAPTER 2. BACKGROUND 27 Default Default Original Variation 1 Original Variation Variation 2 Variation 2 (a) All context of variation 1 are active (b) No context methods fit currently active contexts Figure 2.15: Method dispatcher behavior on context activation events Context Method Finder Finding the best context method corresponding to the currently active contexts is delegated to a submodule called the Context Method Finder. Before having a look at the algorithm used in Subjective-C 1.0, it is needed to define the properties taken in account by the Context Method Finder. These properties have been defined in a formal way to avoid any ambiguity. Three order relations have been defined between context methods: o =, o > and o <. In Subjective- C 1.0, these three relations are directly defined in terms of the priority of each context method. These relations define a partial order between context methods. Before defining these relations in details, a few sets and functions must be defined: CONT EXT CMET HOD CANDIDAT E CMET HOD contexts : CMET HOD {c c CONT EXT prior : CMET HOD Z state : CONT EXT {active, inactive the set of contexts the set of context methods the set of candidate context methods the contexts for which a context method is defined the priority of a context method the state of a context Given that m 1 and m 2 are two context methods, m 1 o = m2 when they have the same priority. m 1 CMET HOD, m 2 CMET HOD : m 1 o = m2 prior(m 1 ) = prior(m 2 ) Given that m 1 and m 2 are two context methods, m 1 o < m2 when the priority of m 1 is lower than the priority of m 2. m 1 CMET HOD, m 2 CMET HOD : m 1 o < m2 prior(m 1 ) < prior(m 2 ) A similar reasoning applies to m 1 o > m2. A candidate context method is defined in the following way: m CMET HOD, c contexts(m) : m CANDIDAT E state(c) = active

38 CHAPTER 2. BACKGROUND 28 As a consequence of this definition, a context method is not a candidate as soon as one of its related context is inactive. A precedence relation between two context methods can be defined: p >. It is said that a context method m 1 takes precedence over another context method m 2 if m 1 o > m2 or if m 1 o = m2 and m 1 is a candidate when m 2 is not. In a more formal way: m 1, CMET HOD, m 2 CMET HOD : m 1 p > m2 m 1 o > m2 (m 1 o = m2 m 1 CANDIDAT E m 2 CANDIDAT E) A similar reasoning applies to m 1 p < m2. The Context Method Finder s job is to find all context methods that take precedence over all other methods defined for the same original method, as defined by this precedence relation. Several context methods can be retrieved because two context methods can have the same priority and be candidate at the same time. The Context Method Finder then chooses one context method among all the ones that have been identified as taking precedence over all the others (with the relation p >). Figure 2.16 illustrates the Context Method Finder algorithm as a flow chart. This shows that Find Best Method Context methods remaining NO No context method YES Related contexts remaining NO Best context method found NO YES YES Next context is active Figure 2.16: Subjective-C 1.0 find best context method flow chart the Context Method Finder goes through all the context methods related to the same original method. For each of these context methods, the state of each context for which it is defined is checked. As soon as an inactive context is found, the next context method is analyzed. When all the contexts related to a context method are active, then this context method is considered as the best context method. In other words, the algorithm stops as soon as a candidate context method is found. When no candidate could be found after going through all the context methods, then the Context Method Finder uses the default method. Algorithm 1 defines the Context Method Finder algorithm in pseudo-code, which is an application of the flow chart illustrated in Figure As expected, the algorithm receives an array of context methods in input. This array must be ordered by ascending context method priority.

39 CHAPTER 2. BACKGROUND 29 Algorithm 1: Subjective-C 1.0 find the best context method in an ordered array Input: An array ms of context methods extending the same original method and that is ordered by ascending priority Input: A default method dm that defines the default behavior of the same original method as the context methods in ms Output: The first best context method encountered or dm if there is no candidate for all m in ms do candidate Y ES for all c in m related contexts do if c is inactive then candidate NO {A context is not active for this context method break end if end for if candidate = Y ES then return m {The best context method is found end if end for return dm {Return the default method It is one of the level three array introduced in previous section. This algorithm gives the first best context method found in this ordered array. To retrieve this first best context method, it goes through the input array and tests each context method to find the first candidate. If not candidate method can be found, then it returns the related default method Context Declaration Previous sections introduce the notion of context as a state of the environment. A context declares a named space in which behavioral variations (i.e. context methods) can be defined for a context-oriented program. These behavioral variations might 14 be adopted by the contextoriented program when the context for which they are defined becomes active. This section explains how these contexts and the relations between each of these contexts can be declared in a file that is external to the program. Subjective-C 1.0 introduced a simple and straightforward way to declare the contexts used in a program and the relations between them. To achieve such a task, a new language called Easy Context Declaration Language (ECDL) is provided. An ECDL file is divided into two sections: 1. Context declarations, containing a list of context names separated by a new line character. 2. Context relations declarations, containing a list of context relations separated by a new line character. This section is optional. The context declarations section always precedes the context relations declaration section. An ECDL file always ends with the word END and usually has a.sc extension. 14 Depending on the choices made by the Context Method Finder.

40 CHAPTER 2. BACKGROUND Contexts Declaration File Snippet 2.9 shows the declaration of the contexts for the Triangles application. The line Contexts: must precede the list of contexts. A context name is made of any alphanumerical character and must not contain white spaces. Snippet 2.9: Contexts relations declaration section in a ECDL file Contexts : Orientation Vertical Horizontal Up Down Left Right Pause Dashed Contexts Relations Declaration Snippet 2.9 shows the declaration of the context relations for the Triangles application. The line Links: must precede the declaration of context relations. Snippet 2.10: Contexts declaration section in a ECDL file Links : Vertical =H=> Orientation Horizontal =H=> Orientation >< ( Vertical Horizontal ) Up =H=> Vertical Down =H=> Vertical >< ( Up Down ) Left =H=> Horizontal Right =H=> Horizontal >< ( Left Right ) Table 2.6 shows ECDL context relations symbols and their meaning. Each symbol is preceded Relation kind ECDL symbol Exclusion >< Soft Inclusion =S=> Hard Inclusion =H=> Requires =R=> Table 2.6: ECDL symbols and followed by a non-empty list of contexts declared in the previous section. For instance, an exclusion link between Up and Down on one side and Left and Right on the other side would look like: ( Up Down ) >< ( Left Right )

41 CHAPTER 2. BACKGROUND 31 The exclusion relation allows to easily make several contexts mutually exclusive to each other. For instance, if one wants to make Up, Down, Left and Right mutually exclusive to each other, then the context relations declaration would look like: >< ( Up Down Left Right ) Declaring a context or a relation in Subjective-C is thus a very simple task. Note that these contexts and relations can also be defined within Subjective-C itself. The next section explains how these external declarations are translated into such internal calls to the Subjective-C API, thanks to the Subjective-C Parser Subjective-C 1.0 Parser Subjective-C is a language that adopts a hybrid approach by providing its services through a library and extending Objective-C with a new syntax for simplifying the use of some of these services. Previous sections present Subjective-C 1.0 runtime characteristics with several concept such as context state, candidate context method, method implementation replacement and Context Method Finder. This sections intends to explain the work that is done at compile time by the Subjective-C Parser to analyze and translate the new syntax and the declarations contained in the ECDL file ECDL File Parsing The first job of the Subjective-C Parser is to collect the contexts declared in the external ECDL file. Thus, the parser firstly goes through the first section containing all the context names. One call to the Context Manager is added for each context encountered to add it to the system. Then, it analyzes the context relations declared in the second section of the file and adds a call to the Context Manager for each of these relations, in order to define these relations at program startup. Figure 2.17 illustrates this parsing phase with two contexts and one context relation declaration. ECDL file CONTEXTS: A B LINKS: A >< B Generated calls addcontext(a) addcontext(b) addexclusionrelation(a,b) Figure 2.17: ECDL file translation Subjective-C Files Parsing Another task of the Subjective-C Parser is to identify the declarations of context methods and translate these declarations into a call to the Subjective-C API for adding them. Subjective-C files contain precompiler symbols that are not recognized by a regular Objective-C compiler. These symbols, used by the parser to identify the context methods, are the following ones: #context, followed by context names related to the following context method

42 CHAPTER 2. BACKGROUND 32 #priority, followed by priority number of the context method that follows Figure 2.18 illustrates this parsing phase with two context methods. Each context method Subjective-C file #context A B #priority 10 - (void)meth {... #context C - (void)meth {... Generated calls addcontextmethod(meth,{a,b,10) addcontextmethod(meth,{c,0) Figure 2.18: Subjective-C file translation occurrence is translated into a call to the Subjective-C API for adding this context method with its related contexts and its priority. The Subjective-C Parser also has the responsibility to transform Subjective-C files into Objective- C files and collect context methods. Context method names are translated so that each method signature is unique. The context names related to a method are concatenated with the original method name and a prefix Context is added to the whole method name. For instance, a method move associated to contexts Up and Logging would be translated into Context Logging Up move. Note that if a method is defined for several contexts, then the different context names appearing in the context method declaration will be ordered alphanumerically Translation Phase These two sub-phases make what is called the translation phase. As shown in Figure 2.19, the Subjective-C compilation process begins with this translation phase when each Subjective-C file is given one by one to the Subjective-C File Parser. When all the files are translated into Objective-C files, the regular Objective-C compilation phase begins. Additionally to the parsing of Subjective-C files, the ECDL file is parsed in order to identify the contexts and the relations defined between these context. A special Objective-C file is generated from all the Subjective-C and ECDL files that have been parsed by the Subjective-C Parser during the translation phase. This generated file is made of context creations and calls to the Subjective-C APIs in view to add these contexts and the relations defined between them in the ECDL file (see Section and Section ) Limitations of Subjective-C 1.0 Even though Subjective-C 1.0 was a big step forward for dynamic programming in Objective- C, it lacks several features such as: User-friendly context state modification. Currently, the user must be aware of Context Manager features to perform basic operations such as an activation or deactivation. A user-friendly context state modification would only require the name of the context and the name of the action to perform.

43 CHAPTER 2. BACKGROUND 33 Subjective-C file Subjective-C file parser Objective-C file Subjective-C file Subjective-C file parser Objective-C file Subjective-C file Subjective-C file parser Objective-C file Objective-C compiler Subjective-C file Subjective-C file parser Objective-C file Generated file ECDL file ECDL file parser Figure 2.19: Subjective-C 1.0 compilation process Thread-local context possibilities. Currently, a context activation always has an impact on all threads in an application. A thread-local approach would allow to define a context that would have a state related to the current thread instead of to the whole program. Error-safe compilation process. Currently, if the compilation process crashes or is stopped while it is running, some files may be lost. Backup files are made before the translation phase to avoid a permanent loss. An Integrated Development Environment (IDE) integration. Using Subjective-C 1.0 in Xcode might become annoying because of files modifications during the translation phase and unrecognized preprocessor directives. A thread-safe library. The Subjective-C 1.0 s library cannot be safely used in a multithreaded application. Software reaction to context activation events. Currently, it is not possible to associate a reaction, such as a method callback, to a context activation event. Subjective-C 2.0, described in Part II, is an improvement to Subjective-C 1.0 by adding almost all of these features and making Subjective-C even easier to use. First and foremost, Subjective-C 2.0 implements a new kind of thread-local contexts. The implementation of this mechanism implies the implementation of a thread-safe library. One step in the achievement of the thread-safe objective is the redefinition of the supercontext mechanism with a new resend mechanism. Subjective-C 2.0 also goes one set further by defining a set of syntactic keywords for easing the use of the main mechanisms of this context-oriented language.

44 CHAPTER 2. BACKGROUND 34 Additionally to these new features, Subjective-C 2.0 adds the support of context activation and deactivation notifications. An IDE integration and an error-safe compilation process are not provided by Subjective- C 2.0.

45 Part II Subjective-C

46 Chapter 3 Overview Contents 3.1 Basic Syntax of Subjective-C Context Method Declaration Context Manager and Method Dispatcher Interaction with Contexts Local Context ECDL Extension Activating a Local Context Retrieving a Local Context Resend Mechanism Context Activation and Deactivation Callback Context Activation Event Notifications Registering for a Notification Context Activation Event Details Subjective-C Class Diagram Conclusion One of Subjective-C 2.0 s aims is to provide a homogeneous and simple COP language to use. In this perspective, Subjective-C 1.0 syntax has been modified and a few specific keywords have been introduced to make Subjective-C 2.0 programs more readable, but also (and perhaps more importantly) to hide Subjective-C s complexity to the final user. Most of the examples used in this chapter are the same as the ones used in Section 2.3, but translated to Subjective-C 2.0. This will make it clear how Subjective-C 2.0 is syntactically an improvement compared to Subjective-C 1.0. Keywords introduced in this chapter are pure syntactic sugar (i.e. it is possible to call Subjective-C 2.0 API to perform the same job). Section 3.1 presents the syntactic keywords introduced in Subjective-C 2.0. This new syntax is supposed to ease the development of programs written in Subjective-C. Another side effect is the improvement of the readability of these programs. Section 3.2 introduces the notion of local contexts that allows for a context to have one state per thread running in a contextoriented program. Section 3.3 shows how to use the resend mechanism that aims to replace the supercontext mechanism. This new mechanism provides thread-safety and allows inter context 36

47 CHAPTER 3. OVERVIEW 37 method calls. A new system of context activation event callbacks is introduced in Section 3.4. These callbacks allow to define a reaction to a context activation or deactivation. Section 3.5 explains the main steps of a context activation event. Finally, Section 3.6 shows the class diagram of Subjective-C Basic Syntax of Subjective-C 2.0 Subjective-C 2.0 introduces several keywords as shown in this section. These keywords allow to use Subjective-C s mechanisms in a simple and intuitive way. All of these keywords start with This syntax fits well in an Objective-C environment that is populated with keywords starting with this character Context Method Declaration Two keywords already introduced in Subjective-C 1.0 are #context and #priority. They are used for declaring a context method. These two keywords have been replaced so that they fit better in an Objective-C environment. The usage of these two keywords stays unchanged. Keyword Snippet 3.1 shows what the code introduced in Snippet 2.4 looks like in Subjective-C 2.0 by keyword. Snippet 3.1: Declaring a context method in Subjective-C ( void ) move { // Move triangle contexts Pause Logging - ( void ) move { NSLog (@" Game is paused "); // Do nothing Keyword Snippet 3.2 shows what the code introduced in Snippet 2.5 looks like in Subjective-C 2.0 by keyword Context Manager and Method Dispatcher In Subjective-C 1.0, the context manager is accessed through CONTEXT C macro. Given that this macro name is not clear enough and is more confusing than helping, it has been removed. The new way to access this module is through the call: [SCContextManager sharedcontextmanager]

48 CHAPTER 3. OVERVIEW 38 Snippet 3.2: Using method priority in Subjective-C ( void ) move { // Move contexts priority ( void ) move { // Log triangle s contexts priority ( void ) move { // Do nothing This syntax respects Objective-C conventions about naming of singleton access method 1 [App10a] and clearly shows to the user that only one instance of SCContextManager exists in a Subjective- C running program. Accessing the Method Dispatcher follows the same idea and the Subjective-C 1.0 s MANAGER C macro has been replaced with the call: [SCMethodDispatcher sharedmethoddispatcher] Again, it follows Objective-C s naming conventions and shows to the user that the method dispatcher is a singleton Interaction with Contexts Keywords As shown in Section , context activation and deactivation is simple but the syntax tends to be verbose because of the need to call the method dispatcher (i.e. retrieving the shared instance and then send it a message). Subjective-C 2.0 introduces two new keywords for activating (@activate) or deactivating (@deactivate) a context. These keywords are pure syntactic sugar. Snippet 3.3 shows what the code introduced in Snippet 2.2 looks like in Subjective-C 2.0 by keyword. The activation call using the new keyword is similar to the call: [[SCContextManager sharedcontextmanager] activatecontextwithname:@"pause"] 1 See CocoaFundamentals/CocoaObjects/CocoaObjects.html

49 CHAPTER 3. OVERVIEW 39 Snippet 3.3: Activating a context in Subjective-C ( IBAction ) pausetriangles :( id) sender ( Pause ); Snippet 3.4 shows what the code introduced in Snippet 2.3 looks like in Subjective-C 2.0 by keyword. The deactivation call using the new keyword similar to the call: [[SCContextManager sharedcontextmanager] deactivatecontextwithname:@"pause"] Snippet 3.4: Deactivating a context in Subjective-C contexts Pause - ( IBAction ) pausetriangles :( id) sender { // Unpause ( Pause Pause - ( IBAction ) pausetriangles :( id) sender { // Pause ( Pause ); It is even possible to activate or deactivate several contexts at once. In the following example, A, B, C and D are B, C, B, C, D); Using multiple activations or deactivations respects the order of the context list provided, that is, the first context of the list will be the first activated. Thread-local context activations or deactivations are possible by referencing a thread after a context name. In the following example, A, B, C and D are contexts and athread is a reference to a in athread, B, C, in athread, B, C, D); See Section 3.2 for further details about thread-local context activations. Controlling context states becomes much more straightforward with this new syntax. The user does not have to know how to activate or deactivate a context.

50 CHAPTER 3. OVERVIEW 40 Keyword One might want to manipulate a context as an Objective-C object. The usual way to retrieve a context is by calling SCContextManager class and specifying the name of the context. Because the user should not necessarily be aware of the context manager, Subjective-C 2.0 introduces a simple way to retrieve a context s reference. It is particularly helpful in the case of context activation event notifications (see Section 3.4). Snippet 3.5 shows a method that retrieve the context Up and print its activation state. Snippet 3.5: Retrieving a context in Subjective-C ( void ) printupcontextstate { SCContext * upcontext context ( Up); NSLog (@"Up context state : %d", [ upcontext isactive ]); 3.2 Local Context Subjective-C 2.0 introduces a way to keep the impact of context activations and deactivations at a thread level, instead of at the application level as with Subjective-C 1.0. Until now, no differentiation was made between each case. However, it is useful to make a clear distinction between these two types of context in this text. Consequently, a difference is made, in the following part of this dissertation, between a global context (i.e. at the application level) and a local context (i.e. at a thread level). When the exact context type is not relevant, this text simply uses the word context ECDL Extension Global contexts denote contexts as they have been defined in Subjective-C 1.0. Their activation state has an effect on all threads of the application. It is said they have an effect at the application level. Local contexts are a new kind of contexts that can be active within a defined set of threads in an application. It is then said that local contexts have an effect at a thread level. To allow the programmer to define local contexts, ECDL has been extended with local context declaration capabilities. The word (local) is directly appended to the context name to denote this context as local. Snippet 3.6 shows Triangles application s ECDL file with orientation contexts declared as local, because every triangle has its own thread and its own orientation. Note that logging context must be local too, because it is possible to log a single triangle at a time Activating a Local Context Activating or deactivating local contexts inside a thread is exactly the same as for global contexts (i.e. keywords). Nevertheless, a local context is said to be active for a thread if this thread has previously activated this context. In this case, a context is said to be locally active. As a side-effect, a context method defined for local contexts

51 CHAPTER 3. OVERVIEW 41 Snippet 3.6: Declaring a local context in an ECDL file Contexts : Orientation ( local ) Vertical ( local ) Horizontal ( local ) Up( local ) Down ( local ) Left ( local ) Right ( local ) Pause Dashed Logging ( local ) Links : Vertical =H=> Orientation Horizontal =H=> Orientation >< ( Vertical Horizontal ) Up =H=> Vertical Down =H=> Vertical >< ( Up Down ) Left =H=> Horizontal Right =H=> Horizontal >< ( Left Right ) END is said to be a candidate for a thread if its related local contexts as well as its related global contexts are active. However, it is possible to activate or deactivate a local context for a given thread from an external thread. The following expression is used for a thread-local activation from an external name> in <thread reference>) The following expression is used for a thread-local deactivation from an external name> in <thread reference>) For instance, the Triangle application s view controller is handling external events in an external thread. This controller needs to activate local contexts for some triangle threads depending on the events that occur. Snippet 3.7 shows how this controller activates or deactivates a specific orientation context for a specific triangle thread, depending on what button the user pressed Retrieving a Local Context A local context can be retrieved thanks like a regular context. Nevertheless, because this keyword returns a general context, the Context Manager includes an additional method localcontextwithname: that returns a local context object. Even though it is possible to retrieve a local context with the same method as for global contexts, this new additional method ensures that the context found is local. Snippet 3.8 shows an example of

52 CHAPTER 3. OVERVIEW 42 Snippet 3.7: Local context activation from an external thread # define UpSelected 0 # define DownSelected 1 # define LeftSelected 2 # define RightSelected 3 - ( IBAction ) updateorientation :( id) sender { if ( selectedtriangle ) { NSInteger selectedindex = [ orientationcontrol selectedsegmentindex ]; NSThread * movingthread = selectedtriangle. movingthread ; switch ( selectedindex ) { case UpSelected activate ( Up in movingthread ); break ; case DownSelected activate ( Down in movingthread ); break ; case LeftSelected activate ( Left in movingthread ); break ; case RightSelected activate ( Right in movingthread ); break ; Snippet 3.8: Retrieving a local context - ( void ) testingcontexts { SCLocalContext * upcontext = [[ SCContextManager sharedcontextmanager ] localcontextwithname :@"Up"]; // This assertion succeeds NSAssert ( is local "); SCContext * upcontext2 = [[ SCContextManager sharedcontextmanager ] contextwithname :@"Up"]; // This assertion succeeds NSAssert ( upcontext == Same context found "); SCContext * upcontext3 context ( Up); // This assertion succeeds NSAssert ( upcontext == Same context found "); SCContext * dashedcontext = [[ SCContextManager sharedcontextmanager ] localcontextwithname :@" Dashed "]; // This assertion fails NSAssert ( Dashed is not local "); this case applied to contexts declared in Snippet 3.6. The main difference between methods contextwithname: and localcontextwithname: is that the former returns any kind of

53 CHAPTER 3. OVERVIEW 43 context whereas the latter always returns a local context or a nil value if no local context exists for the name provided. 3.3 Resend Mechanism As said in Section , Subjective-C 1.0 introduced the supercontext mechanism. That is a simple way to call, from a context method, another context method with a lower precedence (i.e. the next context method). But the approach of Subjective-C 1.0 is not thread safe, because it changes the original method implementation, as shown in Figure 2.9. Problem 1 What would happen if a context activation 2 occurred during a supercontext call preparation? If the activated context is used for defining one variation of the concerned context method, then Method Dispatcher could 3 have to replace the original method implementation twice. Once for the supercontext call preparation and once for the context activation. Whatever comes first, the system would be in an inconsistent state because either the context method would not be prepared correctly for the supercontext call, or the method implementation would not correspond to the context activation. Problem 2 What would happen if a context activation 4 occurred during a supercontext call restoration 5? Again, if the activated context is used for defining one variation of the concerned context method, then Method Dispatcher could have to replace the original method implementation twice. Once for the supercontext call restoration and once for the context activation. Whatever comes first, the system would be in an inconsistent state because either the original method implementation would not be restored correctly after the supercontext call, or the method implementation would not correspond to the context activation. To resolve these two problems, Subjective-C 2.0 removes the supercontext mechanism and introduces a new resend mechanism taking advantage of Objective-C s dynamic method call possibilities instead of method implementation switching. The whole implementation is detailed in Chapter 6. Snippet 3.9 shows what the code introduced in Snippet 2.7 looks like in Subjective-C 2.0 by keyword. A resend call without parameters must be followed by empty parentheses. Like with supercontext mechanism, a resend call result can be stored in a variable. But unlike with supercontext mechanism, the storage syntax follows the standard Objective-C syntax. So the following statement is allowed in Subjective-C 2.0 for storing the result of a resend call: aboolean 2 The same question applies to a context deactivation. 3 This scenario only happens when a new context method becomes a candidate for the concerned original method. This context method must also take precedence over all other context methods defined for the same original method. 4 The same question applies to a context deactivation 5 A supercontext call restoration is the phase during which the Context Manager restores the old method implementation.

54 CHAPTER 3. OVERVIEW 44 Snippet 3.9: Resending a context method - ( void ) move { movepoint (&a, xoffset, yoffset ); movepoint (&b, xoffset, yoffset ); movepoint (&c, xoffset, yoffset ); movepoint (& center, xoffset, yoffset ); if ([ self isoutofbounds ]) { [ self reverse contexts priority ( void ) move { NSLog (@" Moving from %@", self (); Returning the result of a resend call also follows the standard Objective-C syntax: By looking like a standard function call, the resend mechanism is much more easier and natural at use than supercontext calls. It resolves the following problems encountered with supercontext mechanism: It is thread safe. The original method name does not have to be provided anymore. It can be used anywhere in the code, allowing to store its result in a variable, returning its result or even to use it as a method parameter in a standard Objective-C way. Note that the resend call in Snippet 3.9 could have been used with parameters param1, param2)) in another method. Subjective-C Parser automatically fills resend parameters with current method s parameters. Actually, it is possible to give any kind of parameters keyword, as long as their types respect the current context method s parameter types. Chapter 6 describes what API is used for making resend mechanism possible. 3.4 Context Activation and Deactivation Callback A limitation of Subjective-C 1.0 was about system reaction to context activation events. With Subjective-C 1.0, it is not possible for an object to be notified when a context is activated or deactivated. Subjective-C 2.0 adds another dynamic side to a Subjective-C program with context activation event callbacks.

55 CHAPTER 3. OVERVIEW Context Activation Event Notifications An object has the possibility to register for different context activation event notifications. There exist 8 kinds of notifications: 1. Context will activate, sent right before a context state changes from inactive to active. This notification is denoted with constant SCContextWillActivate. 2. Context did activate, sent right after a context state changed from inactive to active. This notification is denoted with constant SCContextDidActivate. 3. Context will deactivate, sent right before a context state changes from active to inactive. This notification is denoted with constant SCContextWillDeactivate. 4. Context did deactivate, sent right after a context state changed from active to inactive. This notification is denoted with constant SCContextDidDeactivate. 5. Four similar notifications are defined for local contexts with the following constants: SCLocalContextWillActivate SCLocalContextDidActivate SCLocalContextWillDeactivate SCLocalContextDidDeactivate Note that a local context always sends the corresponding general notification, in additional to the local notification. Thanks to this property, an object can simply register for any kind of context activation event instead of registering for global context and local context separately Registering for a Notification Subjective-C 2.0 uses the default notification center to send a notification to all the listeners for this kind of notification. The notification center synchronously sends a message with a NSNotification object to each registered listener for the corresponding kind of notification [BY09]. The message name (i.e. the method called) is defined by the listener beforehand. Figure 3.1 illustrates the context activation events notification system in Subjective-C 2.0. Snippet 3.10 shows how an object should register for SCLocalContextDidActivate notification for a specific context. When Up context becomes active, the listener will be sent the message orientationchangedtoup:. Snippet 3.11 shows how to register for the notification Snippet 3.10: Context activation event notification registration for a specific context - ( void ) orientationchangedtoup :( NSNotification *) notification { // Change triangle points coordinates - ( void ) registerfordebugactivation { [[ NSNotificationCenter defaultcenter ] addobserver : self selector selector ( orientationchangedtoup :) name : SCLocalContextDidActivate object (Up)]; SCContextDidActivate for all contexts. When any context becomes active, the listener will be sent the message contextdidactivate:.

56 CHAPTER 3. OVERVIEW 46 Context Context Context Notification Center Listener Listener Listener Listener Listener Legend: Activation event notification Method callback with notification Listener registration for a notification type Figure 3.1: Context activation events notification system Snippet 3.11: Context activation event notification registration for a specific context - ( void ) contextdidactivate :( NSNotification *) notification { SCContext * acontext = [ notification object ]; NSLog (@" Context did activate : %@", acontext. name ); - ( void ) registerfordebugactivation { [[ NSNotificationCenter defaultcenter ] addobserver : self selector selector ( contextdidactivate :) name : SCContextDidActivate object : nil ]; This way of achieving method callbacks on context activation events is the best one because it ensures no coupling between the contexts and the listeners. The contexts only care about sending a notification, not about how to deliver it and to what listeners. Note that context activation event notifications will never overlap (i.e. there will never occur two notifications at the same time) because of Context Manager synchronization. In other words, there is always at most one context activation 6 or deactivation 7 being processed by the Context Manager. 6 An context activation occurs when an object sends the message activate to a context. 7 An context deactivation occurs when an object sends the message deactivate to a context.

57 CHAPTER 3. OVERVIEW Context Activation Event Details A context activation event is made of several steps for modifying the state of the corresponding context, notifying the listeners,... Figure 3.2 illustrates what happens, step by step, when a context activation event occurs. Relations Context Context Source 1 activation propagation 2 Context 4 notification Notification Center 5 notification dispatching Listener 3 activation update Listener Context Method Finder Figure 3.2: Context activation event details 1. An activation event occurs (i.e. context activation or deactivation). 2. The target context propagates the activation event to the contexts it is in relation with. 3. The Context Method Finder is notified about the activation event so that it can update its internal data. 4. The target context sends a notification to the notification center. 5. The listeners registered for this kind of notification are notified. 3.6 Subjective-C Class Diagram Subjective-C 2.0 is mainly made of 6 different classes that allow to manage contexts, to update context methods,... Figure 3.2 illustrates the UML class diagram of Subjective-C 2.0. SCContext A context representation. SCLink A relation between two contexts. SCMethod An original method representation. SCContextMethod A context method representation. SCContextManager The context manager module. SCMethodDispatcher The method dispatcher module.

58 CHAPTER 3. OVERVIEW 48 SCMethodDispatcher original methods * SCMethod 1 dispatcher utiliy 1 original method SCContextMethod variations 1..* related contexts * SCLink * source target 1..* context methods relations SCContext 2 context utiliy * 1 contexts SCContextManager Figure 3.3: Subjective-C class diagram 3.7 Conclusion This chapter shows that Subjective-C 2.0 is a big step forward about simplifying the use of Subjective-C s concepts. Furthermore, several concepts such as local contexts or resend mechanism have been introduced to supplement Subjective-C 1.0 s capabilities. The following chapters explain in details all concepts used in Subjective-C 2.0.

59 Chapter 4 Local Dispatch Contents 4.1 Overview Limitations of Global Dispatch Characteristics of a Local Dispatch System Implementation Requirements General Architecture of the Local Dispatch System Local Dispatcher Algorithm Return Type Specific Dispatcher Motivation Definition of Local Dispatchers as C Functions Reference to a Local Dispatcher Method Argument Processors Motivation Definition of Argument Processors as C functions Reference to a List of Argument Processors Dynamic Method Invocation Method Signature Information Filling Method Arguments Definition of Dynamic Method Invocation Discussion Performance Local Dispatch at Compile Time Fault Tolerance Conclusion This chapter aims to give an explanation about a local dispatch system. Subjective-C uses such a system to allow contexts that are local to one particular thread of a running program, as explained in the next chapter. A few concepts must thus be explained to have a clear and complete idea about the local context implementation in Subjective-C. 49

60 CHAPTER 4. LOCAL DISPATCH 50 Section 4.1 gives an overview of such a system by explaining the unsuitability of global dispatch in some cases and what are the main characteristics of a local dispatch system. Section 4.2 explains the strategy adopted by Subjective-C for intercepting a method call. Section 4.3 gives a detailed explanation about the way method call argument values are retrieved in Subjective-C s local dispatching system. The concepts introduced in these two sections are used to create a dynamic invocation to a context method as explained in Section 4.4. Eventually, Section 4.5 discusses the local dispatching system performance and some implementation details. 4.1 Overview Limitations of Global Dispatch Context methods as presented in Chapter 2 work by directly replacing an original method s implementation with one of its related context methods. With this sytem, a context method is chosen among others thanks to its higher precedence. This kind of dispatch system is named global dispatch. Figure 4.1 illustrates how a behavioral variation (Variation 1 in this case) taking precedence over the other context methods has its implementation used as a replacement for its respective the original method. A dashed arrow represents a method implementation replacement. Typically, this method implementation replacement happens when a global con- Default Original Variation 1... Variation 2 Figure 4.1: Using a context method in global dispatch mode text activation event occurs, that is, when the previous inferred precedence between context methods might not correspond to the currently active contexts anymore. This kind of dispatch system works well in a single-threaded environment. Since replacing an original method implementation has global impact, it is not always usable in a multi-threaded environment. Furthermore, a global dispatch system assumes that a context activation event is sufficient for choosing a context method among others and thus that this method choice can be made at activation time. A more local system would allow to choose the best context method corresponding to a set of properties that are verified at method call time Characteristics of a Local Dispatch System The main difference between a global dispatch system and a local dispatch system is that the latter will find the best context method at method call time instead of context activation time. Local dispatch implies that the complexity of finding the best context method is located in the methods calls instead of the context activation events. But it provides a more dynamic way to find this context method as the local dispatcher can take advantage of current system state

61 CHAPTER 4. LOCAL DISPATCH 51 as well as properties related to the current thread at call time. It also brings opportunities for implementing thread-local contexts (see Chapter 5). The next section presents the requirements for implementing such a local dispatch system Implementation Requirements Implementing a local dispatch system requires several capabilities from the host language. These requirements may slightly differ in their concrete implementation from one language to another. But they must be present for implementing a generic local dispatch system. Intercepting a method call To be able to hide the use of a local dispatcher to the programmer, there must exist a way to intercept a call to the method that is locally dispatched. This might be achieved by using a proxy strategy [BY09, GHJV94] or by replacing the method implementation with a local dispatcher implementation. The second strategy has been chosen for local dispatching in Subjective-C 2.0. Retrieving the method signature Information about the method called must be retrieved for being able to find the best related context method. This concerns information about the method name, its arguments and its return value. In other words, the local dispatcher must be able to retrieve the signature of the method that is being called. Retrieving the argument values Because the method call is forwarded to a context method, the argument values from this call must be retrieved by the local dispatcher so that they can be forwarded to the context method. Creating a method invocation When the best context method is found and the method call arguments values are retrieved, the local dispatcher must be able to dynamically invoke the context method with all the information that has been gathered (i.e. the context method signature and argument values). Returning a value The value returned by the context method that was called must be returned transparently to the caller. The Objective-C language fulfills all these requirements thanks to its reflective capabilities and to some of the underlying C language properties General Architecture of the Local Dispatch System Figure 4.2 illustrates the general architecture used for locally dispatching a context method in Subjective-C. The original method implementation is replaced with the implementation of a local dispatcher. The local dispatcher delegates the task of finding the best context method to the Context Method Finder module. This module finds the best context method by choosing one context method definition among all the context methods defined for the original method. The next section presents the local dispatcher algorithm adopted by Subjective-C Local Dispatcher Algorithm Subjective-C s local dispatcher algorithm follows the four steps illustrated in Figure 4.3. The first step consists in finding the best context method. The time spent for this step does not depend on the local dispatcher implementation but rather on the Context Method Finder s algorithm for finding a method.

62 CHAPTER 4. LOCAL DISPATCH 52 Local dispatcher find best method Context Method Finder choose one of these Default Variation 1... Variation 2 Related context methods Figure 4.2: Local dispatch system 1: Find best context method 2: Create dynamic method invocation 3: Invoke method 4: Get return value Figure 4.3: Local dispatcher algorithm The second step is about collecting information about the method call and the best context method and create a dynamic invocation to this context method. Subjective-C takes advantage of the capabilities of NSMethodSignature and NSInvocation classes for creating a dynamic call. Section 4.4 gives further information about the creation of dynamic invocations. The third step obviously consists in invoking the context method. In Subjective-C, this is achieved through calling the invoke method of an instance of the NSInvocation class. Finally, the fourth step is about getting the return value. This step does only exist for methods actually returning a value. Again, in Subjective-C, this is achieved thanks to the NSInvocation class. The next sections describe in details the local dispatcher implementation in Subjective-C. 4.2 Return Type Specific Dispatcher The very first step for dispatching a method call is to be able to get complete descriptive information about the method that is called. This section explains how Subjective-C achieves this task by taking advantage of some characteristics of the C language.

63 CHAPTER 4. LOCAL DISPATCH Motivation As said in Section 1.3, one of the objectives of this thesis is to create a generic local dispatch system that can be used for every method. Nevertheless, method return types may differ from one method to another, which can complicate the task of implementing a unique dispatcher for typed languages such as Objective-C. Therefore, several local dispatchers have been created so that every return type can be handled. Because of its heritage from the C language, Objective-C types are made of primitives (e.g. int, double,... ), pointers (e.g. char *, id,... ) and composite types (structures, unions and arrays). As shown in Table 4.1, several primitive types are handled by the same dispatcher (corresponding to the type group column) thanks to the fact that all grouped types are handled equally when they have to be returned by a C function 1. Type group Types supported BOOL unsigned char signed char int unsigned short signed short unsigned int signed int long unsigned long signed long long long unsigned long long signed long long float float double double long double long double void void id id 1 Bytes 1 byte data structure 2 Bytes 2 bytes data structure Bytes 32 bytes data structure Table 4.1: Local dispatchers supported return types Additional dispatchers have been added for pointers and for composite types such as structures or unions. In this case, several dispatchers have been created, each one returning a certain amount of bytes (from 1 byte to 32 bytes 2 ), according to the size of the returned composite type. As a pointer size may differ depending on the architecture of the system on which the program is running, the size of a pointer return value is automatically adapted to the current architecture. 1 See Returning Result section of Mac OS X and ios ABI Function Call Guides 2 It is usually discouraged, for efficient issues, to return a large composite value given that the whole data must be copied to the caller of the function returning this composite value. Therefore, 32 bytes seems like a reasonable size limit for returning a composite type from a context method. For larger composite values, a pointer to the value must be returned. The same remark applies for composite function arguments.

64 CHAPTER 4. LOCAL DISPATCH 54 Even though everything works well on Mac OS X, locally dispatched context methods returning composite types produce undesired crashes on ios. This is due to a different handling of method parameters and return values 3 from one platform to another because of a different processor architecture (x86 64 for Mac OS X and ARM for ios). This problem implies that a Subjective-C program running under ios cannot use locally dispatched methods returning a composite type. This limitation can be overcome by using pointers to the composite values instead of passing the whole value Definition of Local Dispatchers as C Functions Thanks to the properties presented in the previous section, a bounded number of local dispatchers can be defined for handling all possible Objective-C types. The local dispatch system of Subjective-C takes advantage of Objective-C s compiling system. At compile time, an Objective-C method is translated into a C variadic function taking 3 arguments: a reference to the method receiver, the selector of the method and a variadic list of arguments. For instance, a method signature like the one shown in Snippet 4.1 would be translated to a function that would look like the one shown in Snippet 4.2. In Snippet 4.2, self is a reference to the re- Snippet 4.1: Objective-C method + ( Triangle *) createtrianglewithcoordinates :( CGPoint ) center { //... Snippet 4.2: Objective-C method translated in plain C Triangle * _ createtrianglewithcoordinates ( id self, SEL _cmd,...) { //... ceiver of the message and cmd is the selector of the method. Subjective-C s local dispatchers take advantage of this property by using a translated Objective-C method signature form. Even if there are several dispatchers (one per return type group), the implementation only differs in the declaration of the return value. As shown in Snippet 4.3, the code has been factorized in a macro LOCAL DISPATCHER DEF that takes a type and a function name suffix as parameters. This macro is then used for each return type group defined in Table 4.1. Snippet 4.3 shows the definition of the local dispatchers for int and long long types. Snippet 4.4 shows the resulting macro expansion for the long long local dispatcher case. A local dispatcher implementation consists in retrieving the variadic method arguments list, creating the return value variable and then dispatching the method. Again, no return value is created for a method that does not return anything (i.e. void return type). Finding the best context method and creating the dynamic context method invocation are handled in the dispatchmethod function. Note that receiver and methodselector arguments corresponds to self and cmd arguments introduced in Snippet See also Procedure Call Standard for the ARM Architecture document

65 CHAPTER 4. LOCAL DISPATCH 55 Snippet 4.3: Local dispatcher macro definition # define LOCAL_ DISPATCHER_ DEF ( _type_, _ type_ name_ ) \ _type_ SCLocalDispatcher_ ## _ type_ name_ ( id receiver, \ SEL methodselector, \...) { \ va_list arguments ; \ va_ start ( arguments, methodselector ); \ _type_ returnvalue ; \ dispatchmethod ( receiver, methodselector, arguments, & returnvalue ); \ return returnvalue ; \ LOCAL_DISPATCHER_DEF (int, int ); LOCAL_ DISPATCHER_ DEF ( long long, long_ long ); //... Snippet 4.4: Local dispatcher macro translation for long long type long long SCLocalDispatcher_ long_ long ( id receiver, SEL methodselector,...) { va_list arguments ; va_ start ( arguments, methodselector ); long long returnvalue ; dispatchmethod ( receiver, methodselector, arguments, & returnvalue ); return returnvalue ; Reference to a Local Dispatcher Because the return type is the same for all the context methods related to the same original method, their specific dispatcher can be statically assigned to their original method when the Subjective-C representation of this latter is created in the system. An original method is represented by an instance of SCMethod class. Snippet 4.5 shows the instance variables of this class. Only the dispatchmode and dynamicdispatcher variables are interesting here. The dispatchmode variable denotes in what dispatch mode the original method is currently. Its value can either be global or local, the former representing global dispatch and the latter representing local dispatch. The localdispatcher variable is a direct reference to the local dispatcher assigned to the original method at its creation. This variable is needed for fast method implementation switching. 4.3 Method Argument Processors One step for redirecting a method call towards another method is to retrieve the value of the arguments given by the caller and give them to the method to which the call is redirected. This section presents the strategy adopted by Subjective-C for retrieving the value of these arguments.

66 CHAPTER 4. LOCAL DISPATCH 56 Snippet 4.5: SCMethod class instance interface SCMethod : NSObject Method method ; SEL selector ; Class relatedclass ; BOOL instancemethod ; NSMutableArray * contextmethods ; SCDispatchMode dispatchmode ; IMP localdispatcher ; SCArgProcessor * argsprocessors ; NSUInteger numberofarguments ; NSMethodSignature * methodsignature ; Motivation In the same logic as for return types, an Objective-C method can take arguments with different types. As shown in Snippet 4.3, a local dispatcher uses a variadic list (i.e. va list type) for retrieving method argument values. Retrieving a variadic argument requires to provide the type of the argument. All the information needed about arguments is provided by the instance of the NSMethodSignature class created for this method (see Section 4.4 for further details). A naive implementation would be made of several conditional statements for adding the argument value to the dynamic invocation in a correct way, as shown in Snippet 4.6. As it is inefficient to Snippet 4.6: Naïve implementation for retrieving method arguments const char * argtype = [ methodsignature getargumenttypeatindex : argindex ]; if ( strcmp ( ( int )) == 0) { int arg = va_arg ( methodarguments, int ); [ invocation setargument :& arg atindex : argindex ]; else if (...) {... else if ( strcmp ( (id)) == 0) { id arg = va_arg ( methodarguments, id); [ invocation setargument :& arg atindex : argindex ]; do it at call time, all this work can be done when the original method representation is created in the system (i.e. when an instance of the SCMethod class is created for this original method). Indeed, because the argument types are the same for all the context methods extending a same original method, there is a possibility to define, once for all, what types of argument should be processed and in what order. The following sections show a more efficient implementation. Furthermore, as explained for return type groups in Section 4.2, all possible method argument types can be regrouped as illustrated in Table 4.2. A group of types here means the same as in Section 4.2 with method return type groups defined in Table 4.1.

67 CHAPTER 4. LOCAL DISPATCH 57 Type group Types supported BOOL unsigned char signed char int unsigned short signed short unsigned int signed int unsigned long long signed long unsigned long long long long signed long long float double double long double long double id id void * void * Table 4.2: Local dispatchers supported argument types Definition of Argument Processors as C functions As with different local dispatchers, here the implementation between each argument processor only differs in the argument value declaration. As shown in Snippet 4.7, the code has been factorized in a macro ARG PROCESSOR DEF that takes a type as a parameter. This macro is then used for each return type group defined in Table 4.2 to create one argument processor function for each possible type group. Snippet 4.7 shows the definition of the argument processors for int and long long types. Snippet 4.8 shows the resulting macro expansion for Snippet 4.7: Method argument processor macro definition # define ARG_PROCESSOR_DEF ( _type_, _postfix_ )\ void SCArgProcessor_ ## _ postfix_ ( va_list methodarguments,\ NSInvocation * invocation,\ NSUInteger index )\ {\ _type_ arg = va_arg ( methodarguments, _type_ );\ [ invocation setargument :& arg atindex : index ];\ ARG_PROCESSOR_DEF (int, int ); ARG_PROCESSOR_DEF ( long long, long_long ); the long long argument processor case. The methodarguments argument is the variadic list of arguments for the currently dispatched method. The invocation argument is the invocation object that will be used to forward the method call (see Section 4.4 for further details). Finally, the index argument is the position of the argument in the method arguments list. An argument processor implementation consists in retrieving the argument value in the variadic list (i.e. using va arg macro) and then fulfilling the NSInvocation instance with this value.

68 CHAPTER 4. LOCAL DISPATCH 58 Snippet 4.8: Method argument processor macro translation for long long type void SCArgProcessor_ long_ long ( va_list methodarguments, NSInvocation * invocation, NSUInteger index ) { long long arg = va_arg ( methodarguments, long long ); [ invocation setargument :& arg atindex : index ]; Reference to a List of Argument Processors Two additional instance variables of the SCMethod class are interesting here: argsprocessors and numberofarguments. The argsprocessors variable is a C array of SCArgProcessor function pointers. Each argument processor in this array will process one of the method arguments. The numberofarguments variable is the size of this array (i.e. the number of arguments of the method). Note that composite types such as structures or unions cannot be used as context method parameters. This comes from the fact that a method argument cannot be simply retrieved byte per byte because it produces undesired values with types like double and float. This limitation can be overcome by using pointers to the composite value instead of passing the whole value. Figure 4.4 shows an example of an argsprocessors variable for a method taking 4 arguments in the following order: an int, a double, a short and an id. The argument types are the types int processor double processor... id processor void * processor 4 arguments of their respective group. Figure 4.4: References to method argument processors This concludes the explanation of information gathering for the creation of a dynamic method invocation. 4.4 Dynamic Method Invocation Section 4.2 explains how the information about a method such as its return type or its argument list can be retrieved. Section 4.3 shows a way to retrieve the argument values of a method call. This section explains how a dynamic method invocation is created by using these two approaches.

69 CHAPTER 4. LOCAL DISPATCH Method Signature Information Every object representing an original method in Subjective-C stores a variable methodsignature. This variable is an instance of NSMethodSignature and holds information about the signature of the original method represented by the object storing this variable. This instance variable is used to create an instance of the NSInvocation class which represents a dynamic method invocation. Snippet 4.9 shows how the dynamic invocation is created in Subjective-C. The Snippet 4.9: Creating an empty dynamic invocation NSInvocation * getmethodinvocation ( id receiver, SCContextMethod * contextmethod, va_list methodarguments ) { // Create method invocation SCMethod * originalmethod = contextmethod - > originalmethod ; NSMethodSignature * signature = originalmethod - > methodsignature ; NSInvocation * invocation = [ NSInvocation invocationwithmethodsignature : signature ]; [ invocation settarget : receiver ]; [ invocation setselector : contextmethod - > selector ]; // Fill with arguments... return invocation ; three first statements are about the creation of the NSInvocation instance. The next statement sets the receiver of the invocation, that is, the instance on which the initial method call has been sent. Finally, the remaining statement sets the selector of the context method to which the method call is forwarded Filling Method Arguments When the dynamic method invocation is created, it needs to be filled with argument values provided by the method call. The argument values located in the variadic list are processed by the argument processors introduced in Section 4.3. Snippet 4.10 shows how the dynamic invocation is filled with argument values in Subjective-C. It simply consists in executing all Snippet 4.10: Filling dynamic invocation arguments NSInvocation * getmethodinvocation ( id receiver, SCContextMethod * contextmethod, va_list methodarguments ) { // Create method invocation... // Fill with arguments SCArgProcessor * argsprocessors = originalmethod - > argsprocessors ; NSUInteger numberofarguments = originalmethod - > numberofarguments ; for ( NSUInteger index = 0; index < numberofarguments ; index ++) { argsprocessors [ index ]( methodarguments, invocation, index + 2); return invocation ;

70 CHAPTER 4. LOCAL DISPATCH 60 the argument processors associated to the method. These argument processors fill the dynamic invocation by getting the right type of value from the provided variadic list (see Section 4.3) Definition of Dynamic Method Invocation Now that all the most important pieces of local dispatch in Subjective-C have been presented, the dispatchmethod function can be explained. It is a simple application of the algorithm shown in Figure 4.3. Snippet 4.11: Local dispatcher method forwarding implementation void dispatchmethod ( id receiver, SEL methodselector, va_list methodarguments, void * returnvalue ) { // Find best method for current contexts SCContextMethod * contextmethod = [[ SCMethodDispatcher sharedmethoddispatcher ] findcontextmethodfromoriginalselector : methodselector relatedclass : SCClassOf ( receiver ) isinstancemethod : SCIsInstance ( receiver )]; // Create the dynamic invocation NSInvocation * invocation = getmethodinvocation ( receiver, contextmethod, methodarguments ); // Invoke the method [ invocation invoke ]; // Get the return value if ( returnvalue ) { [ invocation getreturnvalue : returnvalue ]; 4.5 Discussion The previous sections explain the internals of Subjective-C s local dispatch system. It is, however, interesting to have a look at the impact of such a system to the general performance of a program written in Subjective-C 2.0. To this end, Section provides a good overview of Subjective-C local dispatch performance by making a comparison with methods that are not locally dispatched. Additionally to these benchmarks, Section explains why a local dispatch system should be working at runtime instead of defining it at compile time. Finally, Section discusses the fault tolerance of the dynamic dispatch system implemented in Subjective-C Performance Several benchmarks have been performed to first compare a regular method call with a locally dispatched call, and then to see what is the impact of varying the number of related contexts

71 CHAPTER 4. LOCAL DISPATCH 61 or the number of arguments of a method call. These benchmarks have been performed with Xcode Instruments Regular Method Call vs Locally Dispatched Call This first benchmark compares the time spent for making a regular method call, compared to the time spent for making a locally dispatched method call. This test has been performed by calling an empty context method with one related local context. No parameter was passed to the method. The method returns atask NSUInteger value. Time (ms) Time (%) Time with regular method 0, ,8 The results of this testtime are with shown local on dispatcher Figure 4.5. This 0,00637 graph shows100 that calling a locally dis- Normal vs dispatcher Time (ms) 0,007 0,006 0,006 0,005 0,004 0,004 0,003 0,002 0,001 0, , ,00005 Regular method Local dispatcher Task Time (ms) Time (%) Figure 4.5: Regular method call vs locally dispatched call time Find best context method 54, ,8 Create invocation 6, ,9 Dispatcher call 0,8281 1,3 Check pending activations 0,3185 0,5 Invoke method 0,5096 0,8 Get return value 1,0829 1,7 Other 2,7391 4,3 TOTAL 63, ,7 YES patched method takes about 127 times more time than calling a regular method. This observation can be justified because of the need to: Find the best context method. Create a dynamic invocation. Get the return value. Time spent in local dispatcher It is important to keep in mind that several steps needed for local dispatch are performed at a high level by means of Objective-C objects and methods. Objective-C s message dispatching 4,3% system is a bottleneck because of its dynamic nature. Performance could be much better if all 10,9% these operations where performed at a lower level (e.g. in Assembly or in plain C). Find best co Create invoc Dispatcher c Check pendi Invoke meth Get return va Other TOTAL What is interesting to discover is the time spent for each of these subtask. This is what the next benchmark aims to show Local Dispatch Time Repartition (1 Context Method with 1 Context) The results from this benchmark comes from the same experience made in the previous benchmark. These results are illustrated in Figure 4.6. This84,8% pie chart shows that 84,8% of the time for locally dispatching this method is spent for finding the best context method. In other words, Find best context method Create invocation Other Fin Cr Ot

72 Create invocation Dispatcher call Check pending activations Invoke method Get return value Other 6, ,9 0,8281 1,3 0,3185 0,5 0,5096 0,8 1,0829 1,7 2,7391 4,3 TOTAL 63,7 100 CHAPTER 4. LOCAL DISPATCH 62 63,7 YES Time spent in dynamic dispatcher Dispatcher call Check pending activat Invoke method Get return value Other TOTAL Time spe 4,3% 10,9% (ms) Time (%) ,8, tcher, ,8% Find best context method Create invocation Other Find best c Create invo Other Figure 4.6: Local dispatch time repartition (1 context method with 1 context) Dynamic dispatcher (ms) Time (%) 4, ,8 6, ,9 0,8281 1,3 0,3185 0,5 0,5096 0,8 1,0829 1,7 2,7391 4,3 63, ,7 YES ic dispatcher 84,8% is spent in the Context Method Finder. Chapter 7 gives further details about the Context Method Finder and its performance. The chart also shows that 10,9% of the time is spent for creating a dynamic invocation. Eventually, a section Other takes 4, 3% of the time. This section is made of steps like calling the dynamic dispatcher and making the invocation. The two next benchmarks show how Taskcan these values Time (ms) be influenced Time (%) by varying the number of related contexts or the number Find best ofcontext arguments method given to253,4522 the method. 91,4 Create invocation Dispatcher call Local DispatchCheck Time pending Repartition activations (1 Context 0,2773 Method with 0,1 5 Contexts) Invoke method 17,7472 6,4 2,2184 0,8 1,3865 0,5 Get return value 2,2184 0,8 For this benchmark, the context method has 5 related local contexts. The aim of this test is to Other 6,1006 2,2 Other analyze the impact of thetotal Context Method Finder task 277,3 by varying the 100 number of contexts of a 277,3 YES context method. Figure 4.7 illustrates the results. The Context Method Finder task for finding Time spent in dynamic dispatcher Task Find best context method Check pending activations Create invocation Dispatcher call Invoke method Get return value TOTAL Time spent in dy 2,2% 6,4% 5,3% 84,8% 91,4% 70,2% thod Find best context method Create invocation Other Figure 4.7: Local dispatch time repartition (1 context method with 5 context) Find best context m Check pending acti Other

73 CHAPTER 4. LOCAL DISPATCH 63 thod ations Time (ms) Time (%) 134, ,5 385, ,3 21,3837 3,9 2,1932 0,4 3,2898 0,6 2,1932 0,4 7,6762 5,3 548,3 100,1 548,8483 NO pent in dynamic dispatcher the best context method takes now 91,4% of the time of the call. This represents an increase of 6,6% compared to the previous benchmark. This benchmark shows that most of the time is spent inside the Context Method Finder. This time can easily grow by varying some parameters such as the number of contexts for which a Task Time (ms) Time (%) context method is defined. Find best context method Create invocation Dispatcher call Local DispatchCheck Time pending Repartition activations (1 Context 0,1626Method 0,2 with 4 parameters) Invoke method 65, ,1 12, ,8 1,3821 1,7 1,2195 1,5 The last benchmark usesget a return context valuemethod with 1 related 1,3008 context 1,6 but 4 parameters 4. Each parameter is an NSUInteger Other 4,065 5 TOTAL value. The results of this 81,3 experience99,9 are illustrated in Figure 4.8. This chart shows that the time spent for creating the 81,2187 dynamic invocation NO has increased com- Time spent in dynamic dispatcher 5,3% 24,5% 14,8% 5,0% 0,2% 80,2% context method nding activations Find best context method Create invocation Other Figure 4.8: Local dispatch time repartition (1 context method with 4 parameters) pared to the first benchmark (+3,9%). The reason is that the dynamic dispatcher must process each parameter by using several argument processors (4 in this case). All these benchmarks tend to show that finding the best context method is the task that usually takes most of the time. Chapter 7 gives an explanation to this observation Local Dispatch at Compile Time Dealing with local dispatch at runtime brings a performance overhead because of the time spent in the local dispatchers. How is that better than a compile-time solution anyway? What are the limitations of doing everything at compile time? Should local dispatch always be used? Yes, always The benchmarks presented in the previous section tend to discourage a massive use of local dispatch because of its negative impact on global performance. 4 It is not usual to see methods with more than 4 parameters.

74 CHAPTER 4. LOCAL DISPATCH 64 No, only after a preprocessor directive 5 Even though this solution seems more reasonable, it does not allow to switch to local dispatch for a specific method from an external thread Two-pass Compilation Process One compilation solution would be to transform every context method call like: id result = [self contextmethod:(id)aparameter]; into a call to the best context method like: SEL contextselector = findbestcontextmethod(...); id result = objc_msgsend(self, contextselector, aparameter); This kind of code transformation requires a two-pass compilation process: A first one for collecting all original method names. A second one for translating every occurrence of a call to one of these original methods into a call to the best context method. The problem with this approach using the compiler to translate calls to dynamically dispatched methods is that it requires access to the source code making these calls. It is not always guaranteed that a program making a call to a dynamic dispatched method will be compiled by Subjective-C. For instance, it is possible to have a library x that is implemented with dynamically dispatched methods. This library would be compiled by the Subjective-C Parser. A program y might use this library for various purposes without knowing it is a library implemented with Subjective-C features. This program would be compiled with a regular compiler such as gcc or llvm. Therefore, calls to locally dispatched methods from the library x would not be translated because the program y would not be compiled with Subjective-C Fault Tolerance An important point about a subsystem being used by other systems is that this subsystem must be fault tolerant. It means that an error occuring in a component involved in this subsystem should not have an impact on other components. The subsystem should therefore continue to provide a reliable service to these other components. In this section, it is assumed that the Objective-C and Subjective-C runtime systems do not randomly crash because of their implementation. In other words, it is assumed that their main mechanisms are correct and never produce an error when they are used as they have been designed for. In Subjective-C, a component might be a thread calling locally dispatched methods. It is always ensured that an unsuspected stop of this thread does not have an impact on the other threads and keeps Subjective-C in a consistent state. This is due to several facts. First, Subjective-C 2.0 s runtime system is not living in its own thread. Subjective-C s operations are performed inside the threads making calls to the Subjective-C API. In Objective-C, 5 For instance, a preprocessor directive #local could specify that the methods should be locally dispatched between this directive and another directive #end.

75 CHAPTER 4. LOCAL DISPATCH 65 when a thread crashes, the whole program in which this thread is running crashes. Therefore if a thread crashes inside a locally dispatched method call, Subjective-C stops working with the program. Second, in Objective-C, a thread cannot be paused or stopped from an external thread. At most, it can be be sent the message cancel which has no direct effect except that it makes the method iscancelled return YES. Therefore, the next time this thread eventually checks the return value of the method iscancelled, it might decide to stop its execution. This verification can only be made inside a regular method body and therefore not while Subjective-C is modifying internal data for this thread. Third, it is assumed that Subjective-C runtime implementation is correct and error-safe. Therefore, a thread will never stop working while Subjective-C is modifying internal data for this thread. Finally, it is assumed that an Objective-C thread never stops running unsuspectedly. A thread s crash is always related to a user defined event. For all these reasons, it is assumed that the local dispatch system in Subjective-C 2.0 is fault tolerant. 4.6 Conclusion The local dispatch system allows to intercept a method call and redirect it to the correct method. It comes with a certain overhead because it needs to retrieve the information about the method call and create a dynamic invocation to the correct method. Nevertheless, as explained in the next chapter, it is a needed step to enable local contexts, as this concept requires to determine what context method should be called at call time.

76 Chapter 5 Local Contexts Contents 5.1 Overview Limitations of Global Contexts Characteristics of a Local Context Implementation Requirements Local Context Representation Local Context Data Structure Thread-Local Information Cleaning Process of Thread-Local Information Thread-Local Context State Activation Events Modifying Context State External Activation Events Activation Event Effect Discussion Performance Pending activation queue Using the Thread Dictionary Conclusion Chapter 4 presents local dispatch system as a way to dynamically forward a method call to a specific method definition. This local dispatch system is a needed step to enable local contexts, as this mechanism requires to determine what context method should be called at call time. This chapter defines local contexts on the one hand, and presents the implementation of such a mechanism in Subjective-C 2.0 on the other hand. Section 5.1 gives an overview of such a system by explaining the unsuitability of a global contexts in some cases and what are the main characteristics of local contexts. Section 5.2 shows how local contexts are represented in Subjective-C 2.0. Section 5.3 explains the strategy adopted by Subjective-C 2.0 for storing thread-local information. Section 5.4 presents how Subjective-C 2.0 handle a thread-local context activation event. Finally, Section 5.5 discusses the global performance of local contexts and several other aspects related to their implementation in Subjective-C

77 CHAPTER 5. LOCAL CONTEXTS Overview Limitations of Global Contexts In Subjective-C 1.0, a context always affects all threads running in a program. These contexts have a global impact on a running application and are therefore called global contexts. Global contexts suit well when they represent external factors concerning the whole device such as the weather, availability of a network connection or the current geographical location. Nevertheless, sometimes contexts might concern only parts of a running program. For instance, in the Triangles applications, the context Logging only concerns the selected triangle. Therefore, at most one triangle s moves can be logged when the logging mode is engaged. This kind of contexts becomes local to specific threads. This is made possible thanks to local contexts introduced in Subjective-C Characteristics of a Local Context Global contexts, as introduced in Subjective-C 1.0, have a state that is global to the whole application. In other words, every thread shares the same state for a same global context. Therefore, behavioral variations defined for global contexts concern every threads at the same time. On the contrary, local contexts have a state that is local to each thread. This means that a local context can be active for a thread t 1 while it is inactive for a thread t 2. Actually, this characteristic applies to every context s property that should be local to a thread. For instance, the activation age of a local context is not shared between threads and is therefore local. Local contexts can be seen as multiple-sided dice 1 where each side corresponds to a thread-local representation. Nevertheless, local contexts may share information between every thread, such as their name. Figure 5.1 shows a local context that has three different representations, depending on what thread is currently running. This local context is active with an activation age of 10 Thread 3 inactive age = NA Thread 1 active age = 10 Local Context active age = 5 Thread 2 Figure 5.1: A local context with a variable representation depending on the thread for Thread 1, it is also active but with an activation age of 5 for Thread 2 and it is inactive for Thread 3. The next section presents the requirements for implementing such a local context mechanism Implementation Requirements Implementing local contexts requires several capabilities from the host language. 1 Multiple-sided dice are very much used in role playing games.

78 CHAPTER 5. LOCAL CONTEXTS 68 Multithreading support Because local contexts are represented differently depending on each thread, the host language must support multithreading. This is the most obvious and most necessary requirement. Thread differentiation Information related to a thread must be differentiable from information related to another thread. There must exist a way to retrieve and modify information concerning a specific thread. This specific thread can either be the current thread or a thread provided by an external module. Thread-independence Operations related to a specific thread must not have any sort of impact on information related to another thread. This can be seen as a sort of thread-safety property. The Objective-C language fulfills all these requirements thanks to its multithreading and thread synchronization capabilities. 5.2 Local Context Representation Local Context Data Structure Local contexts define an activation scope that is similar to layers used in languages like ContextL [CH05] and other similar context-oriented extensions 2. Ideally, local contexts should share several underlying mechanisms with global contexts. Base mechanisms of local contexts are semantically the same but they are extended to define them by using thread-local information. For instance, local context activation means the same as for global contexts, that is, adapting the behavior of a software to the activated context. The difference is that a local context activation only adapts the software behavior within a given thread. In Subjective-C 2.0, local contexts are represented by an instance of the SCLocalContext class. As illustrated in Figure 5.2, the SCContext class has been subclassed to create the SCLocalContext class used for representation of local contexts and the SCGlobalContext class used for global contexts representation. The SCLocalContext class redefines necessary SCContext SCLocalContext SCGlobalContext Figure 5.2: SCContext class subclassing methods for modifying and accessing local context state. A local context keeps information about each thread for which it has been activated in the past. Subclassing the SCContext class allows to define all context mechanisms in this class and specialize only what is needed in the subclasses. 2 ContextS [HCH07] and ContextJ [AHHM09] are inspired from ContextL

79 CHAPTER 5. LOCAL CONTEXTS Thread-Local Information In order to adapt the behavior of a software within given threads only, information about those threads must be stored separately. Context information related to a specific thread must be retrievable based on meta-information about this thread. Subjective-C 2.0 s strategy is to create dictionaries in each local context for storing information related to threads within which the concerned local context has been activated in the past. Figure 5.3 illustrates two dictionaries maintained by a local context when an activation event occurs. A first dictionary that keeps one distinct activation count per thread withing which the local context has been activated. Further information about access and modification of this dictionary is given in Section 5.3 and Section 5.4. A second dictionary keeps information about the last time the local context was activated within a given thread. This dictionary has a purpose of helping the Context Method Finder for context method precedence ordering and is thus not explained in this chapter but rather in Chapter 7. Thread 1 Activation count Thread Number Thread 2 Last activation Thread Number Figure 5.3: Local context threads information In a sense, the strategy adopted by Subjective-C 2.0 is simulating different context instances, one per thread, by means of dictionaries. One might think about an alternate strategy where there exists one instance of the SCLocalContext class per thread for each local context. This alternate strategy is valid because it is more natural to define context s properties in terms of instance variables rather than by means of dictionaries. Nevertheless, this strategy must be defined in a special way because of context relations. In Subjective-C 2.0, relations assume that the source and the target contexts are instances that are shared within the whole application. An alternate implementation could therefore define instances of SCLocalContext as proxies that forward operations to appropriate instances of SCContext. Each proxy would be seen as a regular local context within relations or from the point of view of external modules. This alternate implementation would therefore get rid of dictionaries storing thread-local information. Figure 5.4 illustrates this alternate strategy with two local contexts and with a relation defined between these two contexts. Next sections explain how the state of a local context is accessed and modified for a given thread in Subjective-C Cleaning Process of Thread-Local Information Every instance of SCLocalContext stores various information about threads within which the local context represented by this instance has been activated. When a thread ends and is

80 CHAPTER 5. LOCAL CONTEXTS 70 Local Context 1 thread 1 Local Context 2 thread 1 Local Context 1 thread 2... Local Context 1 thread n relation Proxy 1 Proxy 2 Local Context 2 thread 2... Local Context 2 thread n Figure 5.4: Local contexts defined with a proxy deallocated, the information related to this thread is not automatically deleted by the Objective- C s runtime system. Therefore, Subjective-C must engage a cleaning process when a thread ends. In Objective-C, a thread posts a notification NSThreadWillExitNotification when its lifetime has ended and it is about to be deallocated. Thanks to this property, the Subjective-C s runtime system can subscribe for this kind of notification coming from any thread. When this runtime system receives such a notification, the cleaning process is engaged for the ending thread corresponding to the received notification. This cleaning process is in charge of removing all remaining information about this thread. This mechanism provides an automatic and transparent way to clean information about threads that have ended. This ensures that the thread-related data kept in memory are always related to threads that are still running. 5.3 Thread-Local Context State As explained in Section 5.2, a local context keeps an activation counter for each thread within which it has been activated. Figure 5.5 illustrates how a local context retrieves the activation counter for the current thread (Thread 2 in this case). When a local context activation count activationcount return 2 objectforkey:currentthread Activation count SCLocalContext Thread Number Thread Thread Figure 5.5: Retrieving the activation count of a local context is accessed, it is always the count related to the current thread that is retrieved. The reason is that it minimizes the differences of implementation between a global context and a local context implementation. Indeed, only the activation counter accessors must be redefined for determining the activation state of a local context. Snippet 5.1 shows how the activation counter of a local context is programmatically retrieved. As it might be interesting to verify whether a local context is active for a given thread, an additional method isactiveforthread: has been added to the SCLocalContext class as shown in Snippet 5.2.

81 CHAPTER 5. LOCAL CONTEXTS 71 Snippet 5.1: Retrieving the activation count of a local context - ( NSUInteger ) activationcount { NSValue * threadpointer = [ NSValue valuewithpointer :[ NSThread currentthread ]]; return [[ activationcountforthread objectforkey : threadpointer ] unsignedintegervalue ]; Snippet 5.2: Verifying a local context state for a given thread - ( BOOL ) isactiveforthread :( NSThread *) athread { NSValue * thread = [ NSValue valuewithpointer : athread ]; return [[ threadsactivationcounts objectforkey : thread ] integervalue ]; 5.4 Activation Events Modifying Context State As for accessing a local context s state, modifying it also has an impact at a thread level. Figure 5.6 illustrates how a local context changes the activation count for the current thread (Thread 2 in this case). With the same logic as for accessing the activation counter of a local setactivationcount:3 setobject:3 Activation count forkey:currentthread SCLocalContext Thread Number Thread Thread Figure 5.6: Modifying the activation count of a local context context (see Section 5.3), modifying it always modifies the activation counter relative to the current thread. Snippet 5.3 shows how the activation counter of a local context is programmatically modified in Subjective-C 2.0. Because a context activation counter is always accessed Snippet 5.3: Modifying the activation count of a local context - ( void ) setactivationcount :( NSUInteger ) newactivationcount { [ threadsactivationcounts setobject : [ NSNumber numberwithunsignedinteger : newactivationcount ] forkey : [ NSValue valuewithpointer :[ NSThread currentthread ]]]; through the accessors defined in the SCContext class, overriding them allows to return or modify the activation counter related to a specific thread (in this case, the current thread). Working

82 CHAPTER 5. LOCAL CONTEXTS 72 this way allows to only override the state variable s accessors to provide a context that is local to each thread. One might wonder how a local context activation coming from an external thread is possible if the activation counter modifications only have an impact on the current thread s value. Next section answers this question and introduces the notion of pending activation queue External Activation Events Local context activations as presented so far always concern the thread within which they occur. Section 5.3 and Section have shown that using the activation state variable accessors of local contexts is always related to the current thread. This choice is motivated because it requires minimal changes to the general architecture and implementation of Subjective-C. Nevertheless, an external thread might want to activate a local context within another thread. Using the local activation counter accessors does not work from an external thread, given that these accessors always access information about the current thread. Therefore, Subjective-C provides a solution by allowing an external thread to notify a local context that it should be activated or deactivated within a specific thread. External local context activation events are added to a queue that is always processed just in time, that is, when a context method defined for a context with pending activations is invoked within the concerned thread. This can be seen as a sort of lazy context activation. This section aims to provide an explanation about external activations with pending activation queues Storing Details A pending activation queue aims to keep a list of local context activation events that came from an external thread. These activations are pending until the next time a locally dispatched 3 method is invoked within the thread the queue is related to. Figure 5.7 illustrates pending activation queues, in Subjective-C 2.0, for two different threads. These queues are stored in Thread 1 Thread dictionary Key Value Activation Queue Key activate activate deactivate Thread 2 Thread dictionary Key Value Activation Queue Key activate deactivate Figure 5.7: Thread pending activation queues the dictionary of their respective thread with a specific key SCThreadActivationQueue. The queue related to Thread 1 is made of three pending activation events: two activations and one deactivation. The queue related to Thread 2 is made of one activation and one deactivation. 3 Next section explains what is the relation between a local context and a local dispatcher.

83 CHAPTER 5. LOCAL CONTEXTS 73 Every time an external local context activation event occurs, an activation block is stored to the end of the pending queue related to the thread the activation event is aimed for. Figure 5.8 illustrates the addition of an activation block to a given thread pending queue by the Context Manager. In this example, a deactivation block is added to the Thread 1 pending queue and an activation block is added to the pending queue related to Thread 2. deactivatecontext:acontext forthread:thread1 activatecontext:acontext forthread:thread2 Context Manager Thread 1 Thread 2 Thread dictionary Key Value Activation Queue Key Thread dictionary Key Value Activation Queue Key add deactivation block deactivate add activation block activate activate Figure 5.8: Adding a pending activation to the related thread queue Given that these activation blocks are always stored at the end of a pending queue (i.e. enqueued), the activation order is always respected Processing the Queue As said in the previous section, the pending activation queue related to a given thread is processed when a locally dispatched method is called inside this thread. This implies a little modification of the local dispatcher algorithm introduced in Figure 4.3 by adding a step before all the others as illustrated in Figure 5.9. This new step consists in going through the whole pending activation queue related to the current thread and then empty the queue when all activation events have been processed. The source code of this check is shown in Snippet 5.4. As shown in this code snippet, an activation block is represented by an instance of the SCAction class. Each instance of this class is made of an Objective-C block and a pointer to an Objective-C object that should be given as a parameter to the block when it is called. In this case the object stored in an instance is the context related to the activation event and the stored block either activates or deactivates the context. Note that the activation queue is only checked if there exist some pending activations. The global variable SCLocalContextActivationPending is a counter that is incremented by the Context Manager when an external context activation event occurs. On the other side, every time an activation queue is processed, the pending activation counter is decremented by the size of the queue. Thanks to this principle, the local dispatcher avoids to check the queue

84 CHAPTER 5. LOCAL CONTEXTS 74 1: Process pending activation events 2: Find best context method 3: Create dynamic method invocation 4: Invoke method 5: Get return value Figure 5.9: Pending activation queue processing in dynamic dispatch algorithm Snippet 5.4: Processing a pending activation queue void checkpendingcontextactivations () { // Check the pending activation counter if ( _ SCLocalContextActivationPending ) { // Retrieve the queue SCMutableQueue * activationqueue = SCGetPendingActivationQueue (); if ( activationqueue ) synchronized ( activationqueue ) { _ SCLocalContextActivationPending -= [ activationqueue count ]; // Process activation events for ( SCAction * anaction in activationqueue ) { anaction -> action ( anaction -> object ); // Remove all activated contexts [ activationqueue removeallobjects ]; when there is no pending activation. Nevertheless, because this counter is global, its value might not be nil even though several activation queues are empty. statement is necessary to get a lock on the activation queue. This ensures that no pending activation will be added to the queue while it is processed.

85 CHAPTER 5. LOCAL CONTEXTS 75 Processing pending context activations before asking the Context Method Finder to find the best context method ensures that the method found by the Context Method Finder is always the most appropriate at this moment Activation Event Effect The activation of a local context (i.e. when it is sent the message activate) has the impact of replacing every related original method s implementation with its respective local dispatcher s implementation. A related original method here means every original method extended by a context method defined for the activated local context. On the other side, a local context deactivation (i.e. when it is sent the message deactivate) might result on replacing the original method s implementation with one of its context methods implementation. An original method only stops using its dynamic dispatcher s implementation as soon as no other local context related to this original method is active for at least one thread. To make the verification of this property as fast as possible, every local context keeps a counter of threads for which it is active. This counter is updated every time the local context is activated or deactivated within a specific thread as shown in Snippet 5.5. This code snippet shows that Snippet 5.5: Modifying the number of thread active for a local context - ( void ) setactivationcount :( NSUInteger ) newactivationcount { // Update the number of thread for which this local context is active if ( newactivationcount == 0) { numberofthreads - -; else if ( newactivationcount == 1) { numberofthreads ++; [ threadsactivationcounts setobject : [ NSNumber numberwithunsignedinteger : newactivationcount ] forkey : [ NSValue valuewithpointer :[ NSThread currentthread ]]]; when a local context is deactivated (for the current thread), that is, when its new activation count is zero, the number of threads related to the local context decreases of one. On the opposite side, when the new activation count is one, that is, when the local context is freshly activated, the number of threads increases of one. By verifying this counter, it is easy to determine whether a local context is still active for at least one thread. The original method keeps a set of local contexts related to itself and removes a local context from this set as soon as it is inactive for every thread. On the other side, when a local context becomes active, it is added to this same set. Figure 5.10 illustrates the behavior of Subjective-C 2.0 concerning an instance of the SCMethod class (i.e. an original method representation) when a local context activation event occurs. As expected, local context activation events have an impact on the dispatch mode of an original method. When a local context is activated, the concerned original methods dispatch modes switch to local for those that are currently in global mode. On the other side, when a local context becomes inactive for every thread, the concerned dispatch modes switch back to global if no other local context is active for these original methods. Note that an original method s

86 CHAPTER 5. LOCAL CONTEXTS 76 Context activation event NO Context Active YES Remove context from the set Add context to the set Remaining Contexts > 0 Dispatch Mode Global 0 Local Pending activations YES Done Switch to local dispatch NO Switch to global dispatch Figure 5.10: Original method context activation event handling flow chart dispatch mode does only switch to global if there are no pending activations for the current thread. 5.5 Discussion The previous sections explain in detail what happens when a local context activation occurs and how the data concerning a local context are stored and retrieved. As interesting as these capabilities are, they have a performance impact compared to global context activation events. Section provides an overview of local context performance by making a comparison with global context activation events. In additional to these benchmarks, Section explains the reason for adopting the system of pending activation queue. Finally, Section gives an explanation about the two different ways used to store information related to different threads Performance This section discusses the performance of local context activation events compared to global context activation events. Several benchmarks have been performed to evaluate the impact of local context activations on global performance. The first benchmark has been realized with Xcode Instruments. The other benchmarks have been realized with manual measures in the source code Pending Activation Impact on Local Dispatcher A first benchmark has been realized for evaluating the time spent in a local dispatcher for processing a pending local context activation event. The results of this experience are illustrated in Figure This chart shows that 70,2% of the time is spent for processing one pending

87 17,7472 6,4 2,2184 0,8 0,2773 0,1 1,3865 0,5 2,2184 0,8 6,1006 2,2 277, ,3 YES in dynamic dispatcher s Check pending activations Create invocation Dispatcher call Invoke method Get return value Other TOTAL 385, ,3 21,3837 3,9 2,1932 0,4 3,2898 0,6 2,1932 0,4 7,6762 5,3 548,3 100,1 548,8483 NO CHAPTER 5. LOCAL CONTEXTS 77 Time spent in dynamic dispatcher Find best context method Create invocation Dispatcher call Check pending activations Invoke method Get return value Other TOTAL Time spent in dynamic 2,2%,4% 5,3% 24,5% 14,8% 5,0% 91,4% 70,2% text method tion Find best context method Check pending activations Other Find best context metho Create invocation Other Figure 5.11: Local dispatch time repartition (1 context method with 1 pending activation event) activation event. This is due to the fact that this step requires to: 1. Retrieve the current context. 2. Retrieve the dictionary related to this thread. 3. Retrieve the pending activation queue in this dictionary. 4. Process the activation event. Even though it may look like a problem as it is a lot of time spent for this basic task, it is important to keep in mind that pending activation events are not that usual (compared to regular activation events). Most of the time, if the pending activation queue is not empty, it will contain at most one pending activation event. The following benchmarks make a comparison between the local contexts and the global contexts Varying the Number of Original Methods This benchmark examines the time spent in milliseconds for one local context activation event with a varying number of original methods for which this local context is related to. Its results are illustrated in Figure This benchmark demonstrates that the local context curve grows very slowly compared to the global context curve. This is due to the fact that a local context activation will at most replace the original method implementation with its respective dynamic dispatcher implementation, which is a fast operation. The curves grow because there are more and more original methods for which the implementation must be replaced. A global context activation will always replace the original method implementation with the best context method at the moment of the activation event. This implies to run the Context Method Finder s algorithm on every context activation event Varying the Number of Activations with 1 Context Method This benchmark evaluates the time spent for activating a local context a certain number of times. In this benchmark, illustrated in Figure 5.13, the context is used for defining only one

88 , , , , , , , , , , , , CHAPTER 5. LOCAL CONTEXTS 78 0,20 Number of original methods ,623 3,070 3,722 4,066 4,685 5,540 Number of Time in milliseconds 0,18 0,16 0,14 0,12 0,10 0,08 0,06 0,04 0,02 Time in milliseconds 6,3 5,6 4,9 4,2 3,5 2,8 2,1 1,4 0, of original methods 0Activations (1) Global Local , , Number 1,244 of original 1,618methods for this context 30 1,729 2, Global 2,181 2,897 Local 50 2,623 3,582 Activation (5) Global Local 60 3,070 3, ,091 0, ,722 4, ,433 1, ,066 4, ,285 4,685 1,773 5, ,547 5,540 2,320 6, ,918 2, ,309 3,626 Number of activations (1 context method) ,3 Figure 5.12: Performances of local context activations with varying number of original methods context method. This chart shows that the time spent for activating a local context related to 100 5,6 Time in milliseconds 4,9 4,2 3,5 2,8 2,1 1,4 0,7 5,833 4,043 6,226 4,393 6,522 4,934 7,184 5,486 Time in milliseconds Active 0versions Global Local , ,0 1 0,0415 Nu 0,0 2 0,0439 0,0 3 0,0444 Global 0,0 4 0,0462 Number of 0,0 5 0, , ,2 0,0499 0,0 8 0,0503 0,0 9 6,4 0,0513 0,0 Time in milliseconds 5,6 0,06 4,8 0, ,048 3,2 0,042 2,4 0,036 1,6 0,03 0,8 0,024 0,018 0,012 0,006 Number of a Nu Global inal methods for this context Local,624,393,773,320,972,626,043,393,934, ,2 6,4 2,4 Number of context activations Global Local Number of activation (5 context methods) Figure 5.13: Performances 8 of local context activations with varying number of activations (1 context method) only one context method is always higher than the time spent for activating a global context the 5,6 same number of times. The reason to this observation is that activating a local context requires 4,8 to retrieve the current context, access the activation counts dictionary for the current thread and 4 then modify an entry in this dictionary. On the other side, a global context activation requires Time in milliseconds to find the best current 3,2 context method for this original method. Logically, both curves grow almost linearly. 1, Varying0,8 the Number of Activations with 5 Context Methods The benchmark here is a variation of the previous one. In this case, the context is used for defining 5 context methods, which are related to different original methods. The results are il- Number of context activations Global Local Number of active Global

89 Tim 2,1 Tim 0,018 1,4 0,7 0,012 0, hods for this context Local CHAPTER 5. LOCAL CONTEXTS 79 Number of context activations lustrated in Figure ThisGlobal benchmark highlights the Local fact that the number of context methods Number of activation (5 context methods) 8 7,2 6, Number of a Global Time in milliseconds 5,6 4,8 4 3,2 2,4 1,6 0, Number of context activations Global Local Figure 5.14: Performances of local context activations with varying number of activations (5 context methods) does not have a big impact on a local context activation. This is because a local context activation only implies that each different original method s implementation is replaced with their respective local dispatcher s implementation. On the other side, a global context activation takes much more time as it needs to find each best context method and uses its implementation for replacing their corresponding original method s implementation. Still, both curves grow almost linearly Varying the Number of Context Methods The last benchmark aims to study the variation of time spent for one context activation by varying the number of additional candidate context methods extending a same original method. Of course, this context is used for defining a context method for which the respective original method is the same as for all these additional context methods. The results of this benchmark are illustrated in Figure As expected, the number of additional context methods does not have an effect at all on a local context activation. This is simply due to the fact that a local context activation only switches the original method to the local dispatch method. The number of related context methods does not have an impact at all at activation time. On the other side, the time spent activating a global context grows almost linearly with the number of related candidate context methods because the Context Method Finder algorithm must compare all the context methods between each other to find the best one (see Chapter 7) Pending activation queue The solution adopted for activating a local context from an external thread might seem a little surprising at first look. Indeed, using a pending activation queue seems unnatural at first compared to a more direct solution. The first idea for allowing activations from external threads was to add a method activateforthread: to the SCLocalContext class so that a local context could directly and simply be activated from an external thread. But this idea was dismissed because it requires to make too many huge modifications at very different places in the source code. Indeed, adding thread information at the activation level would require to carry this infor-

90 (1 context method) ,0462 0,0578 0,0465 0,058 0,0491 0,058 0,0499 0,0581 0,0503 0,0584 0,0513 0,0582 CHAPTER 5. LOCAL CONTEXTS 80 0,06 Number of active context methods 0,054 0,048 Time in milliseconds 0,042 0,036 0,03 0,024 0, xt activations Local (5 context methods) 0,012 0, Global Number of additional context methods Local Figure 5.15: Performances of local context activations with varying number of active context methods ext activations Local mation through the whole activation process, especially through the calls to SCLink instances that propagate the activation events to the contexts that are in relationship. An additional parameter representing a specific thread would need to be added to every method concerned by local context activation events, which would be a high price to pay in terms of code complexity. Because these modifications were considered too onerous, an easier solution has emerged: keep the context activation event stored somewhere and perform the activation later in the thread that is concerned by this activation event. This lazy context activation entirely respects the activation order and is thus a valid solution. The activation events are therefore processed just in time Using the Thread Dictionary One thing that might look appealing is that this chapter presents two different ways to store data that are related to a given thread. The first solution introduced in Section 5.3 for local context activation counts consists in using a local dictionary that would have a given thread as a key and the corresponding data would be related to this thread. The second solution introduced in Section for pending activation queues consists in using the dictionary carried by every thread during its lifetime. Most of the time, it is easier to use the thread s dictionary, given that it is always carried by the corresponding thread and it is then easy to retrieve data stored during a previous operation. It is particularly interesting in producer-consumer scenario. The case of pending activation queues is one application of this scenario where the context manager is the producer (of pending activations) and the dynamic dispatcher is the consumer. In the case of local context s activation counters, it is easier and faster to store thread-related information internally instead of using the thread dictionary. This ensures a direct access to the activation count dictionary and an activation counter is retrieved or modified in one step. If the thread s dictionary were used, it would require four steps:

91 CHAPTER 5. LOCAL CONTEXTS Retrieve the current thread. 2. Retrieve the current thread dictionary. 3. Retrieve the activation count dictionary in this thread dictionary. 4. Access or modify the activation count. 5.6 Conclusion Local contexts allow to define behavior that is local to given threads. Even though this mechanism is useful in several cases such as logging or tracing, it comes with a big overhead compared to global contexts. This is because local context information is stored in a dictionary so that it can keep separate information for each thread within which it is active. Therefore, local contexts must be wisely used to not incur a huge global performance loss. Nevertheless, the performance impact of local contexts could be minimized thanks to various optimization techniques such as caching thread-local information between two context activation events. Chapter 10 gives further details about such an optimization mechanism. Furthermore, these local contexts open the perspectives of new kind of behavioral scopes. Thanks to this mechanism, it is now possible to execute blocks of instructions within which several local contexts are active with no impact on the other parts of the application.

92 Chapter 6 Resend Mechanism Contents 6.1 Problems of the Supercontext Mechanism Resend Calls History Principle Motivation Multiple Histories Recursive Calls within Context Methods Inter-Method Calls Multiple Histories in Subjective-C Definition Resend Algorithm Definition of Resend Call NSObject Class Extension Discussion Performance Fault Tolerance Conclusion Subjective-C 1.0 introduced the supercontext mechanism that allows to call the next context method, as explained in Section This mechanism has one main problem, it is not thread-safe. Because of that, a new resend mechanism has been introduced for replacing the supercontext system. This new mechanism is similar to the resend mechanism introduced in Ambience [Gon08]. However, in Subjective-C, this mechanism is extended with the support of context methods defined for local contexts. Section 6.1 explains in detail the problems of the supercontext mechanism. The resend mechanism comes with the notion of resend calls history that is presented in Section 6.2. The definition of the resend mechanism and its algorithm are shown in Section 6.3. Finally, Section 6.4 discusses the global performance of this mechanism. 82

93 CHAPTER 6. RESEND MECHANISM Problems of the Supercontext Mechanism As explained in Section and Section 3.3, the supercontext mechanism is not threadsafe. To understand the weaknesses of supercontext, the translation of the following statement is analyzed in this section. [supercontext isoutofbound] => aboolean; Snippet 6.1 shows the supercontext call translated into standard Objective-C code. Snippet 6.1: Supercontext call translated in Objective-C [ MANAGER callsupercontextmethod selector ( isoutofbound ) forclass :[ self class ]]; aboolean = [ self isoutofbound ]; [ MANAGER restorecontextmethod selector ( isoutofbound ) forclass :[ self class ]]; The main problem of the approach adopted by Subjective-C 1.0 is that a supercontext is translated in 3 separated statements. The first statement asks the Method Dispatcher to prepare the supercontext call. The second statement makes the call to the next method. Eventually, the last statement asks the Method Dispatcher to restore everything as it was before the supercontext call. Preparing a supercontext call means that the original method implementation is replaced with the implementation of the corresponding next context method. This approach is not thread-safe for two reasons: If another thread activates a context between the supercontext call preparation and the method call. In this case, the original method implementation might not correspond to the next context method found by the Context Method Finder. Modifying the original method s implementation has an impact on all the threads calling this original method. An external thread should not be affected by a supercontext call. Furthermore, this mechanism is incompatible with the notion of local contexts. Because it is not thread-safe, it is impossible to safely perform several nested supercontext calls as a context activation event might modify the original method implementation and therefore confuse the Context Method Finder about the current supercontext level. The new resend mechanism does not modify the original method implementation. Rather, it creates a dynamic invocation to the next context method. Thus, the impact is only local to the thread making the resend call. Another problem introduced with the supercontext mechanism is that it imposes a specific syntax for storing the result of a call into a variable. This specific syntax is not standard and is not flexible enough as it cannot be used as a method call parameter for instance. As shown in Chapter 8, keyword is translated into an Objective-C block that can be used everywhere as a simple function call.

94 CHAPTER 6. RESEND MECHANISM Resend Calls History For being able to nest several resend calls, a history of these resend calls must be kept. Therefore, resend calls must be completely isolated in the thread from which the call comes from. As explained in next chapter, the Context Method Finder uses this resend calls history for removing the methods that have already been resent from the methods received as input by the algorithm used for finding the next context method (see Chapter 7) Principle Every time a context method makes a resend call, its selector 1 is added to the resend call history corresponding to the current thread. When the resend call ends, the selector added before the call is removed from the history. The history can be seen as a stack. Therefore a resend call is made in 3 steps: 1. Push the source context method selector. 2. Call the next context method. 3. Pop the source context method selector. Figure 6.1 illustrates the resend history as a timeline. In this timeline, m 1 makes a resend call return return m1 m2 m3 time resend resend Figure 6.1: Resend history timeline at first. The Context Method Finder finds m 2 as the next context method. After that, m 2 also makes a resend call that leads to m 3. When a resend call ends, it returns to the calling context method 2. In Subjective-C. this resend call history is stored in the calling thread dictionary so that each thread has its own isolated history Motivation To find the next context method, Subjective-C 1.0 makes a comparison between the current original implementation and the implementation of the corresponding context methods. As explained in the previous section and in Section 3.3, this solution is not thread-safe because a context activation event happening in between might confuse this mechanism. Nevertheless, one might think about a solution based on locks to avoid intermediate context activation events. This solution is not valid because it might produce deadlocks. Indeed, a resend call might lead to a method starting an infinite loop and therefore, the resend locks would never be released. With the resend call history, each thread keeps an isolated trace of methods that must not be taken into account by the Context Method Finder for finding the next context method. The order 1 A selector acts as the name of a method. Each context method related to the same original method has a unique selector. 2 The context method performing a resend call is also called the source context method.

95 CHAPTER 6. RESEND MECHANISM 85 in which each next context method will be found cannot be predicted because of the possibility for a context activation event to happen between two nested resend calls. Nevertheless, it is always ensured that the next context method found at a given time t corresponds to the best context method in the list of remaining context methods, that is, the context methods that are not present in the history at this time t. In other words, the history timeline cannot be predicted but it is ensured that every consecutive next context method is different from the previous ones in the same history. It might happen that a resend call is made when all the possible context methods are already present in the history. In this kind of situation, the default method is called (see Chapter 7). Obviously, a resend call cannot be made inside a default method as it would result in a compilation error Multiple Histories The resend history is used to make sure that context methods are not resent twice in a same history. Nevertheless, using a single history per thread is not a valid approach in several situations Recursive Calls within Context Methods One problematic situation concerns recursive calls occurring inside resent context methods. With resend call histories as defined so far, resend calls occurring inside a recursive call are not dispatched correctly because the current history already contains context methods extending the same original method. Snippet 6.2 shows an example code where such a situation might happen. In this example, an original method m is defined with three behavioral variations: one Snippet 6.2: Example code needing multiple resend call contexts Logging - ( void )m { NSLog (@" Log something contexts Up - ( void )m (); - ( void )m { if (...) { // Recursive call [ self m];... for Logging (m log ), one for Up (m up ) and one for the default behavior (m de f ault ). The context

96 CHAPTER 6. RESEND MECHANISM 86 methods defined for Logging and Up always perform a resend call. The default method might perform a recursive call, depending on the value of the conditional statement. Figure 6.2 illustrates how such a situation cannot work properly with the current definition of the resend mechanism. At the beginning, the resend call history is empty. When m log and m up Resend history (call time) Global history Resend history (return time) empty log log log log up up up log log up default log default time call1 call2 empty empty log log log Legend: up up regular call resend call return Figure 6.2: Several original methods in a same resend history perform the resend call, their respective selector is added to the resend history. When mde f ault performs the recursive call, the resend call history is unchanged. Therefore, when m log performs a resend call in this recursive call, the call is resent to m de f ault because m up is already in the history and is therefore dismissed by the Context Method Finder. This is a problem because resend calls occurring within two separate recursive calls should be independent. Instead, m up is ignored and the call is resent to the next context method that is not present in the history (i.e. the default method). This is due to the fact that the Context Method Finder prunes away the context methods that are already in the history. A solution to overcome this problem is to temporarly isolate resend call histories when a recursive call occurs in context methods. Resend call histories must then be restored when this recursive call returns. Figure 6.3 illustrates the application of such a solution to the example shown in Snippet 6.2. In this figure, the current resend call history is isolated when mde f ault makes a recursive call to m. A new resend call history is created for the resend call corresponding to the recursive call. When m log returns, the previous resend call history is restored. This ensures that every context method can be resent again when a recursive call occurs Inter-Method Calls Another problematic situation concerns inter-method calls. Inter-method call means that two context methods defined for two different original methods perform a call to each other. Snippet 6.3 shows an example code where such a situation might happen. In this example, an original method m1 is defined with three behavioral variations in the exact same way as with de f ault the method m in the previous example. The only difference is that m1 does not perform a recursive call but rather makes a call to another method m2 (m 2 ). The situation is similar to the previous example because resent context methods are not correctly dispatched when the calls happen in the following order: m log 1 resend m up 1 resend de f ault resend de f ault m1 m 2 m log 1 m1...

97 CHAPTER 6. RESEND MECHANISM 87 Resend histories (call time) Global history Resend histories (return time) empty log log up call1 log up default restore previous history empty empty log empty log log up create new history call2 log up default log up empty log Legend: regular call resend call return Figure 6.3: Multiple resend history timelines Snippet 6.3: Example code needing multiple resend call contexts Logging - ( void )m1 { NSLog (@" Log something contexts Up - ( void )m1 (); - ( void )m1 { // Calling m2 [ self m2 ]; - ( void )m2 { // Calling m1 [ self m1 ]; represents a resend call and represents a regular method call. In this example, the last resend call occurring in m log 1 cannot be dispatched to m up 1 because this context method is already in the resend call history. Note that m log 1 is invoked again because the active set of contexts has not changed between each method call and also because resend call histories are supposed to be independent between two calls to different original methods. where resend

98 CHAPTER 6. RESEND MECHANISM 88 A solution to overcome this problem is, as for the previous situation, to isolate the current resend call history when a context method extending m 1 and performing a resend call is called from a method m 2 that is not a behavioral variation of m 1. The resend call history must be restored when this resend call returns Multiple Histories in Subjective-C 2.0 The notion of isolated resend call histories explained in this section ensures that resend calls related to different original methods or occurring within different threads are independent from each other. Resend calls can therefore be used in the exact same way as regular function calls and method calls. Subjective-C 2.0 does only provide a partial implementation of the solution explained in this section. Subjective-C 2.0 isolates resend call histories when the source context method of a resend call is a variation of another original method than the one related to the current resend history. This corresponds to a particular case of the second situation presented in this section. In this solution, resend call histories are restored as soon as the current history is empty. An implementation of the full-fledged resend mechanism remains as future work. Chapter 10 gives an idea of the main difficulties involved in the implementation of such a mechanism. The next section explains the whole resend mechanism solution provided by Subjective-C Definition The resend mechanism is really similar to using a local dispatcher (see Chapter 4). The main differences between the two mechanisms is that the resend mechanism needs call the next context method and also requires updates of the resend call history Resend Algorithm Subjective-C resend s mechanism algorithm follows the four steps illustrated in Figure 6.4. This figure clearly shows how this algorithm is similar to the local dispatch s one. Actually, both mechanisms share the same source code for the steps 1, 3, 4 and 5. The second step is the only step that differs from the local dispatcher algorithm as it asks the Context Method Finder to find the next context method. These five steps are wrapped by the update of the resend history. The source context method is added to the history before the first step of the algorithm and is removed after the last step. This resend mechanism allows nested resend calls. The only limit is the number of remaining candidate context methods at the time the resend call is made. When no more candidate context methods remain, the corresponding default method is used Definition of Resend Call The definition of the resend call mechanism, shown in Snippet 6.4, is a strict application of the algorithm illustrated in Figure 6.4. The source code shown in Snippet 6.4 does the following steps:

99 CHAPTER 6. RESEND MECHANISM 89 Add source context method to history 1: Process pending activation events 2: Find next context method 3: Create dynamic method invocation 4: Invoke method 5: Get return value Remove source context method from history Figure 6.4: Resend call algorithm 1. Add the selector to the history. Actually this step does more than that as it is in charge of putting the current history aside if the original method related to source context method does not match with the current history original method. 2. Check the pending context activation events. 3. Find the next context method. The Context Method Finder uses the information stored in the resend calls history to find the next context method. See Chapter 7 for further details about it. 4. Create a dynamic invocation to the next context method. 5. Invoke the next context method. 6. If needed, get the return value from the invocation. 7. Remove the selector from the history. As for step 1, this step does more than simply removing the source context method from the history. If the history is empty after removing the selector, the previous history that was put aside in step 1 is restored. Note that steps 2 6 in Snippet 6.4 correspond to steps 1 5 in Figure 6.4. One might be surprised by seeing statement block wrapping steps 5 and 6 and wrapping step 7. This is mandatory because an exception might occur during the dynamic method invocation and therefore unexpectedly leave the SCResend function. Nevertheless, if the step that consists in removing the source context method were omitted then the current history would become inconsistent. Therefore, wrapping these three steps with a catching exception block ensures that the history always reflects reality NSObject Class Extension The SCResend function is not intended to be used directly inside a context method. Rather, the NSObject class has been extended with an instance method that allows to resend a context method in a more user-friendly way, as shown in Snippet 6.5. Because every Objective-C

100 CHAPTER 6. RESEND MECHANISM 90 Snippet 6.4: Resend call implementation void SCResend ( id receiver, SEL baseselector, SEL currentselector, void * returnvalue, va_list methodarguments ) { // 1. Add selector to history SCResentMethodsSet * oldresentmethods ; SCResentMethodsSet * currentresentmethods ; preresend ( receiver, baseselector, currentselector, & oldresentmethods, & currentresentmethods ); // 2. Process pending context activation checkpendingcontextactivations (); // 3. Find the next context method SCContextMethod * contextmethod = [[ SCMethodDispatcher sharedmethoddispatcher ] findnextcontextmethodfromoriginalselector : baseselector relatedclass : SCClassOf ( receiver ) isinstancemethod : SCIsInstance ( receiver )]; // 4. Create the dynamic invocation NSInvocation * invocation = getmethodinvocation ( receiver, contextmethod, methodarguments { // 5. Invoke the method [ invocation invoke ]; // 6. Get the return value if ( returnvalue ) { [ invocation getreturnvalue : returnvalue { // 7. Remove selector from history postresend ( currentselector, oldresentmethods, currentresentmethods ); class is supposed to subclass NSObject 3, every regular instance can make a call to the method resendselector:withcontextselector:returnvalue:. The first parameter of this method is the original selector of the source context method. The second parameter is the context selector of the source context method. The third parameter is a pointer to the return value. Finally, the last parameter is a variadic list of parameters that act as the resend call parameters. Note that the reference to the source instance is automatically found by using self because the method used here is an instance method. A class context method can also resend a context method by using the same utility method because every Objective-C class inherits from the NSObject class. Because the two first parameters should not be guessed by the programmer, each context method contains two hidden constant variables: 3 Exception made to the NSProxy subclasses.

101 CHAPTER 6. RESEND MECHANISM 91 Snippet 6.5: NSObject extension with SCContext implementation NSObject ( SCContext ) - ( void ) resendselector :( SEL ) originalselector withcontextselector :( SEL ) contextselector returnvalue :( void *) returnvalue,... { if ( originalselector == contextselector ) [ NSException exceptionwithname :@" Resend call within a " " default method " reason :@" A default method cannot " " perform a resend call " userinfo : nil ]; // Get the methods arguments va_list methodarguments ; va_ start ( methodarguments, returnvalue ); SCResend ( self, originalselector, contextselector, returnvalue, methodarguments SCOriginalSelector: the selector of the original method which the source context method is extending. SCContextSelector: the selector of the source context method. Chapter 8 explains that keyword is translated into a call to the the instance method introduced in this section. The parser automatically uses the two hidden variables SCOriginalSelector and SCContextSelector. The next section discusses the performance of this mechanism by measuring how much time is spent in resending a method. 6.4 Discussion This sections aims to discuss the performance of the resend mechanism (Section 6.4.1) and to prove that this mechanism is fault tolerant (Section 6.4.2) Performance Because the resend mechanism shares a lot with the dynamic dispatch mechanism, this section only focusses on the differences between these two mechanisms. There are mainly two things that change with the resend mechanism: Handling the resend calls history. Finding the next context method. This part is further discussed in the next chapter.

102 Time (%),9 0, ,008 0,8 0 0, ,635 64,6 5 0,074 7,5 6 0,008 0,8 7 0, ,001 0,1 6 0,155 15,8 8 0,092 9,4,9 1, ,9 1 Task Time (ms) Time (%) NSObject Find next context method Create invocation Pre resend 45,346 0,155 15,8 CHAPTER 6. RESEND MECHANISM 92 Post resend SCResend Check The benchmark presented Invoke in this section has 2,296been realized 0,008 with 0,8 1 original method and 2 context Get return 2,87 0,010 1 methods extending this original method. The measures have been made with Xcode Instruments. try catch Other History TOTAL 4,9 0, ,402 0,635 64,6 21,525 0,074 7,5 26,978 0,092 9,4 2,296 0,008 0,8 0 0, ,287 0,001 0,1 7,749 0,027 2,7 72,324 0,248 25,2 291,9 1, Figure 6.5 shows the time repartition for each 291,9 subtask during 1 a resend call. It shows that 64% of Resend 3% 2% 25% 7% 64% NSObject Create invocation Other Find next context method History Figure 6.5: Resend call time repartition the time is spent finding the next context method. This measure is not really relevant here as it is part of the Context Method Finder. Thus, this time could increase or decrease independently from the other part of the algorithm. Another interesting thing this chart shows is that 25% of a resend call is spent for updating the resend call history. Updating this history is made of two distinct parts: Adding the source context method to the history Removing the source context method from the history The time spent updating the history may vary a little depending on whether a new history must be created or restored. These measures have shown that in these 25% needed for updating the history, 7.4% are used for creating a new history and 3.8% for restoring an old history. This means that in the case of nested resend calls, only 13.8% is spent updating the history (i.e. only adding and removing the source context methods). This graph shows that, in the same logic as in Chapter 4 with local dispatchers, most of the time ( 2 3 here) is spent in the Context Method Finder algorithm. Details about this module are given in the next chapter Fault Tolerance The resend mechanism is highly similar to the dynamic dispatch mechanism introduced in Chapter 4. Therefore, the reasoning about fault tolerance explained in Section applies for the steps that are similar between each mechanism. The two differences between both

103 CHAPTER 6. RESEND MECHANISM 93 mechanisms are that the resend mechanism calls the next context method and has to manage the resend calls history. The fault tolerance is ensured for the next context method call because it is assumed that the implementations of Subjective-C and Objective-C do not produce errors when they implementations are used as they have been designed for. Nevertheless, the resend calls history needs to be updated before and after the next context method call. The source code shown in Snippet 6.4 shows that the resend mechanism always ensures that the source context method is removed from the resend calls history after the next context method call thanks to statement. Therefore, if an exception is thrown during the execution of the next context method, the source context method is removed from the history and the resend mechanism lets this source context method handle the exception. Thanks to this property, the resend calls history never becomes inconsistent. For all these reasons, it is assumed that the resend mechanism is fault tolerant. 6.5 Conclusion The resend mechanism allows context methods to invoke another context method with a lower precedence. This chapter shows that this mechanism is very similar to the dynamic dispatch system introduced in previous chapters. The main difference is that resending a method consists in calling the next context method. Additionally to this method call, the resend mechanism must ensure that the resend call history is always updated before and after a resend call so that the Context Method Finder can use this information to find the correct next context method and not resend a same context method twice in the same history.

104 Chapter 7 Context Method Finder Contents 7.1 New Context Method Precedence Properties Context Activation Age Local Context Presence Property Precedence Order Algorithms Find Best Context Method Find Next Context Method Discussion Time Spent for Retrieving the Activation Age of a Context Time Spent for Knowing if a Context Method is a Candidate Time Spent for Finding the Best Context Method Time Spent for Finding the Next Context Method Conclusion Previous chapters present Subjective-C major concepts such as context activation events, resend mechanism and locally dispatched methods. All these concepts resort to the Context Method Finder. A global context activation event replaces several original method implementations with their respective best context method at the moment of the activation event. A locally dispatched method always seeks the best context method for creating a dynamic invocation to this context method. Eventually, a resend call creates a dynamic invocation to the next context method corresponding to the method from which the call came. Searching the best or the next context method are two tasks achieved by the Context Method Finder. This chapter presents the algorithm of each of these tasks. Section 7.1 introduces two new properties taken into account by the Context Method Finder for sorting the context methods by precedence. The algorithms for finding the best and the next context method are presented in Section 7.2. Finally, Section 7.3 discusses the Context Method Finder performance through several benchmarks. 94

105 CHAPTER 7. CONTEXT METHOD FINDER New Context Method Precedence Properties Subjective-C 1.0 s Context Method Finder, introduced in Section , is taking into account two properties about context methods: Its priority, used for ordering context methods extending a same original method. Methods with a higher priority take precedence over methods with a lower priority. Its candidate status, used for determining what context methods should be taken into account by the Context Method Finder for choosing the best context method. Methods which are not candidate are automatically dismissed. In Subjective-C 1.0, the Context Method Finder chooses the first candidate context method with the highest priority. Subjective-C 2.0 adds two new properties for refining the search of the best context method: Being defined for a local context, used for ordering context methods extending a same original method. Methods defined for local contexts take precedence over methods defined for global contexts. The lowest activation age of the context for which methods are defined, used for ordering methods with the same priority and defined for the same kind of contexts (i.e. global or local). For ease of reading, this section uses the terms local context method and global context method. Local context methods are defined for at least one local context whereas global context methods are exclusively defined for global contexts Context Activation Age Each context has an activation age that defines a strict order among active contexts. This activation age is used to determine if contexts have been activated before or after other contexts. Therefore, when a context is activated (i.e. when it is sent the message activate) at a time t, its age becomes the lowest possible at this time t. When a context is deactivated (i.e. when it is sent the message deactivate), it does not have an activation age anymore. Note that inactive contexts do not need an activation age as context methods defined for these context are automatically dismissed by the Context Method Finder Formal Definition To ease the reading of this section, additional sets are defined for denoting active contexts from inactive contexts 1. ACT IV E CONT EXT INACT IV E CONT EXT ACT IV E INACT IV E = CONT EXT ACT IV E INACT IV E = /0 the set of active contexts the set of inactive contexts a context is active or inactive a context cannot be active and inactive The following predicate defines the set of active contexts as follows: c CONT EXT : c ACT IV E state(c) = active 1 See Section for the definition of the sets and functions used in this section.

106 CHAPTER 7. CONTEXT METHOD FINDER 96 A new relation among active contexts is introduced to represent the age difference between each other. The function age returns the context activation age of the context given as a parameter. age : ACT IV E N 0 In this definition, the activation age of an active context is an integer. In additional, the function youngest returns the youngest context for which a candidate context method is defined. youngest : CANDIDAT E CONT EXT For two different contexts c 1 and c 2, it is said that c 1 c 2 when the age of c 1 is superior by 1 to the age of c 2. In other words, it says that c 1 has been activated right before c 2. c 1 ACT IV E, c 2 ACT IV E : (c 1 c 2 ) age(c 1 ) = (age(c 2 ) + 1) n With the same logic, for two different contexts c 1 and c 2, it is said that c 1 c 2 when the age of c 1 if superior by n to the age of c 2. c 1 ACT IV E, c 2 ACT IV E, n N 0 : (c 1 n c 2 ) age(c 1 ) = (age(c 2 ) + n) Given that there exists a strict order among contexts activation age, two different contexts can t have the same activation age. c 1 ACT IV E, c 2 ACT IV E : c 1 0 c 2 c 1 = c 2 Eventually, for two different contexts c 1 and c 2, it is said that c 1 c 2 when c 1 is older than c 2, that is, the last activation of c 1 occurred before the last of c 2. c 1 ACT IV E, c 2 ACT IV E : (c 1 c 2 ) age(c 1 ) > age(c 2 ) The following example illustrates 4 global context activation events and the impact of these activations on each context activation age. The array on the right represents the activation age timeline for contexts A, B, C and D after each activation event. Time Timeline Event t 0 : A B C D activate B t 1 : A C D B activate A t 2 : C D B A activate A t 3 : C D B A deactivate D t 4 : C B A A B C D Everything can be seen as a context activation timeline. At time t 0, the context D is the last that has been activated and thus becomes the youngest context. At this time, the age difference

107 CHAPTER 7. CONTEXT METHOD FINDER 97 between A and D can be represented by A 3 D. When B is activated, its age becomes equal to 0 and therefore becomes the youngest context. At this moment, the age difference between A and D is represented by A 2 D. Then A is activated and it therefore in front of the context activation timeline. The next event happening between t 2 and t 3 shows that activating a context that is already in front of the timeline does not have an impact on the activation timeline. At this moment, the age difference between A and D is represented by D 2 A. Finally, at time t 4, D has been deactivated and is thus removed from the timeline. This property is dynamic compared to the priority of a context method and to the presence of local contexts because the activation age relations may vary from one method call to another. The next section shows that this activation age property may even vary from one thread to another in case of local contexts Local Context Activation Age Local contexts are always activated within a specific thread and may be therefore be active for a thread t 1 and inactive for a thread t 2. Therefore, the activation age of a local context depends on the currently running thread. This implies that several different timelines may exist within a same application, that is, one timeline per running thread. Section 5.2 presents two structures maintained internally by instances of the SCLocalContext class to store information related to each thread for which this context has been activated (see Figure 7.1). The first structure stores the activation counter corresponding to each thread. The Thread 1 Activation count Thread Number Thread 2 Last activation Thread Number Figure 7.1: Local context threads information second structure, which is not explained in Section 5.2, is a dictionary that is used for the context activation age related to each thread. In the exact same logic as for the local context activation counter, the local activation age related to a specific thread is accessed by using the thread as a key for the dictionary. Therefore, only the activation age accessors have been redefined for the SCLocalContext class Local Context Presence In Subjective-C 2.0, local context methods take precedence over global context methods if these global context methods have a priority inferior or equal to these local context methods. This property is justified because it seems more natural that local contexts active within the

108 CHAPTER 7. CONTEXT METHOD FINDER 98 current thread have a bigger impact than global contexts. This property is therefore focusing on the scope of context methods. The next section defines an order of importance among the properties of context methods taken into account by the Context Method Finder for finding the best context method Property Precedence Order With the two new properties introduced in the previous sections, it is needed to define a processing order between all the properties taken into account by the Context Method Finder. For each active context method: 1. The Context Method Finder checks the context method priority. 2. If there are several candidate context methods with the same highest priority and these are made of local and global context methods, the Context Method Finder prunes away the global ones. 3. If there remains more than one context method, the Context Method Finder checks the lowest activation age for each of these methods. 4. If there are more than one remaining method with the lowest context activation age, then the Context Method Finder chooses the the first in the ordered list 2. Therefore the Context Method Finder first checks the priority of a context method (1), then its scope (2) (i.e. local or global) and then the lowest activation age of the context for which this method is defined (3). Given that these new properties are checked by the Context Method Finder, the relations =, o o > and > p o must be redefined. As a reminder, = and > o define an order relation in an array of context methods extending a same original method. The relation p > defines a precedence relation among context methods and is used by the Context Method Finder for determining what is the best context method. See Section for further details. Because Subjective-C 2.0 makes a difference between local contexts and global contexts, two new sets must be defined, additionally to those defined in Section LCONT EXT CONT EXT GCONT EXT CONT EXT LCONT EXT GCONT EXT = CONT EXT LCONT EXT GCONT EXT = /0 the set of local contexts the set of global contexts a context is global or local a context cannot be global and local Furthermore, two additional sets are defined for denoting a local context method from a global context method. LCMET HOD CMET HOD GCMET HOD CMET HOD LCMET HOD GCMET HOD = CMET HOD GCMET HOD LCMET HOD = /0 the set of local context methods the set of global context methods a context methods is global or local a context method cannot be global and local The scope of a context method is said to be local when it is defined for at least one local context. 2 In Subjective-C, a same context can be used to define several context methods extending a same original method. Therefore, several context methods extending a same original method can have the same lowest activation age. Chapter 10 discusses this characteristic and suggests additional disambiguity rules.

109 CHAPTER 7. CONTEXT METHOD FINDER 99 m CMET HOD, c contexts(m) : c LCONT EXT m LCMET HOD The scope of a context method is said to be global when it is exclusively defined for global contexts. m CMET HOD, c contexts(m) : c GCONT EXT m GCMET HOD As it was the case in Subjective-C 1.0, m 1 o > m2 is true for two context methods m 1 and m 2 when the priority of m 1 is higher than the priority of m 2. m 1 CMET HOD, m 2 CMET HOD : prior(m 1 ) > prior(m 2 ) m 1 o > m2 With the introduction of local contexts in Subjective-C 2.0, if a context method m 1 is local and another context method m 2 is global, then m 1 o > m2 if both context methods have the same priority. m 1 LCMET HOD, m 2 GCMET HOD : prior(m 1 ) = prior(m 2 ) m 1 o > m2 The relations o > and o = are therefore determined first by method priority, and then by method scope (local vs. global). From the two previous predicates and from the Context Method Finder s point of view, it is assumed that for two context methods m 1 and m 2, m 1 o > m2 implies that m 1 p > m2 when m 1 is a candidate for its respective original method. m 1 CANDIDAT E, m 2 CMET HOD : m 1 o > m2 m 1 p > m2 o When two context methods m 1 and m 2 have the same priority and both are local (i.e. m 1 = m2 ), then the Context Method Finder must look at the context activation age property. Given that m 1 is a candidate, if m 1 is defined for a context c 1 that is younger than any context c 2 for which p m 2 is defined (i.e. c 1 c 2 ), then m 1 takes precedence over m 2 (i.e. m 1 > m2 ). m 1 CANDIDAT E, m 2 CMET HOD : o p (m 1 = m2 youngest(m 1 ) youngest(m 2 )) m 1 > m2 Eventually, several context methods m 1 and m 2 may have the same precedence (i.e. m 1 p = m2 ) when m 1 o = m2 and both context methods are defined for the same related youngest context. m 1 CANDIDAT E, m 2 CANDIDAT E : m 1 o = m2 youngest(m 1 ) = youngest(m 2 ) m 1 p = m2 Several context methods m 1 can have the same precedence (i.e. p =) and take precedence over all the other context methods m 2 (m 1 p > m2 ). The Context Method Finder always chooses one of the context methods taking precedence over all the others. Note that there might be several context methods taking precedence over all the other methods because a same context can be used to define several context methods extending a same original method. All these predicates allow to define the algorithms in the following section.

110 CHAPTER 7. CONTEXT METHOD FINDER Algorithms The Context Method Finder has two responsibilities, finding the best context method and finding the next context method, both in a given array of context methods related to the same original method. The section defines the algorithm for both of these responsibilities Find Best Context Method Compared to Subjective-C 1.0, finding the best context method in an array of context methods is more complex because the Context Method Finder cannot simply return the first encountered candidate method anymore. As explained in the previous section, it must now consider the presence of a local context if several context methods have the same priority. If it is not enough for finding one best context method, the Context Method Finder also takes a look at the lowest context activation age for each method considered as equivalent for the priority and local context presence priorities Flow Charts Figure 7.2 illustrates the Context Method Finder algorithm as a flow chart for finding the best context method. The first step in the dashed rectangle consists in finding all the methods that Find Best Method Find equivalent context methods Number of equivalent methods > 1 NO Best context method found YES Find context method with highest precedence Figure 7.2: Subjective-C 2.0 find best context method flow chart are considered as equivalent. Before explaining this step, it is needed to make a recap about how the array of context methods is ordered. Such an array is illustrated in Figure 7.3. The Priority 1000 Priority 900 Priority 0 Local Global Local Global Local Global... Default method Ascending priority Figure 7.3: Ordered array of context methods related to a same original method context methods in this array are regrouped by ascending priority. Inside each of these groups, the local context methods take precedence over the global ones. Every array of context methods extending a same original method is reordered when a new context method related to the same original method is added in the system. This array is therefore ordered according to the relation

111 CHAPTER 7. CONTEXT METHOD FINDER 101 o > and o =. For all context methods m 1 and m 2 in the same subgroup Local, m 1 o = m2. The same rule applies for the methods in the same subgroup Global. But for all context methods m 1 within a subgroup preceding another subgroup made of context methods m 2, m 1 o > m2. This is why o > and o = define order relations. Note that the context activation age is not taken into account for ordering such an array. This is because the context activation age might be a thread-local property in case of local contexts. This property is therefore considered at a later stage. Note that in Subjective-C 2.0, the default method is considered as a context method too. Its priority is lower than any other context method extending the same original method and it only has the default context related. The default context is a global context that is always active. Given these default method characteristics, this method is always the last in the ordered array illustrated in Figure 7.3. This simplifies the algorithm for finding the best context method because the default method is not a special case anymore. When no regular context method can be found, the Context Method Finder always chooses the default method in the end. Because the default method is always a candidate for its respective original method, the Context Method Finder always finds a best context method. The first Context Method Finder step that consists in finding all the methods considered as equivalent 3 is illustrated in Figure 7.4. It is the most complicated because it first consists Find Equivalent Context Methods Set highest priority found to - NO YES Context methods remaining Next context method is candidate NO YES Set highest priority found to current priority Highest Current priority < Highest Equivalent C.M. found C.M. has local context NO Already found C.M. with local context YES YES NO Set found C.M. with local context Add context method Figure 7.4: Find equivalent context methods flow chart in going through all the given context methods and find the first candidate. When the first 3

112 CHAPTER 7. CONTEXT METHOD FINDER 102 candidate context method is found, its priority is considered as the highest candidate priority that can be possibly found in this array. This is due to the fact that the array of context method is supposed to be ordered by priority and local context presence. In other words, the algorithm stops when another priority is found, that is, when it goes in the next priority group of context method in the array (see Figure 7.3). For each context method with the same highest priority, the Context Method Finder checks the presence of a local context. If at least one context method with a local context is found, then it stops as soon as a context method with no related local context is encountered. If more than one context method is found in the first step, then the Context Method Finder must check the lowest context activation age for all the context methods found as illustrated in Figure 7.5. This step simply goes through all the list to find the context methods with the Find C.M. with Highest Precedence Context method with highest precedence found NO Set min age found to + Context methods remaining YES Find min age in context method's related contexts NO current age < min found YES Set min age found to current age Figure 7.5: Find context methods with the highest precedence flow chart related context with the lowest activation age. Again, several context methods may have the same lowest related context activation age. But according to the flow chart in Figure 7.5, the Context Method Finder only returns the first method encountered with this lowest activation age. The next section defines the algorithms based on the flow charts illustrated in the current section Algorithm Definition The algorithms defined in this section strictly follow the flow charts introduced in the previous section. Algorithm 2 defines the algorithm for finding the best context method. As expected, it uses two external algorithms as illustrated in Figure 7.2. The first algorithm finds the context methods considered as equivalent in the input array. Equivalent here mean that for all these methods m 1, the relation o = holds between each of them and the relation m 1 o > m2 holds for all the other context methods m 2. This algorithm is defined in Algorithm 3 and is an application of the flow chart illustrated in Figure 7.4. The complexity of this algorithm is O(n.m) were n is

113 CHAPTER 7. CONTEXT METHOD FINDER 103 Algorithm 2: Subjective-C 2.0 find best context method algorithm O(n.m) Input: An array ms of context methods related to the same original method, ordered by ascending priority and scope. Output: The first best context method encountered. equivalentmethods equivalent methods in ms if size of equivalentmethods > 1 then return the first method with the highest precedence in equivalentmethods end if return the single element in equivalentmethods Algorithm 3: Find equivalent context methods algorithm O(n.m) Input: An array ms of context methods related to the same original method, ordered by ascending priority and scope. Output: An array containing all the methods from ms for which the relation o = holds between each of them and the relation o > holds with the other context methods in ms. equivalentmethods new Array highestpriority localcontextfound NO for all m in ms do if m is a candidate then if priority of m highestpriority then highestpriority priority of m {The highest priority has been found else return equivalentmethods {A lower priority has been found end if if m has a related local context then localcontexfound Y ES else if localcontextfound = Y ES then return equivalentmethods {Leaving local contexts subgroup end if add m to equivalentmethods end if end for return equivalentmethods the number of context methods in the input array and m is the number of related contexts per context method. The second algorithm used in Algorithm 2 finds the context method with the highest precedence if more than one equivalent method were found. It is shown in Algorithm 4. This algorithm is an application of the flow chart illustrated in Figure 7.5. Only one context method is retrieved even if several method share the same lowest related context activation age. The complexity of this algorithm is O(n.m) were n is the number of context methods in the input array and m is the number of related contexts per context method. Given that both external algorithms complexity is O(n.m), the complexity for finding the best context method is O(n.m).

114 CHAPTER 7. CONTEXT METHOD FINDER 104 Algorithm 4: Find context method with highest precedence algorithm O(n.m) Input: An array ms of equivalent context methods related to the same original method, ordered by ascending priority and scope. Output: The first context method the highest precedence encountered. bestcontextmethod nil lowestactivationage + for all m in ms do currentlowestactivationage lowest activation age in m related contexts if currentlowestactivationage < lowestactivationage then lowestactivationage currentlowestactivationage bestcontextmethod m {Method with lowest related activation age so far end if end for return bestcontextmethod Finding the best context method is the algorithm that is the most used in Subjective-C. The next section defines the algorithm for finding the next context method. This algorithm takes advantage of the algorithm used for finding the best context method as introduced in this section Find Next Context Method The previous section defines the algorithm for finding the best context method. This section defines the algorithm used by the resend mechanism for finding the next context method. This algorithm uses the algorithm for finding the best context method in an array of context methods after removing the methods present in the current resent calls history (see Chapter 6) Flow Chart Figure 7.6 illustrates the algorithm for finding the next context method. As expected, the first Find Next Method Prune resent methods Find best context method Next context method found Figure 7.6: Find next context method flow chart step consists in removing all the methods present in the current resend calls history from the input array of context methods. Once this step is done, the algorithm simply finds the best context method in the remaining context methods in the input array. This algorithm is very similar to finding the best context method except that it is necessary to prune away the resent methods from the input array. Because the previous sections already

115 CHAPTER 7. CONTEXT METHOD FINDER 105 define the algorithm for finding the best context method, defining the one for finding the next is very straightforward Algorithm Definition This section defines the algorithm as a strict application of the flow chart illustrated in Figure 7.6. Algorithm 5: Find next context method algorithm O(n.m) Input: An array ms of context methods related to the same original method, ordered by ascending priority and scope. Input: A set resent representing the current resend calls history. Output: The first next context method encountered. prunedmethods ms remove every method in resent from prunedmethods return f indbestcontextmethod(prunedmethods) Finding the best or the next context method in Subjective-C 2.0 is more complex than in Subjective-C 1.0 because several additional properties such as the presence of related local context and the lowest related context activation age must be taken in account. The next section discusses the impact of these two algorithms on the global performance of a Subjective-C 2.0 program. 7.3 Discussion Several benchmarks have been realized to measure the performance of the Context Method Finder for finding a best or a next context method. Section makes a comparison between a global context and a local context for the time needed for retrieving their respective activation age. Section measures the time spent for a context method to know if it is a candidate. Section presents a benchmark that measures the time spent for finding a best context method. Eventually, Section measures the time spent for finding a next context method. The two first benchmarks have been carried out because they measure two important parameters in the algorithms for finding a best or a next context method. These benchmarks have been performed with Xcode Instruments Time Spent for Retrieving the Activation Age of a Context This first benchmark compares the global context and local context time needed for retrieving their respective activation age. Figure 7.7 illustrates the results of this benchmark. This shows that the time needed for retrieving the activation age of a local context is 69 times superior to the time needed for a global context. This is because a local context needs to retrieve a the value in a dictionary and convert this value from an object (NSNumber) to a primitive (unsigned long long).

116 Global Global Local Time 0,0007 0,0468 Local CHAPTER 7. CONTEXT METHOD FINDER Time (ms) 0,05 0,045 0,04 0,035 0,03 0,025 0,02 0,015 0,01 0,005 0 Global Activation age Local Figure 7.7: Time spent for retrieving the activation age of a context # contexts Global Global Increase % Local Local Increase % Time Spent for Knowing if a Context Method is a Candidate 4 5 9,8 0, ,7 0, ,2 0,244 0, ,3 0,646 0, ,1 0,302 0, ,8 1,096 0, ,7 0,374 0, ,5 1,49 0, ,6 0,432 0, ,1 1,842 0, The second benchmark aims to analyze the impact of a related local context for finding if a method is a candidate for its respective original method. The results are shown in Figure 7.8. It Context method candidate check Time (ns) 2 1,778 1,556 1,333 1,111 0,889 0,667 0,444 0, Global Global Local Time 0,0007 0,0468 Local Figure 7.8: Time spent for know if a context method is a candidate is not surprising to observe that the presence of a related local context implies more time spent Activation age for performing this task. This is quite logical given that the time needed for accessing a local 0,05 context activation count is bigger than for a global context. What is interesting to get out of 0,045 this observation is that 0,04adding global contexts has few impact on the time spent for performing the task compared0,035 to the impact of adding local contexts. This means that in the case of local contexts, most of the 0,03 time is spent for finding if each context is active. Time (ms) 0, Time Spent 0,02for Finding the Best Context Method 0,015 The objective of the0,01 third benchmark is to measure the time spent for finding a best context method. This is an0,005 important benchmark because this task is the one that is the most performed in Subjective-C. In this 0 benchmark, the number of context methods in the array given to the algorithm increases from 1 toglobal 6. The 5 first context methods Local have related global contexts only (one context per method). The 6th context method has one related local context. All the related context are active and the relation = o exists between each of the 5 first context methods. Time (ms) Time (ms) Time (ms) # C (loca 0,007 0,006 0,006 0,005 0,004 0,004 0,003 0,002 0,001 0, Histo ,014 0,014 0,013 0,013 0,012 0,012 0,012 0,011 0,011 0,01 0,01

117 Local Increase % 7 0, ,646 0, ,096 0, ,49 0, ,842 0, # C.M. Time (ms) CHAPTER 7. CONTEXT 3 METHOD 0,00348 FINDER 34, , ,3 0, ,5 0, ,0 0, ,1 The results of this experience 6 (local) are illustrated 0,00674 in Figure 67,47.9. This graph shows that the difference Find best context method Time (ms) 0,007 0,006 0,006 0,005 0,004 0,004 0,003 0,002 0,001 0, (local) History size ,013 0,012 0,01 Number of context methods Time (ms) 0, ,7 0, ,2 0, ,2 0, ,5 0, ,4 0, ,8 between the two first tests is about 59% and the difference between the second and the third is about 26%. This is due to the fact that when there is only one context method, the algorithm does not need to take a look a the lowest related context activation age. Because the relation o = exists between each context Find method next context and because method each (5 context method methods) is a candidate, adding a second context method 0,014 implies that the Context Method Finder must compare the related context activation 0,014 ages. Time (ms) Figure 7.9: Time spent for finding the best context method The second thing to observe is that the increase between the third and the fourth step is about 0,013 18% and the increase between the fourth and the fifth step is about 12%. This means that the 0,012 time spent is not linear. Adding more and more active context methods has less and less impact 0,012 on the time spent for finding the best context method. Eventually, the sixth 0,011 step, that is, the one where a context method with a related local context is added, shows an increase of 46%. This shows one more time how the time for accessing local 0,011 context information0,01 is superior to the time for accessing information about a global context Time Spent for Finding the Next Context Method Size of resend calls history This last benchmark measures the impact of the variation of the size of the resend calls history on the time spent for finding a next context method. This benchmark has been realized with five context methods equivalent to the ones used in the previous benchmark. Figure 7.10 shows the results of this experiment. This graph shows that the processing of the current resend calls history implies an increase of time of 18% on the total time. The variation of the size of the history implies an increase of time between 1% and 5%. 7.4 Conclusion All the benchmarks presented through the previous chapters and the current one tend to demonstrate that the use of several local contexts implies a severe loss of performance. Fortunately, local contexts tend to be less used than global contexts, therefore the impact on performances should not be that noticeable.

118 History size Time (ms) 0, ,7 0, ,2 0, ,2 0, ,5 0, ,4 0, ,8 CHAPTER 7. CONTEXT METHOD FINDER 108 Time (ms) 0,014 0,014 0,013 0,013 0,012 0,012 0,012 0,011 0,011 0,01 0,01 Find next context method (5 context methods) Size of resend calls history Figure 7.10: Time spent for finding the next context method Furthermore, usually, most of a software lifetime is not spent in context methods but rather in global methods. Therefore, the possible loss on performances is most of the time worth the gain of readability, maintainability and extensibility 4 in the source code. Part III of the dissertation compares the performance between COP and the non-cop version of the Triangles app. This app overuses local contexts to show their limits. A comparison between each application is also made to measure the impact on performance, readability, maintenance and extensibility. Next chapter explains the job of the Subjective-C Parser and how are Subjective-C 2.0 keywords translated into plain Objective-C. 4 Third-party sources are only concerned by extensibility because they can neither be read nor maintained.

119 Chapter 8 Subjective-C Parser Contents 8.1 Keyword Translations Keywords EBNF Grammar Translation Phase Parser State Machine Whole File Translation Example Conclusion The power of Subjective-C 2.0 resides in the use of keywords introduced in Chapter 3. These keywords allow to use Subjective-C in a very simple way. However, because they are not part of standard Objective-C, the Subjective-C files must be translated into plain Objective-C. This chapter describes the translation and the impact of each of these keywords. Section 8.1 explains in detail the translation of every Subjective-C 2.0 keyword. Section 8.2 presents the Subjective-C 2.0 EBNF grammar. The new translation phase is explained in Section 8.3. Section 8.4 presents the Subjective-C 2.0 Parser state machines. Eventually, Section 8.5 shows the result of the translation of a whole Subjective-C file. 8.1 Keyword Subjective-C 2.0 Parser s behavior for this keyword is the same as Subjective- C 1.0 parser s behavior with the #context preprocessor directive. It mainly memorizes each context name provided and tags the context method names to make them unique and contextlike. See Section for further Subjective-C 2.0 Parser s behavior for this keyword is the same as Subjective- C 1.0 parser s behavior with the #priority preprocessor directive. It stores the priority for this context method and writes it in the generated contexts initialization file. See Section for further This keyword is translated into a call to the SCContextManager singleton for activating the contexts provided as keyword parameters. There is one separate context ativation for each context name provided. The Pause) will create the Objective-C code shown in Snippet

120 CHAPTER 8. SUBJECTIVE-C PARSER 110 Snippet 8.1: Translation keyword [[ SCContextManager sharedcontextmanager ] activatecontextwithname :@" Dashed "]; [[ SCContextManager sharedcontextmanager ] activatecontextwithname :@" Pause "]; The in thread1, Down in thread2), used for thread-local activations, will be translated into the code shown in Snippet 8.2. Snippet 8.2: Translation keyword in thread-local activation [[ SCContextManager sharedcontextmanager ] activatecontextwithname :@" Up" forthread : thread1 ]; [[ SCContextManager sharedcontextmanager ] activatecontextwithname :@" Down " forthread : thread2 The translation of this keyword follows the same logic as keyword, except that the Context Manager will be asked for context deactivations. The Pause) will produce the Objective-C code shown in Snippet 8.3. Snippet 8.3: Translation keyword [[ SCContextManager sharedcontextmanager ] deactivatecontextwithname :@" Dashed "]; [[ SCContextManager sharedcontextmanager ] deactivatecontextwithname :@" Pause "]; The in thread1, Down in thread2), used for thread-local deactivations, will be translated into the code shown in Snippet 8.4. Snippet 8.4: Translation keyword in thread-local deactivation [[ SCContextManager sharedcontextmanager ] deactivatecontextwithname :@" Up" forthread : thread1 ]; [[ SCContextManager sharedcontextmanager ] deactivatecontextwithname :@" Down " forthread : thread2 This keyword is translated in a very straightforward way by making a call to the Context Manager. The will be translated into the code shown in Snippet 8.5. Snippet 8.5: Translation keyword [[ SCContextManager sharedcontextmanager ] contextwithname :@" Resend translation takes advantage of Objective-C blocks introduced by Apple in The content of the block will vary depending on the return type of the method. In other 1 In other languages and environments, a block object is sometimes also called a closure. See Apple Blocks Programming Topics for further details.

121 CHAPTER 8. SUBJECTIVE-C PARSER 111 words, if a context method does return a value, then the block will store the value of the resent method and then return it. Otherwise, the block simply resends the method. For instance, given that a current method named amethodwithparam:anotherparam: has a int return type, the following expression would be translated into the code shown in Snippet 8.6. int value param2); Snippet 8.6: Translation keyword with a return value int value = ^{ int SCReturnValue ; [ self resendselector : SCOriginalSelector withcontextselector : SCContextSelector returnvalue :&( SCReturnValue ), param1, param2 ]; return SCReturnValue ; () ; SCOriginalSelector and SCContextSelector constants are automatically generated by the parser for every context method. The former variable is the selector of the original method corresponding to the current context method. The latter variable is the selector of the current context method. If a context method does not return a value, then the following expression translation is shown in Snippet param2); Snippet 8.7: Translation keyword with no return value ^{ [ self resendselector : SCOriginalSelector withcontextselector : SCContextSelector returnvalue : NULL, param1, param2 ]; () ; Finally, an empty resend call translation for methods taking no arguments is shown in Snippet 8.8. For a method taking arguments, say two arguments param1 and param2, Snippet 8.8: Translation keyword without parameters ^{ [ self resendselector : SCOriginalSelector withcontextselector : SCContextSelector returnvalue : NULL ]; () ; the empty resend call parameters will be filled automatically and the translation will be similar to Snippet 8.6 or Snippet 8.7.

122 CHAPTER 8. SUBJECTIVE-C PARSER 112 The main advantage of using blocks as translation tool is that they can be used anywhere in the code like any function call. Details about the resend API are given in Chapter Keywords EBNF Grammar This section is about the EBNF grammar of Subjective-C 2.0 keywords. In this grammar, it is assumed that <string> is a chain made of alphanumeric characters and <objcexpr> is a valid Objective-C expression, that is, an expression that is accepted by an Objective-C compiler. Subjective-C 2.0 keywords EBNF grammar (* Activation event *) < activationevent > = activate " deactivate ") "(" < activationparam > ("," < activationparam >)* ")" ; < activationparam > = < string > [" in" < string >] ; (* Context method contexts *) < contextsdecl > = " (["!"] < string >)+ ; (* Retrieving a context *) <contextdecl > = " "(" <string > ")" ; (* Context method priority *) < prioritydecl > = " <number > ; (* Resend call *) <resendcall > = " "(" [< objcexpr > ("," <objcexpr >) *] ")" ; 8.3 Translation Phase The Subjective-C 2.0 compilation process is fairly similar to Subjective-C 1.0 except that Subjective-C 2.0 files are parsed concurrently. One thread is created per Subjective-C file to parse, as illustrated in Figure 8.1. Grand Central Dispatch (GCD) technology [App10b] has been used to achieve this task in a simple manner. GCD allows to simply create a set of concurrent tasks. This technology takes care of creating an appropriate number of concurrent threads for the amount of tasks provided. Note that, contrary to Subjective-C 1.0 Parser, all Subjective-C files are provided to the Subjective-C 2.0 Parser at once. The ECDL file translation process is unchanged compared to Subjective-C Parser State Machine The parser has been rewritten for supporting Subjective-C 2.0 keywords support on the one hand, and for easily adding additional features in the future on the other hand. The Subjective- C 2.0 parser is now entirely based on the State pattern [GHJV94] which makes it more readable and maintainable. The parser implementation follows the state machines described in Figures 8.2, 8.3, 8.4, 8.5, 8.6 and 8.7. For ease of reading, a Subjective-C 2.0 source file example is used to accompany the explanation of state machines. The content of this file is shown in Snippet 8.9. The translation of this file is shown in the next section.

123 CHAPTER 8. SUBJECTIVE-C PARSER 113 Subjective-C file Parsing thread Objective-C file Subjective-C file Parsing thread Objective-C file Subjective-C file Subjective-C parser Objective-C file Objective-C compiler Subjective-C file Parsing thread Objective-C file Generated file ECDL file ECDL file parser Figure 8.1: Subjective-C 2.0 parser compilation phase Figure 8.2 represents the general state machine, that is, the one with main parser states. The other ones represent the specific states, that is, the internals of states with dashed borders in the general state machine. These state machines are provided for helping the person that will modify the parser in the future. @deactivate Context activation event ) [previous state = class In class Context method EOF + Method body { Method header ) [previous state = method body] Figure 8.2: Subjective-C 2.0 parser general state machine

124 CHAPTER 8. SUBJECTIVE-C PARSER 114 Snippet 8.9: Whole Subjective-C 2.0 file example implementation Triangle 3 // Default method - ( void ) move 5 { // Move triangle 7 //... contexts Logging 11 - ( void ) move { 13 // Log triangle move //... (); contexts Pause priority ( void ) move 21 { // Do nothing 23 contexts Up - ( void ) reverse 27 ( Down ); ( void ) orientationchangedtoup :( NSNotification *) notification { 33 // Change triangle points coordinates ( to UP) // ( void ) registerfornotifications { 39 [[ NSNotificationCenter defaultcenter ] addobserver : self 41 selector selector ( orientationchangedtoup :) name : SCLocalContextDidActivate 43 object (Up)]; The occurrence of the Objective-C is a starting point for the general state machine illustrated in Figure 8.2. The meaning of this keyword is that the implementation of a class starts at this point. This corresponds to line 1 in the example. If the parser finds the (line 10), it means that a context method declaration is following. The state machine corresponding to the processing of a list of contexts is illustrated in Figure 8.3. The optional priority of a context method is processed when the occurs (line 19). The header of a context method (line 20) is processed in a state

125 CHAPTER 8. SUBJECTIVE-C PARSER 115 machine illustrated in Figure 8.4. The body of a context method (lines 21 23) is processed in a state machine illustrated in Figure 8.5. If the (line 28) occurs, the parser changes its state for processing a context activation event. The corresponding state machine is illustrated in Figure 8.6. When the parser finds the (line 43), it expects a context request (i.e. retrieving a context from its name). The corresponding state machine is illustrated in Figure 8.7. Note that this general state machine does not explicitly process regular method implementations. Therefore, a context request or a context activation event that occurs outside of a method implementation will be successfully parsed. Nevertheless, the Objective-C compiler will report an error. The state machine illustrated in Figure 8.3 handles the contexts declared for a context method (lines 10, 18 and 25). This state machine simply parses the context names one by one until contextname Inside + - Figure 8.3: Subjective-C 2.0 parser contexts declaration state machine either the occurs (line 19) or the sign of the method occurs. Figure 8.4 shows the state machine describing the parsing of an Objective-C method header. The Subjective-C Parser actually only analyzes context method headers (lines 11, 20 and 26). Sign + - Return type Parameter name { ) ) Name part : Parameter type Figure 8.4: Subjective-C 2.0 parser context method header state machine This state machine collects the information about a context method such as its corresponding original method selector and the name of its parameters. It is also this state machine that defines whether a context method is an instance method. The state machine illustrated in Figure 8.5 parses a context method body (lines 12 16, and 27 29). It handles the (line (line These keywords are delegated to their corresponding state machines. This state machine ends when the last closing brace occurs. The state machine illustrated in Figure 8.6 handles context activation events (line 28). This

126 CHAPTER 8. SUBJECTIVE-C PARSER 116 regular Resend Inside method @context [last closing brace] Figure 8.5: Subjective-C 2.0 parser context method body state machine Keyword contextname ( ) Inside, Context activation, Thread threadref in Waiting thread ) Figure 8.6: Subjective-C 2.0 parser context activation event state machine state machine is used when either the (line 28) occurs. It parses the context names separated by a comma. An external context activation event is characterized by the presence of the word in. The state machines ends when a closing parenthesis occurs. Figure 8.7 shows the state machine used for parsing a request for a context with the (line 43). This state machine is very simple as it expects to find one context name Keyword contextname ( ) Inside Context request surrounded by parenthesizes. Figure 8.7: Subjective-C 2.0 parser context access state machine This section clearly shows that the current implementation of the Subjective-C parser is not perfect. It does not handle well syntax errors or keywords used in wrong places. The current version of the parser only ensures that a Subjective-C 2.0 program will be successfully parsed if it is well written (i.e. no syntax errors or wrong use of keywords).

127 CHAPTER 8. SUBJECTIVE-C PARSER Whole File Translation Example To summarize Subjective-C 2.0 Parser s capabilities, Snippet 8.10 shows the translation of the source code example used in the previous section (Snippet 8.9). Snippet 8.10: Whole Subjective-C 2.0 file example translated in implementation Triangle // Default method - ( void ) move { // Move triangle //... - ( void ) Context_ Logging_ move { const SEL SCOriginalSelector = ( SEL )" move "; const SEL SCContextSelector = ( SEL )" Context_ Logging_ move "; // Log triangle move //... ^{ [ self resendselector : SCOriginalSelector withcontextselector : SCContextSelector returnvalue : NULL ]; () ; - ( void ) Context_Pause_move { const SEL SCOriginalSelector = ( SEL )" move "; const SEL SCContextSelector = ( SEL )" Context_ Pause_ move "; // Do nothing - ( void ) Context_Up_reverse { const SEL SCOriginalSelector = ( SEL )" reverse "; const SEL SCContextSelector = ( SEL )" Context_ Up_ reverse "; [[ SCContextManager sharedcontextmanager ] activatecontextwithname :@" Down "]; - ( void ) orientationchangedtoup :( NSNotification *) notification { // Change triangle points coordinates ( to UP) //... - ( void ) registerfornotifications { [[ NSNotificationCenter defaultcenter ] addobserver : self selector selector ( orientationchangedtoup :) name : SCLocalContextDidActivate object :[[ SCContextManager sharedcontextmanager ] contextwithname

128 CHAPTER 8. SUBJECTIVE-C PARSER Conclusion Subjective-C 2.0 improves Subjective-C 1.0 at several levels. First, it makes it possible to use it in a multi-threaded application by replacing the supercontext mechanism with the resend mechanism. Then, Subjective-C 2.0 introduces the concept of local contexts which allows to have contexts which state depends on the currently active thread. These local contexts allow to define dynamic behavioral variations in a thread-local scope. Finally, it adds a layer of simple keywords that simplifies the use of Subjective-C. These new keywords implied to write a new Subjective-C Parser as presented in this chapter. This part of the dissertation has presented in details all the concepts and mechanisms that exist in Subjective-C 2.0. The next part makes a comparison between two programs making the same job. The first program is written in Objective-C and the second in Subjective-C 2.0. A comparison is made between the readability, the maintenance, the extensibility and the performance of each program.

129 Part III Validation 119

130 Chapter 9 Case Study Implementation Contents 9.1 Entity-relationship Diagram Triangle Entity Moving a Triangle Checking if a Triangle is Out of Bounds Reversing a Triangle Controller Entity Changing a Triangle Orientation Pausing Triangles Toggling Dashed Lines Logging Triangle Moves View Entity Drawing Dashed Lines Conclusion A case study has been developed for measuring several aspects of Subjective-C 2.0: Efficiency: This measures whether Subjective-C takes more or less time to execute than plain Objective-C. Readability: is Subjective-C source code more or less readable than source code in plain Objective-C? Even though this argument is somewhat subjective, the measures are based on general good practices and principles. Reusability: is Subjective-C source code more or less reusable than source code in plain Objective-C? Does it provide a better separation of concerns? Maintainability: is Subjective-C source code more or less maintainable than source code in plain Objective-C? Extensibility: is Subjective-C source code more or less easily extensible than source code in plain Objective-C? In other words, it measures if it is easier to add functionalities to an application with Subjective-C. The case study is an application called Triangle and developed for running on ios. It is made of triangles moving in several directions (up, down, left or right) and with their own color depending on their orientation. The game can be paused at any moment. A triangle can be 120

131 CHAPTER 9. CASE STUDY IMPLEMENTATION 121 selected and its orientation can be modified by touching an orientation button. The moves of the selected triangle can also be logged by touching a log button. Eventually, the user can activate a mode in which all triangles are drawn with dashed lines. Further details are given in the preface of this dissertation (page vii). An equivalent version of the test case has been developed in Objective-C, additionally to the one developed in Subjective-C. A comparison is made between both versions along this chapter. Section 9.1 presents the entities used in the case study. Section 9.2 presents the parts of the case study that are about moving the triangles. Section 9.3 explains how the case study handles the external events. Eventually, Section 9.4 explains how the view prepares the graphical context for drawing the triangles. 9.1 Entity-relationship Diagram The entity-relationship diagram of the Triangle app is very simple, as illustrated in Figure 9.1. Triangle * * triangles 1 TrianglesView controller triangles view TrianglesViewController 1 Figure 9.1: Triangles app entities It is composed of three entities: Triangle: Represents a triangle with an orientation. It is in charge of moving a triangle and reversing it when this triangle is out of bounds. TrianglesView: Represents the view that draws the moving triangles. TrianglesViewController: Represents the controller that handles events for: Adding a triangle. Selecting a triangle. Changing the orientation of the selected triangle. Pausing the game. Toggling the dashed lines for drawing triangles. Toggling the logging of the selected triangle moves. These entities respect the Model-View-Controller (MVC) pattern. Each triangle is moving within its own thread. When the controller creates a triangle, it also creates a thread for that triangle. A triangle becomes out of bounds as soon as one of its vertex coordinates are out of the bounds of the view. When this occurs, the triangle reverses its orientation. The next sections present the source code of the most important part of the Triangle app. Each section shows how the Objective-C code of the concerned part can be refactored into Subjective-C 2.0 code.

132 CHAPTER 9. CASE STUDY IMPLEMENTATION Triangle Entity This entity is in charge of moving a triangle and reversing it when this triangle is out of bounds. Section presents the code used for moving a triangle. Section presents the code used for checking if a triangle is out of bounds. Eventually, Section presents the code used for reversing a triangle Moving a Triangle Objective-C Version Snippet 9.1 presents the Objective-C code of the method move in charge of moving a triangle. The methods starts by logging the move a triangle. This logging method verifies if the log- Snippet 9.1: Moving a triangle in Objective-C - ( void ) logmessage :( NSString *) message { if ( loggingenabled ) { NSLog (@" LOG : %@", message ); - ( void ) move ( self ) { [ self logmessage :[ NSString stringwithformat :@" Moving from %@", self ]]; movepoint (&a, xoffset, yoffset ); movepoint (&b, xoffset, yoffset ); movepoint (&c, xoffset, yoffset ); movepoint (& center, xoffset, yoffset ); if ([ self isoutofbounds ]) { [ self reverse ]; ging mode is activated and shows the log message if the log is active for this triangle. After that, each point of the triangle is modified with the variables xoffset and yoffset. These two variables are pre-calculated every time the triangle changes its orientation. The function movepoint moves a point accordingly to the offsets passed as function s parameters. Eventually, the triangle is reversed if it crossed the bounds of the view Subjective-C Refactoring Refactoring the code shown in Snippet 9.1 requires to focus on the main goal of the method, that is, moving the triangle, as shown in Snippet 9.2. The default method simply moves the triangle and checks if it became out of bounds. The second refactoring step consists in creating one context-specific variation for logging the moves of the triangle. This context method logs the move of the triangle and then makes a resend call to invoke the default method. Another context method must be added in case of

133 CHAPTER 9. CASE STUDY IMPLEMENTATION 123 Snippet 9.2: Moving a triangle in Subjective-C (basic methods) - ( void ) move { movepoint (&a, xoffset, yoffset ); movepoint (&b, xoffset, yoffset ); movepoint (&c, xoffset, yoffset ); movepoint (& center, xoffset, yoffset ); if ([ self isoutofbounds ]) { [ self reverse ]; the game is paused. Snippet 9.3 shows the code of these two additional context methods. The Snippet 9.3: Moving a triangle in Subjective-C (additional contexts Logging - ( void ) move { [ self logmessage :[ NSString stringwithformat :@" Moving from %@", self contexts priority ( void ) move { // Do nothing logging version needs to be executed before the default implementation. This is ensured thanks to the fact that a context method defined for a local context (Logging here) takes precedence over other context methods defined for global contexts and with a priority that is superior or equals. On the other side, the context method defined for the context Pause must be executed before the other context methods so that nothing happens when the game is paused. This is ensured thank to the higher context method priority Comparison The following table makes a comparison between the Objective-C and the Subjective-C version. Efficiency Readability Reusability Maintainability Extensibility = Subjective-C is better than Objective-C = Subjective-C and Objective-C are equivalent Objective-C is better than Subjective-C

134 CHAPTER 9. CASE STUDY IMPLEMENTATION 124 Efficiency The Objective-C version is more efficient than the Subjective-C version. This is mainly due to the fact that the logging context-specific variation of the original method move is defined for a local context. See Section and Section for further details about locally dispatched methods 1. Another reason is that the call to the method isoutofbounds is more costly in Subjective-C version, as explained in next section. Readability The Objective-C version provides readable implementation of the method. This version contains the logging part and the moving part at the same time. The Subjective-C version divides the method move into several behavioral variations which might confuse an unexperienced user. Nevertheless, the separation of concerns makes the code looks clear and straightforward. The Objective-C version did not really need a refactoring with its current implementation but the separation of concerns might help users who like to focus on the main task of a method. Reusability version. Subjective-C version provides a better separation of concerns than Objective-C Maintainability Subjective-C version is more maintainable for several reasons. There is no need for instance variables such as loggingenabled or global variables such as gameispaused. Furthermore, it is easy to modify the different variations of the method because the default implementation focuses on moving the triangle whereas the extensions add optional functionalities. Extensibility Adding or removing context-specific variations related to the method move is much easier with Subjective-C version. For instance, when the development of the app Triangle began, the method move was only defined for the default implementation (i.e. moving the triangle). After that, logging and reversing context methods have been added to extend the software capabilities. It is then easier to add functionalities one by one with Subjective-C Checking if a Triangle is Out of Bounds Objective-C Version Snippet 9.1 presents the Objective-C code of the method isoutofbounds in charge of checking if a triangle is out of bounds. The method checks the triangle vertexes coordinates according Snippet 9.4: Checking if a triangle is out of bounds in Objective-C - ( BOOL ) isoutofbounds { switch ( orientation ) { case UpOrientation : return a. y <= movingbounds. origin. y; case DownOrientation : return a. y >= ( movingbounds. origin. y + movingbounds. size. height ); // Left and Right... 1 When a context method defined for a local context is a candidate, its corresponding original method is locally dispatched.

135 CHAPTER 9. CASE STUDY IMPLEMENTATION 125 to the current orientation of the triangle Subjective-C refactoring Refactoring the Objective-C code presented in the previous section into Subjective-C requires to divide the method into context-specific variations. The result of this refactoring is shows in Snippet 9.5. As expected, there is one context method per possible orientation. Each context Snippet 9.5: Checking if a triangle is out of bounds in contexts Up - ( BOOL ) isoutofbounds { return a. y <= movingbounds. origin. contexts Down - ( BOOL ) isoutofbounds { return a.y >= ( movingbounds. origin.y + movingbounds. size. height ); // Left and Right... method determines if the triangle is out of bounds according to the context for which this method is defined Comparison The following table makes a comparison between the Objective-C and the Subjective-C version. Efficiency Readability Reusability Maintainability Extensibility = + = = Efficiency Again, the Subjective-C is less efficient than the Objective-C version because of the use of local contexts. Readability Both versions are equally readable because this case is very simple. Reusability Again, Subjective-C provides a better separation of concerns. Even though the Objective-C version is only focussed on checking if the triangle is out of bounds, the Subjective-C is more precise by focussing on each orientation. Maintainability Both versions are equally maintainable because this case is very simple. Extensibility Again, because it is a very simple case, extending both versions (e.g. logging when a triangle is out of bounds) are equally simple.

136 CHAPTER 9. CASE STUDY IMPLEMENTATION Reversing a Triangle Objective-C Version Snippet 9.1 presents the Objective-C code of the method reverse in charge of reversing a triangle. This method reverses the triangle s orientation according to its current orientation. For Snippet 9.6: Reversing a triangle in Objective-C - ( void ) reverse { switch ( orientation ) { case UpOrientation : [ self setorientation : DownOrientation ]; break ; case DownOrientation : [ self setorientation : UpOrientation ]; break ; case LeftOrientation : [ self setorientation : RightOrientation ]; break ; case RightOrientation : [ self setorientation : LeftOrientation ]; break ; instance, the triangle would be going up if it was going down at the beginning of this method. The method takes advantage of another method setorientation:. This method consists Snippet 9.7: Changing the orientation properties of a triangle in Objective-C - ( void ) setorientation :( TriangleOrientation ) anorientation ( self ) { static const NSUInteger movingoffset = 4; orientation = anorientation ; switch ( orientation ) { case UpOrientation : // Go Up a = CGPointMake ( center.x, center.y - offset ); b = CGPointMake ( center. x - offset, center. y + offset ); c = CGPointMake ( center. x + offset, center. y + offset ); color = upcolor ; xoffset = 0; yoffset = - movingoffset ; break ; // Down, Right, Left,... in modifying the triangle s vertex coordinates, changing its orientation and then changing its

137 CHAPTER 9. CASE STUDY IMPLEMENTATION 127 color. Finally, this method sets the moving offsets to the appropriate value corresponding to the new orientation. These offsets are used in the method move introduced in Section Subjective-C refactoring Refactoring this method requires to create one context method per orientation context, as shown in Snippet 9.8. Instead of directly calling a method, each reversing context method activates Snippet 9.8: Reversing a triangle in contexts Up - ( void ) reverse ( Down contexts Down - ( void ) reverse (Up); // Do a similar job for Horitonzal contexts... the appropriate orientation context. Actually, each context method takes advantage of the notification that is sent when a context is changed. Snippet 9.9 shows how each triangle registers for orientation context activation notifications. All the job that was made in the method setorientation: is here divided in one separate method per orientation context. Therefore, every time an orientation context is activated, the appropriate callback method is called by the notification center Comparison The following table makes a comparison between the Objective-C and the Subjective-C version. Efficiency Readability Reusability Maintainability Extensibility = + = = Efficiency Again, the Subjective-C is less efficient than the Objective-C version because of the use of local contexts. Readability Reusability Both versions are equally readable because this case is very simple. As usual, there is a better separation of concerns with Subjective-C. Maintainability complicated. Both versions are equally maintainable because both versions are equally Extensibility Again, because it is a very simple case, extending both versions (e.g. logging when a triangle is reverse) are equally simple.

138 CHAPTER 9. CASE STUDY IMPLEMENTATION 128 Snippet 9.9: Reaction to an orientation change in Subjective-C - ( void ) orientationchangedtoup :( NSNotification *) notification { NSDictionary * notificationcontext = [ notification userinfo ]; NSThread * thread = [ notificationcontext objectforkey : SCContextNotificationThread ]; if ( thread == movingthread ) { // Go Up a = CGPointMake ( center.x, center.y - offset ); b = CGPointMake ( center. x - offset, center. y + offset ); c = CGPointMake ( center. x + offset, center. y + offset ); color = upcolor ; xoffset = 0; yoffset = - movingoffset ; // Orientation changed to Down, Right, Left... - ( void ) registerfornotifications { [[ NSNotificationCenter defaultcenter ] addobserver : self selector selector ( orientationchangedtoup :) name : SCLocalContextDidActivate object (Up)]; // Register for Down, Left and Right Controller Entity This entity is in charge of handling events such as adding a triangle, changing its orientation, pausing the game,... Section presents the code used for changing the orientation of a triangle. Section presents the code used for pausing the game. Section shows the code used to activate the logging mode for the selected triangle Changing a Triangle Orientation Objective-C Version Snippet 9.10 presents the Objective-C code of the method updateorientation: in charge of handling events for modifying the orientation of the selected triangle. The method is very simple as it changes the selected triangle orientation according to the button pressed by the user. Note that this method uses the method setorientation: presented in Section Subjective-C refactoring Refactoring this method is less natural than in previous cases, as shown in Snippet Here, the method cannot be divided into four context-methods (one per orientation context) because the method has to verify what button has been touched. Therefore, the general structure of the

139 CHAPTER 9. CASE STUDY IMPLEMENTATION 129 Snippet 9.10: Changing a triangle orientation in Objective-C - ( IBAction ) updateorientation :( id) sender { NSInteger selectedindex = [ orientationcontrol selectedsegmentindex ]; switch ( selectedindex ) { case UpSelected : [ selectedtriangle setorientation : UpOrientation ]; break ; case DownSelected : [ selectedtriangle setorientation : DownOrientation ]; break ; // Right, Left... Snippet 9.11: Changing a triangle orientation in Subjective-C - ( IBAction ) updateorientation :( id) sender { if ( selectedtriangle ) { NSInteger selectedindex = [ orientationcontrol selectedsegmentindex ]; NSThread * movingthread = selectedtriangle. movingthread ; switch ( selectedindex ) { case UpSelected activate ( Up in movingthread ); break ; case DownSelected activate ( Down in movingthread ); break ; // Right, Left... Objective-C version is kept unchanged. Instead of calling the method setorientation:, the Subjective-C version activates the appropriate orientation context with an external activation Comparison The following table makes a comparison between the Objective-C and the Subjective-C version. Efficiency Readability Reusability Maintainability Extensibility = Efficiency The execution time is almost similar for both versions. The Subjective-C version contains an external context activation which delays the modification of orientation (see previous section). The Objective-C version directly modifies the properties of the triangle with the

140 CHAPTER 9. CASE STUDY IMPLEMENTATION 130 new orientation. Nevertheless, the impact of this method on the general performance is more important in the Subjective-C version because the modification of orientation is made in two steps: 1. Create a delayed activation (i.e. adding it to the pending activation queue). 2. Modify the orientation of the triangle the next time a context method defined for this orientation context is called. The Objective-C version simply consist in one step, that is, modifying the orientation of the triangle. Readability, Reusability and Maintainability The Subjective-C version is less readable because of the need to use the variable movingthread. Therefore, the use of this variable makes it conceptually harder to understand this code and therefore also to modify or reuse it. Extensibility Given that the general structure of both methods is the same, both versions are equally extensible Pausing Triangles Objective-C Version Snippet 9.12 presents the Objective-C code of the method pausetriangles: in charge of pausing the game. This method pauses or unpauses the game depending on the value of the Snippet 9.12: Pausing triangles in Objective-C - ( IBAction ) pausetriangles :( id) sender { if ( gamepaused ) { pausebutton. style = UIBarButtonItemStyleBordered ; gamepaused = NO; else { pausebutton. style = UIBarButtonItemStyleDone ; gamepaused = YES ; variable gamepaused. It also changes the style of the pause button Subjective-C refactoring Refactoring this part of code is very straightforward. The method is divided in two separate context methods, as shown in Snippet One of the two versions is called when the context Pause is active. Otherwise, the other context-specific variation is called Comparison The following table makes a comparison between the Objective-C and the Subjective-C version. Efficiency Readability Reusability Maintainability Extensibility + + = =

141 CHAPTER 9. CASE STUDY IMPLEMENTATION 131 Snippet 9.13: Pausing triangles in Pause - ( IBAction ) pausetriangles :( id) sender { pausebutton. style = UIBarButtonItemStyleDone ( Pause contexts Pause - ( IBAction ) pausetriangles :( id) sender { pausebutton. style = UIBarButtonItemStyleBordered ( Pause ); Efficiency Because of the use of a global context, the implementation of the original method pausetriangles: is replaced when the context Pause is activated or deactivated. Therefore, there is no need to test if it is paused or not. Nevertheless, the Objective-C version simply modifies a variable whereas the Subjective-C version activates a global context. Therefore, the Subjective-C version is less efficient. Readability Because there are only two context methods, the Subjective-C version seems more readable. Reusability There is again a better separation of concerns in the Subjective-C. Maintainability Both versions are equally maintainable because this case is very simple. Extensibility Again, because it is a very simple case, extending both versions (e.g. logging when the user pauses the game) is equally simple Toggling Dashed Lines This part of code is very similar to the code presented for the context Pause except that it uses the variable dashedtriangles for the Objective-C version and the context Dashed for the Subjective-C version Logging Triangle Moves Objective-C Version Snippet 9.14 presents the Objective-C code of the method togglelogging: in charge of activating the logging mode for the selected triangle. Very logically, it sets the variable loggingenabled to its opposite value. It also modifies the style of the logging button according to the new value of the variable loggingenabled Subjective-C refactoring Because the context Logging is a local context, the Objective-C version cannot be divided in two separate context methods, as shown in Snippet This is because Logging is a local context and this method performs an external local activation event. As with the Objective- C version, the method checks whether the logging mode is activated by using the keyword

142 CHAPTER 9. CASE STUDY IMPLEMENTATION 132 Snippet 9.14: Logging triangle moves in Objective-C - ( IBAction ) togglelogging :( id) sender { selectedtriangle. loggingenabled =! selectedtriangle. loggingenabled ; if (! selectedtriangle. loggingenabled ) { [ logbutton setstyle : UIBarButtonItemStyleBordered ]; else { [ logbutton setstyle : UIBarButtonItemStyleDone ]; Snippet 9.15: Logging triangle moves in Subjective-C - ( IBAction ) togglelogging :( id) sender { NSThread * movingthread = selectedtriangle. movingthread ; if context ( Logging ) isactiveforthread : movingthread ]) { // Stop log [ logbutton setstyle : UIBarButtonItemStyleBordered deactivate ( Logging in movingthread ); else { // Start log [ logbutton setstyle : UIBarButtonItemStyleDone activate ( Logging in movingthread For activating or deactivating the context Logging, this method uses an external activation so that the effect is local to the thread related to the selected triangle Comparison The following table makes a comparison between the Objective-C and the Subjective-C version. Efficiency Readability Reusability Maintainability Extensibility = This case is very similar to the one introduced in Section Given that the general structure is the same, the observations made for this case are similar to the ones made for the method updateorientation:. 9.4 View Entity This entity is in charge of drawing the triangles on the screen with a color corresponding to their orientation. Triangles are drawn with dashed lines if needed. Section presents the code used for setting up the graphical context with dashed lines.

143 CHAPTER 9. CASE STUDY IMPLEMENTATION Drawing Dashed Lines Objective-C Version Snippet 9.16 presents the Objective-C code of the method setupcontext: in charge of setting up the graphical context. This method sets the width for the lines and the style used for the Snippet 9.16: Drawing dashed lines in Objective-C - ( void ) setupcontext :( CGContextRef ) context { CGContextSetLineWidth ( context, 5.0) ; CGContextSetLineCap ( context, kcglinecapround ); if ( dashedtriangles ) { const CGFloat lengths [] = {5, 10; CGContextSetLineDash ( context, 3, lengths, 2); line borders. If the lines should be dashed, then it sets the graphical context with a dashed line pattern Subjective-C refactoring Refactoring the Objective-C version into Subjective-C requires to create a context method specific to the context Dashed, as shown in Snippet The context method related to the context Snippet 9.17: Drawing dashed lines in Subjective-C - ( void ) setupcontext :( CGContextRef ) context { CGContextSetLineWidth ( context, 5.0) ; CGContextSetLineCap ( context, kcglinecapround contexts Dashed - ( void ) setupcontext :( CGContextRef ) context { const CGFloat lengths [] = {5, 10; CGContextSetLineDash ( context, 3, lengths, (); Dashed sets the graphical context with a line dash pattern and then makes a resend call so that the rest of the setup is performed Comparison The following table makes a comparison between the Objective-C and the Subjective-C version. Efficiency Readability Reusability Maintainability Extensibility + + = =

144 CHAPTER 9. CASE STUDY IMPLEMENTATION 134 Efficiency Even though the Subjective-C version is using a global context, which would imply better performance, the resend call is very costly. Therefore, the Objective-C is more efficient. Readability Because there is only two context methods, the Subjective-C version seems more readable. Reusability The Subjective-C provides a better separation of concerns. Maintainability Both versions are equally maintainable because this case is very simple. Extensibility simple. Again, because it is a very simple case, extending both versions are equally 9.5 Conclusion This section makes a recapitulation of the power of Subjective-C compared to a plain Objective- C program. The following table summarizes this comparison. It is not a simple average of the comparisons made in the previous sections. Rather it adds a general appreciation about Subjective-C usage. Efficiency Readability Reusability Maintainability Extensibility + / + + / + / = Efficiency Subjective-C is clearly not designed for developing applications that need speed. Even though the use of global contexts might provide a certain speedup in some cases, using local contexts always implies a huge slowdown. Nevertheless, even though Triangle overuses local contexts, the impact of local context is normally limited in regular applications (i.e. applications using more global contexts than local contexts). Readability This argument is very subjective. Some people prefer to have all-in-one methods while other people appreciate when things are separated by concern. It is about beliefs. The author of this thesis thinks that dividing things by concerns provides a better readability. The note for this column is + / because the readability of a program in Subjective-C 2.0 is not constant: When a program uses global contexts, the whole readability is improved thanks to context methods that can be defined anywhere in the program. Because a global context has an impact on the whole program, context methods can be defined for this context regardless of being in a part of the code that is executed by a specific thread. On the other side, when a program uses a local context, the context-oriented adaptation of the source code differs depending on whether the part of the code is executed within a thread that is related to the local context. For instance, in the Triangle app, the method isoutofbounds can be easily extended with behavioral variations because this method is always executed within threads that are related to the orientation contexts. But this is not the case for the method updateorientation: which is always executed within an external thread that is not related to any orientation context an therefore needs to make an explicit reference to the thread of the selected triangle. One thing that helps when reading a whole Subjective-C program source code is that each context method is prefixed with its related contexts, which gives a good additional hint about

145 CHAPTER 9. CASE STUDY IMPLEMENTATION 135 what the method is supposed to do or what kind of behavior it adds to its respective original method. Another good point of Subjective-C 2.0 is that its new keywords are made of a simple names and are easy to use. Nevertheless, the concepts of priority and external activation might confuse an unexperienced reader. Reusability As shown in the previous sections, the Subjective-C version does almost always provide a better separation of concerns. Subjective-C also allows to play with the fact that a context state may have an impact on several parts of an application. For instance, in the case study Triangles, activating an orientation context implies that the color of the triangle will change, the triangle orientation will change and that several methods behavior will change. Therefore, it becomes easy to take advantage of some parts of code of the application with a very low coupling. Furthermore, it is easy to reuse other context-specific variations of a same original method thanks to the resend mechanism. Maintainability As for the readability, the maintainability of the Subjective-C version is not constant. The separation of concerns brought by Subjective-C facilitates the maintenance of specific parts of an application. It is easier to localize the parts of code that need to be modified thanks to the contexts for which they are defined. But the parts of code making an explicit reference to a thread become less maintainable by confusing the programmer. Note that the case study could have been developed by using the State pattern which would have probably brought a better maintainability of the Objective-C version of this application. Extensibility Its is easy to add functionalities to a method with Subjective-C by creating new context-specific variations of this original method. These functionalities can be turned on and off by activating or deactivating their corresponding contexts. It is also easy to remove a functionality by simply removing the context method that defines this functionality. Subjective- C also allows to add functionalities to methods for which source code is not available, without inheritance. Nevertheless, the parts of code which are not executed within a thread that is related to a local context are equally extensible to their Objective-C version. To conclude, compared to Objective-C, Subjective-C 2.0 is a big improvement at several level. Besides the fact that this new version of Subjective-C adds the support of local contexts, it provides a COP language that can be safely used with multithreaded applications. Moreover, the high-level syntax of Subjective-C 2.0 simplifies the use of this language and let an unexperienced programmer use the main concepts of Subjective-C very straightforwardly. Nevertheless, this section points out that parts of code dealing with local contexts, and which are supposed to be executed within a thread that is not related to these local contexts, provide a code that is less readable or maintainable than a plain Objective-C solution. This gives a good indication about what should be improved in a next version of Subjective-C. Next part explains several features that could improve Subjective-C on a capability and a performance side.

146 Part IV Conclusion 136

147 Chapter 10 Future Work Contents 10.1 Parameters and Return Types of Locally Dispatched Methods Context Method Finder s Additional Disambiguity Rules Advanced Context-method Ordering Context Ordering Optimizations Cached Search Results Subjective-C Core in Plain C Metaobject Protocol (MOP) Advanced Context Methods Declarations Contextual Blocks Improving the Subjective-C Parser Context Inference Engine Improving the Thread Information Cleaning Process Xcode Integration Conclusion This chapter aims to propose features that could be added to Subjective-C to bring it to another level. These features can be about extending Subjective-C capabilities, improving its efficiency or simplifying the way it must be used Parameters and Return Types of Locally Dispatched Methods As explained in Chapter 4, locally dispatched methods called under ios do not support composite types such as C structures or unions. A solution should remove this limitation with composite type as return values and method parameters under Mac OS X and ios. Ideally, the solution provided should be generic instead of platform dependent Context Method Finder s Additional Disambiguity Rules In its current implementation, the Context Method Finder might find several best context methods extending a same original method, within a same thread. This is because two context 137

148 CHAPTER 10. FUTURE WORK 138 methods extending a same original method can be defined for a same context, as long as these context methods are also defined for other different contexts. The Context Method Finder might therefore have to arbitrarily choose one context method among several. This leads to unpredictable choices of this module. Additional rules should be introduced to help the Context Method Finder to always find one best context method. Here are two possible additional rules: When two candidate context methods are defined for a same active context, the context method defined for the highest number of contexts takes precedence over the other method. When two candidate context methods are defined for the same number of contexts, the youngest context that is not used to define each context method determines what context method takes precedence over the other. These two additional rules allow to always ensure that only one best context method is found by the Context Method Finder Advanced Context-method Ordering Currently, Subjective-C supports one way to statically order context methods thanks to the method priority mechanism. This mechanism tends to be imperfect for two main reasons: It imposes to think about priority numbers that are big enough so that it is possible to add another context method with a priority inferior to the formers. For instance, if a context method m 1 has a priority x, it must be big enough so that a method m 2 can also have a priority y with y < x. It gets more complicated when a third context method m 3 is added with a priority z so that y < z < y. This mechanism is less natural than simply specifying that a context method should always take precedence over other context methods. The mechanism is not flexible enough. For instance, if there are three context methods m 1, m 2 and m 3, it is not possible to have the following scenario: m 1 o > m2 m 2 o > m3 m 3 o > m1 In other words, it is not possible to create a priority between two context methods without affecting other context methods extending the same same original method. A new context method order mechanism should get rid of context method priorities and be more flexible by permitting to create an order between subsets of context methods. This mechanism should allow to redefine the order at runtime Context Ordering One way to create a flexible order between context methods is to create an order between the contexts for which these methods are defined. One might want to create a context method taking priority over all other context methods as soon as the former is bound with a certain context.

149 CHAPTER 10. FUTURE WORK 139 For instance, say there are two context methods m 1 and m 2 extending the same original method. m 1 is defined for a context c and m 2 is not. Therefore, if c takes precedence over all the other contexts then m 1 o > m2. In other words, there should exist a simple mechanism to manually create an order between subsets of contexts. This mechanism should allow to redefine the order at runtime. With this mechanism, it should be possible to create an order between: two contexts a context and a set of contexts a context and all other contexts 10.5 Optimizations Cached Search Results A big issue with Subjective-C is how using local contexts slows things down compared to using global contexts. This is due to the fact that context methods defined for local contexts imply their respective original method to be locally dispatched. Therefore, the Context Method Finder is asked to find the best context method every time this original method is called. There exists the same problem with the resend mechanism that asks the Context Method Finder to find the next context method. The Context Method Finder algorithms could be optimized by using cached data. For instance, between two context activation events, there exists one context method order per thread. This order does not change until the next context activation event (or the next reordering action). The optimization can be made at several levels: A context method keeps its candidate status unchanged between two context activation events. There are two distinct cases: 1. Context methods defined for global contexts represent the easiest case because their candidate status is the same for all the threads. Therefore, it is possible to determine whether this kind of context method is candidate at context activation time. 2. Determining the candidate status of context methods defined for at least one local context is more complicated. To cache their candidate status for a given thread t, the Context Method Finder would have to wait until the first time this candidate status is checked for this thread t 1 (e.g. the first time these context method are called between two context activations). The order in a list of context methods 2 stays unchanged between two context activation events. Keeping this kind of information might require a little more work because, in a same list, some context methods might have a thread-local candidate status (i.e. being a candidate within a subset of threads) while others don t. Therefore, there exists one different order per thread. Again. to cache this order for a given thread t, the Context Method Finder would have to wait until the first time it is asked for finding the best context method for this thread t. 1 The Context Method Finder cannot predict that a context method will be called within a certain thread, but it can assume this method will be called again within the thread in the future and before the next context activation. 2 Context methods extending a same original method are stored in a same ordered list.

150 CHAPTER 10. FUTURE WORK 140 Using cached data could bring a big performance improvement to Subjective-C and would allow to use this language with a larger set of applications. A more in depth study could bring to light the real contribution and impact of such a cache mechanism Subjective-C Core in Plain C The efficiency problem also comes from the fact that Subjective-C core has been designed with object-oriented structures. For instance, a context method is an Objective-C class with an Objective-C set of related contexts. Compared to other languages like C++, calling a method in Objective-C is slow because of its dynamic side. When a method is called in Objective-C (i.e. when a message is sent to an object), a mini dispatcher (the objc msg send function) searches if the target object can handle this method (i.e. if it understands the message). Therefore, calling methods on Objective-C object-oriented data structures implies a significant method dispatching overhead. Currently, when a locally dispatched method is called, the function objc msg send is called dozens of times because of the use of Objective-C data structures for storing the core data. An idea is to rewrite the core of Subjective-C in plain C. The classes would be replaced by C structures and the instance methods would be replaced by C functions. Thus, the core would be fully written in C. Additionally to this core, an object-oriented layer can wrap everything so that the external calls to Subjective-C s API would be in Objective-C, as shown in Figure This is achievable Subjective-C (written in Objective-C) Subjective-C Core (written in C) Figure 10.1: Subjective-C core wrapped with an object-oriented layer because C is a subset of Objective-C Metaobject Protocol (MOP) Many languages provide a reflective API. Reflection can be useful in many cases such as creating generic solutions (e.g. a generic solution for cloning an object), getting information about a running system or creating development tools taking advantage of this reflection API (contextoriented debuggers or profilers for instance). Reflection can also be used for modifying the internal behavior of a system. It is thanks to the Objective-C s reflective API that Subjective-C can work at runtime.

151 CHAPTER 10. FUTURE WORK 141 In Subjective-C, a reflective API should provide access points for retrieving or modifying structural informations such as contexts, context methods,... A set of tools should also be provided for modifying the internal behavior of Subjective-C such as the way best context methods are found or how context methods become candidate. The Subjective-C s introspection 3 API should allow to: Retrieve structural information such as original methods, context methods and contexts. Retrieve behavioral information such as the algorithms used by the Context Method Finder or the strategy used for inferring that a context method is a candidate. The Subjective-C s intercession API should allow to: Adding and modifying structural information introduced in the introspection part. Adding and modifying behavioral information introduced in the introspection part Advanced Context Methods Declarations The current way to declare a context method is very basic. All contexts for which context methods are defined must be active for these methods to become candidate. Most of the time, this strategy works good. Nevertheless, it might happen that a context method should become a candidate when one context among several contexts is active. This is partially achievable with inclusion relations when two contexts share something semantically, but it is too limited. Context-oriented languages like JCop [AHM + 10] provide a way to declare conditional layered instruction blocks by using the boolean logic. In other words, in this kind of language, it is possible to defined an instruction block that will be executed only when the boolean contextual condition defined for this block is true. By reusing this idea, context methods could be declared by using conditional context compositions. The new syntax for declaring context methods should allow to: Make an OR expression between several of contexts Make an AND expression between several of contexts Make an XOR expression between several of contexts The syntax could be inspired from the existing Objective-C syntax (except for the AND) for defining a boolean expression: OR: (A B C) (D E F) XOR: (A B C) ^ (D E F) AND: (A B C) (D E F) The following example shows an advanced context method declaration using such a condition composition mechanism. Advanced context method declaration contexts (( A B) ^ C) D - ( void ) amethod { 3 A reflection API is always made of a two distinct parts: the introspection and the intercession. The introspection part provides a set of tools for retrieving internal information (structural or behavioral) about the system. The intercession part provides a set of tools for modifying internal information about the system.

152 CHAPTER 10. FUTURE WORK This context method would become a candidate in one the following situations: D is active. A and B are active and C is inactive. C is active and A or B is inactive Contextual Blocks It happens that a part of code in a method should only be executed when one or several contexts are active. For instance, in the Triangles app, when the logging button is pressed, Logging is deactivated if it was active. Otherwise it is activated. A new mechanism could permit to wrap a section of code so that this section would only be executed when certain contexts are active or inactive. The syntax of this mechanism could use the for which the different contexts could be declared with the syntax proposed in the previous section about the advanced context method declarations. The following example shows a conditional contextual block that is executed when A or B is active.

153 CHAPTER 10. FUTURE WORK 143 Conditional contextual block example - ( void ) amethod (A B) { // Only executed when A or B is active... Another type of contextual block could temporarily activate or deactivate a given set of contexts during the execution of the block. The syntax of this mechanism could use the The following example shows a context activation block that is executed with Logging begin deactivated. Context activation block example - ( void ) amethod withcontexts (! Logging ) { // Logs nothing inside this block... This last feature is inspired from the way ContextL [CH05] activates several layers during the execution of a layered instruction block Improving the Subjective-C Parser The current version of the Subjective-C Parser is very basic. It works well with Subjective- C 2.0 compliant source code but gives very few information in case of a parsing error. An enhanced version of the parser should bring the following capabilities: Make a strict verification of Subjective-C keywords used. For instance, if a context method is declared with a context A and its opposite (i.e. not A), then this context method could never become a candidate. The Subjective-C Parser should detect this kind of strange declarations. Provide explicit error messages. Error message lines should correspond to the original Subjective-C file lines. This can be achieved by inserting several #line preprocessor directives in the translated files Context Inference Engine Most of external contexts could be inferred thanks to predefined predicates. Ambience [Gon08] suggests an inference engine that is charge of inferring contexts based on incoming data and predefined rules. Such a mechanism avoids the use of most of explicit context activations or deactivations.

154 CHAPTER 10. FUTURE WORK 144 In Subjective-C, context relations are a first step in that direction. Thanks to those relations, contexts can be implicitly activated or deactivated with an activation event propagation. These propagations are performed thanks to the relations defined between these contexts. An inference engine system should be flexible: Rules (or predicates) can be added and removed at runtime. The inference engine must adapt its results to the updated set of rules. Complex rules defining the conditions to a context activation or deactivation can be provided. The representation of these rules must therefore be well chosen. A specific syntax should be provided to define basic rules, externally to the software (e.g. in an external file) Improving the Thread Information Cleaning Process In the current version of Subjective-C, an automatic data cleaning process is launched every time a thread is about to end. Subjective-C does not make a difference between threads about which information is stored and threads about which no information is stored. Furthermore, every context object is asked for cleaning information about an ending thread, even if this context never was activated within this ending thread. An improved cleaning process should bring two enhancements: Filtering the ending threads. Only the threads about which information is stored in the system should be taken in account. Only the context objects which have been manipulated within the ending thread should be asked for cleaning information about this thread. A possibility is to launch a low-priority thread that acts as a garbage collector. This thread would be in charge of verifying whether information about a thread is still relevant. In this case, relevant means that the thread is still running. When the garbage collector detects that a thread has stopped, it removes the information about this thread. Because a garbage collector solution can use some precious processor time, the current cleaning process might be preferred. Therefore, the programmer should have the choice to choose the most appropriate solution Xcode Integration Subjective-C clearly lacks of an IDE integration. On Mac OS X, Xcode is the most used IDE for developing Cocoa-based applications. A good integration of Subjective-C should provide the following features: Create an empty Subjective-C project like a regular project is created with Xcode. Syntax coloring for Subjective-C keywords. A graphical user interface for modifying context relations. The compilation process should not have an impact on the undo/redo manager. For the moment, when a Subjective-C project is compiled, the undo/redo history is cleared because the original files are temporarily moved and replaced with translated files (i.e. during the translation phase).

155 CHAPTER 10. FUTURE WORK 145 No warnings or errors should be displayed while typing with Xcode 4 when the code is Subjective-C compliant Conclusion All the possible additional features presented in this chapter can bring Subjective-C to another level. The ordering features would improve the possibilities provided by Subjective-C for dispatching context methods. The possible optimizations introduced in this chapter would allow to use this context-oriented language with applications that need good global performance. The advanced context method declarations would simplify or gather context methods defined for several contexts. The contextual instruction blocks would introduce a new finer-grained scope for context activation events or activation status. A MOP would provide tools for creating more advanced solutions related to Subjective-C such as generic solutions or development tools. The possible improvements for the Subjective-C Parser and the Xcode integration are an important step from a productivity point of view. The improved thread information cleaning process can speed things up when a thread ends. Finally, the context inference engine would provide a more natural way of dealing with external contexts, that is, with less explicit context activation events.

156 Chapter 11 Discussion This dissertation introduces a lot of notions and mechanisms. Since the beginning of this text, Subjective-C 2.0 is presented as a big improvement over Subjective-C 1.0. This chapter revisits the context in which this thesis was set (Section 11.1), recalls the key aspects of the developed solution (Section 11.2), discusses the advantages and limitations of this solution (Section 11.3) and then sums up what objectives have been achieved through this thesis Thesis Context Subjective-C is the first programming language that brought COP to mobile devices [MGLG10]. The solution provided by Subjective-C 1.0, developed as a superset of Objective-C, allows to easily design Cocoa-based software adapting their behavior to a given set of global contexts. However, Subjective-C 1.0 has not been designed for being used with multi-threaded applications and therefore lacks a notion of contexts that are local to a selected set of threads or to a block of instructions (i.e. local contexts). This excludes adaptation to scenarios such as enabling a logging mode for a specific thread. Subjective-C 1.0 provides a limited specific syntax for using its main context-oriented concepts. These concepts need be used through direct calls to the API of the Subjective-C s library. This results into complicated and hardly readable source code. The third main problem of Subjective-C 1.0 is that it provides a limited and error-prone mechanism for calling the next context method from a source context method. This mechanism, called supercontext, is not thread-safe as it is based on method implementation replacement for preparing the call to a next context method. These and other smaller problems with Subjective-C were supposed to be solved during the course of thesis with a particular focus on adding support for local contexts Key Aspects of the Developed Solution The solution provided by Subjective-C 2.0 to the lack of local context is mainly based on the Objective-C s reflection API. Local contexts in Subjective-C 2.0 are built on a local dispatch system, making dynamic calls to the best context method at method call time. Contextual information relative to threads are stored at separate places and are easily recoverable based on 146

157 CHAPTER 11. DISCUSSION 147 the currently running thread. When a thread ends, a cleaning process is automatically engaged for removing all the information relative to this thread. Subjective-C 2.0 provides a simple new syntax made of one-word context-oriented keywords for performing main operations such as retrieving a context, activating a context or calling the next context method. This is made possible thanks to a rewriting of the Subjective-C Parser program which translates these syntactic keywords into standard calls to the Subjective-C API. The new mechanism developed in Subjective-C 2.0 for calling the next context method is based on the same main principles as for the local dispatch mechanism. It has been renamed resend mechanism. This mechanism manipulates a resend calls history per thread to provide a threadsafe solution. The Context Method Finder algorithms have been improved to take the context activation age in account. This activation age is used to create a total order of contexts. Thread-local contexts have one specific activation age per thread for which it has been activated. This property implies that several activation age timelines can exist in a same application. These solutions resolve the problems enumerated in Section The advantages and limitations of these solution are discussed in the next section Advantages and Limitations of the Developed Solution The local dispatch solution allows to intercept a method call and redirect it to the best context method at the time of the method call. It comes with a certain overhead because it needs to retrieve and compute information about each dispatched method call but this solution allows to transparently dispatch these calls. The Context Method Finder s algorithm in charge of finding the best context methods did not have to be adapted to local contexts because these contexts define the same high level properties as global contexts. Activating, deactivating or checking the state of local contexts works in the same way as for global contexts. This provides a good feeling of coherence of the whole system. The new syntax provided by Subjective-C 2.0 allows to create context-oriented programs with simple and clear source code. This does not introduce new functionalities, that is, every mechanism introduced by Subjective-C 2.0 can be used through the library developed for this language. The purpose of these keywords is rather to simplify the use of Subjective-C. This lets an unexperienced Subjective-C programmer design a context-oriented program without having to know the exact calls to make to the Subjective-C s library. Therefore, these keywords remove lots of the complexity introduced by every concept provided by this new version of Subjective-C. The resend mechanism provides a way to create concurrent resend calls, which was not possible with the supercontext mechanism. This is due to the fact that this new solution is thread safe. It also allows to use it inside cycling method calls. Furthermore, reusing many of the dynamic dispatch s sub-mechanisms makes both mechanisms more maintainable. Even though the Context Method Finder algorithms are slowed down with the new activation age parameter, this new property allows to create more dynamic programs. The context methods are not only statically ordered with their priority anymore. Using the activation age as an algorithm s decision property provides a more natural way to dynamically order context methods.

158 CHAPTER 11. DISCUSSION 148 The case study analysis in Chapter 9 shows that Subjective-C 2.0 provides a solution to design programs that are more maintainable, readable and more easily extensible than equivalent programs written in plain Objective-C. Only the parts dealing with local contexts from an external thread require a less readable and therefore less maintainable source code. The different benchmarks presented in this dissertation show that using local context for defining context methods introduces a certain overhead compared to using global contexts or regular methods Achievement of Objectives The most important contribution of Subjective-C 2.0 compared to Subjective-C 1.0 is that it adds the support of local contexts, in additional to global contexts. Subjective-C 2.0 is therefore a context-oriented language reconciling the use of local and global contexts. An implication of the support of local contexts is the thread safety of Subjective-C 2.0. A multithreaded Objective-C application can now take advantage of Subjective-C s features without risking system inconsistencies. Making Subjective-C thread safe forced to redesign the system used for calling the next context method by introducing the resend mechanism. One objective of this thesis was to delegate a maximum of work to the library instead of to the Subjective-C Parser. The impact of this objective is that all the Subjective-C 2.0 s features can be used by calling the Subjective-C API and without using the Subjective-C Parser. On the other side, an objective was to also simplify the use of Subjective-C and make programs written with Subjective-C more readable and maintainable. This has been achieved thanks to new syntactic keywords introduced in Subjective-C Conclusion Subjective-C 2.0 is a big step forward compared to Subjective-C 1.0 in the sense that it is a complete, thread-safe and yet simple object-oriented and context-oriented language. This new version of Subjective-C provides a way to design multithreaded context-oriented programs with Objective-C. Its main drawback is that the thread-local contexts are not a reliable solution yet for application needing efficiency. Nevertheless, several optimizations made on the algorithms and the design of Subjective-C would bring this language to another level from an efficiency point of view.

159 Part V Appendixes 149

160 Appendix A Subjective-C and Xcode This tutorial chapter is based on Xcode 4. Nevertheless, the following steps have an equivalent in Xcode 3. A.1 Requirements Creation Step by Step System requirements Compiling and running a Subjective-C 2.0 project requires Mac OS X 10.6 (or superior) and ios 4 (or superior). The compiler LLVM 2.0 is used for compiling the Subjective-C s library and the Subjective-C Parser. Using GCC 4.2 (or a previous version) will not work because Subjective-C s implementation uses Objective-C blocks which are not supported by GCC 4.2. Subjective-C Projects The folder Subjective-C contains Subjective-C s Xcode projects. Subjective-C 2.0 is made of 3 distinct Xcode projects located in the following directories: context ios: The sources of Subjective-C runtime system for ios. The project is configured for ios compilation. context Mac: The sources of Subjective-C runtime system for Mac OS X. These are actually a link to the ios project sources. The project is configured for Mac OS X compilation. SubjectiveParser2: The sources of the new Subjective-C Parser. Note that context ios and context Mac must always be in the same parent folder. Otherwise, the context Mac project can t find the original sources. Here are the compilation steps: 1. Compile context ios (for and ios project) or context Mac (for a Mac OS X project) in Release mode 1. The context ios project compilation process produces a static li- 1 This can be changed in Project > Manage Schemes... Select context and click on Edit... button. Select the Run lateral tab and choose Release for Build Configuration. 150

161 APPENDIX A. SUBJECTIVE-C AND XCODE 151 brary libcontext.a. The context Mac project compilation process creates a dynamic library context.dylib 2. Compile PARSEKIT 2 framework in Debug mode. PARSEKIT is located in the Libraries directory of the SubjectiveParser2 directory. 3. Compile SubjectiveParser2 in Debug mode. It creates an executable file SubjectiveParser2. By default with Xcode 4, the compilation products are located in a shared directory 3 (~/ Library/Developer/Xcode/DerivedData/<product>/Build/Products/<platform>). If these default parameters are kept, it is important to link the PARSEKIT build product with the SubjectiveParser2 project 4. Environment Variables Three environment variables must be defined before compiling a Subjective-C 2.0 compliant project: SUBJ LIB: the absolute path to context ios project directory. SUBJ LIB MAC: the absolute path to context Mac project directory. SUBJ PARSER2: the absolute path to SubjectiveParser2 executable file. These variables can be defined in a file located at ~/.MacOSX/environment.plist. This file can be opened with Xcode. In this file, add the following entries: Key Type Value SUBJ LIB String <absolute path to context ios directory> SUBJ LIB MAC String <absolute path to context Mac directory> SUBJ PARSER2 String <absolute path to SubjectiveParser2 executable file> The user session must be restarted after setting up these variables. A.2 Project Creation Step by Step ios Project 1. Open Xcode and create a standard ios project. 2. Add the library libcontext.a to the project. 3. It might be needed to add linker flags. Go in the target properties and click on the Build Settings tab. Type Other Linker Flags in the search field and find the line with the same name. Add these two flags: -ObjC -all load 4. In the same Build Settings tab, type Header Search Paths in the search field and find the line with the same name. Add the following entry: 2 PARSEKIT is a Mac OS X framework written by Todd DITCHENDORF in Objective-C and released under the MIT Open Source License 3 It is possible to modify this behavior in Xcode > Preferences... > Locations > Build Location. Xcode 3 stores compilation products in a subdirectory build of the project directory. 4 A library or a framework can be linked with a project by going in the project properties. Select the target and click on the Build Phases tab. Expand the Link Binary With Libraries box and add the needed library.

162 APPENDIX A. SUBJECTIVE-C AND XCODE 152 $SUBJ_LIB/context 5. Still in the same Build Settings tab, type Library Search Paths in the search field and find the line with the same name. Add the absolute path to the Context ios project build product. If the build product is located in the project directory, the path is the following one: $SUBJ_LIB/build/Release-$PLATFORM_NAME 6. Click on the Build Phases tab: (a) Click on the button Add Build Phase located in the bottom right corner and select Add Run Script. (b) Rename this new phase into Subjective-C Compilation Process. (c) Move the new build phase on top of the phase named Compile Sources. (d) In the phase details, edit the text field with the following line: $SUBJ_LIB/context/SubjcPreCompilation.sh <target name> 0 <target name> is the name of the folder in which the sources of the target are located. The last number in the command line can be changed into 1 to display the Subjective-C Parser logs. 7. In the same Build Phases tab: (a) Click on the button Add Build Phase located in the bottom right corner and select Add Run Script. (b) Rename this new phase into Subjective-C Cleaning Process. (c) Move the new build phase under all the other existing phases. (d) In the phase details, edit the text field with the following line: $SUBJ_LIB/context/SubjcPostCompilation.sh <target name> 0 <target name> is the name of the folder in which the sources of the target are located. The last number in the command line can be changed into 1 to display the Subjective-C Parser logs. 8. Compile the project. A new directory Subjective-C is created inside the directory of the current target. 9. Add the folder Subjective-C to the project. 10. Edit the precompiler header file (the one with the exentesion.pch) and add the following line: #import <SubjectiveC.h> This automatically import Subjective-C for the whole project. 11. Import the context initialization file to the file main.c (or the entry-point file of the project) by adding the following line: #import "ContextsInitializer.h" 12. Initialize the contexts and their relations by adding the following lines in the main function: ContextInitializer *ci = [[ContextInitializer alloc] init]; [ci initializecontexts]; [ci release]; 13. Compile the project again. If the build works, then the project is good to go. Otherwise, review the previous steps. Mac OS X Project 1. Open Xcode and create a standard Mac OS X project. 2. Add the library context.dylib to the project. 3. In the target properties, click on the Build Settings tab. Type Header Search Paths in the search field and find the line with the same name. Add the following entry:

163 APPENDIX A. SUBJECTIVE-C AND XCODE 153 $SUBJ_LIB/context 4. If the library has not been added from usr/local/lib, then, in the same Build Settings tab, type Library Search Paths in the search field and find the line with the same name. Add the absolute path to the Context Mac project build product. If the build product is located in the project directory, the path is the following one: $SUBJ_LIB_MAC/build/Release 5. The following steps are the same as for an ios project (steps 6 13). ECDL file The file located at Subjective-C/ContextDeclaration.sc is the ECDL file that contains the context declarations. It should be empty when a Subjective-C project is created. Contexts and relations can be declared in this file. Compilation error When a Subjective-C 2.0 project s compilation process starts, it copies the original sources into a subfolder <targetdirectory>/subjective-c/originalsources. During the compilation process, the original sources are translated into plain Objective-C and then provided to the Objective-C compiler. After the Objective-C compilation process, the original sources are copied back to their original place. If one of the compilation steps fails, the original source files must be manually copied back from the <targetdirectory>/subjective-c/originalsources directory to their original place. The file located at <targetdirectory>/subjective-c/locked must also be removed. This file is a security that avoids to starts a new compilation process if the previous one failed and the original sources were not copied back yet. Otherwise, the original sources would be lost.

164 Bibliography [AHH + 09] Malte Appeltauer, Robert Hirschfeld, Michael Haupt, Jens Lincke, and Michael Perscheid. A comparison of context-oriented programming languages. COP 09: International Workshop on Context-Oriented Programming (ACM), [AHHM09] Malte Appeltauer, Robert Hirschfeld, Michael Haupt, and Hidehiko Masuhara. Contextj: Context-oriented programming with java. COP 09: International Workshop on Context-Oriented Programming, [AHM + 10] Malte Appeltauer, Robert Hirschfeld, Hidehiko Masuhara, Michael Haupt, and Kazunori Kawauchi. Event-specific software composition in context-oriented programming. Springer-Verlag Berlin Heidelberg 2010, [App09] Apple. Objective-c runtime programming guide [App10a] Apple. Creating a singleton instance [App10b] Apple. Grand central dispatch (gcd) reference [BY09] [CH05] [CH07] Erick M. Buck and Donald A. Yacktman. Cocoa Design Patterns. Addison Wesley, Pascal Costanza and Robert Hirschfeld. Language constructs for context-oriented programming: An overview of contextl. DLS 05: Proceedings of the 2005 symposium on Dynamic languages (ACM), Pascal Costanza and Robert Hirschfeld. Reflective layer activation in contextl. SAC 07: Proceedings of the 2007 ACM symposium on Applied computing (ACM), pages , [GCM + 10] Sebastián González, Nicolás Cardozo, Kim Mens, Alfredo Cádiz, Jean-Christophe Libbrecht, and Julien Goffaux. Subjective-c. SLE 10 Proceedings of the Third international conference on Software language engineering, Oct [GHJV94] [GMC08] [GMH07] Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns Elements of Reusable Object-Oriented Software. Addison Wesley, Sebastián González, Kim Mens, and Alfredo Cádiz. Context-oriented programming with the ambient object system. Journal of Universal Computer Science, 14: , Sebastián González, Kim Mens, and Patrick Heymans. Highly dynamic behaviour adaptability through prototypes with subjective multimethods. DLS 07 Proceedings of the 2007 symposium on Dynamic languages,

165 BIBLIOGRAPHY 155 [Gon08] Sebastián González. Programming in Ambience: Gearing up for Dynamic Adaptation to Context. PhD thesis, Université catholique de Louvain - École Polytechnique de Louvain, [HCH07] Robert Hirschfeld, Pascal Costanz, and Michael Haupt. An introduction to context-oriented programming with contexts. Generative and Transformational Techniques in Software Engineering II, [LASH11] Jens Lincke, Malte Appeltauer, Bastian Steinert, and Robert Hirschfeld. An open implementation for context-oriented layer composition in contextjs. Science of Computer Programming, [MGLG10] Kim Mens, Sebastián González, Jean-Christophe Libbrecht, and Julien Goffaux. Subjective-c: Enabling context-aware programming on iphone. Master s thesis, Université catholique de Louvain, [ZKT10] Lamia Abo Zaid, Frederic Kleinermann, and Olga De Troyer. Feature assembly: A new feature modeling technique. ER 10: Proceedings of the 29th international conference on Conceptual modeling (Springer-Verlag), 2010.

166 Glossary Subjective-C Parser A compilation module that is in charge of translating Subjective-C files into plain Objective- C files. It also has the task to collect context names and relations from an ECDL file and context methods from Subjective-C files in order to generate a context initialization file. activation counter For a context, it defines its activation state. A context is said to be active when its activation count is superior to zero. It is inactive otherwise. activation event Defines a context activation or deactivation. best context method From the Context Method Finder point of view, the context method that takes precedence over all the others extending the same original method. candidate context method A context method is said to be a candidate for its respective original method when all the contexts for which this context method is defined are active at the same time. context A state of the environment. This state can be external (temperature, wifi access,... ), logical (network data) or internal (logging, debug,... ). context activation age An indication about the time during which a context has been active. When a context is sent the message activate, its age becomes 0 and all the other active contexts have their age incremented by 1. When a context is deactivated, it does not have an age anymore and the contexts that were older than it have their age decremented by 1. It can be seen like an context activation timeline. Context Manager A module that is in charge of managing contexts. It can add, remove contexts and retrieve contexts. It is also capable of adding or removing relations between groups of contexts. context method A method defined for one or several contexts and which is extending an original method. A context method is said to be a behavioral variation of its respective original method. Context Method Finder A module that is in charge of breaking the tie between conflicting context methods. It is called every time the system tries to find the best or the next context method. It is a submodule of the Method Dispatcher. context method priority An integer that is used as a static property to define an order between context methods extending a same original method. If a context method has a higher priority than another context method, then the former takes precedence over the latter. context method state See candidate context method. context methods conflict It happens when there exist simultaneously at least two candidate context methods for the same original method. The Context Method 156

167 Glossary 157 Finder then needs to break the tie thanks to dynamic properties such as the context activation age. context relation A link defining dependence properties between two contexts. There are four types of binary relations: exclusion, weak inclusion, strong inclusion and requirement. There is one n- ary relation called composition. Eventually, there is one more unary relation called not relation. context state A context is said to be active when its activation count is superior to zero. It is inactive otherwise. default method A method implementation defining the default behavior of an original method, that is, the method variation defined for no contexts. If no default implementation is provided, one is automatically created by Subjective- C with a specific user-defined behavior. This behavior can either throw an error or display a warning message or simply do nothing. global context A context that concerns all threads in the application. Its activation events always have effects at the application-level, that is, on all threads. local context A context that is local to specific threads. Its activation events always have effect at a thread-level, that is, for at most one thread at a time. local dispatcher A special method that is in charge of forwarding a call to the best context method. It is used when a local context is activated. Every methods defined for this local context then become locally dispatched. Method Dispatcher A module that is in charge of handling context updates by replacing method implementations. It can register context methods and keep a trace of every default method. In Subjective-C 1.0, it handles supercontext calls. In Subjective-C 2.0, it s helping the resend mechanism for finding the next context method. It is the most important module in Subjective-C. next context method From the Context Method Finder point of view, the best context method that has not already been called in the current resend history. original method A method structure for which context-specific variations are defined. The implementation of this method is modified by Subjective-C, at runtime, on every context activation event. All context methods with the same method signature and declared in the same class are defined for the same original method. original selector The selector of an original method. related contexts The set of contexts used to defined a context method. This context method is said to be a candidate for its original method when all its related contexts are active at the same time. resend A mechanism used for calling, from a certain context method, the next context method. It replaces the supercontext mechanism and ensures thread-safety. supercontext A mechanism used for calling, from a given context method, the corresponding next context method. This call is translated by Subjective-C parser into a call to this next context method. In Subjective-C 2.0, this mechanism is replaced by the resend mechanism because the former mechanism is not thread safety. translation phase The Subjective-C compilation phase during which the Subjective-C files are translated into Objective-C files and the context initialization file is generated from the context names and relations collected from an ECDL file and the context methods coming from the parsed Subjective-C files.

168 Acronyms AmOS Ambience Object System. API Application Programming Interface. CLOS Common List Object System. COP context-oriented programming. EBNF Extended Backus Naur Form. ECDL Easy Context Declaration Language. GCD Grand Central Dispatch. GPS Global Positioning System. IDE Integrated Development Environment. MOP Metaobject Protocol. MVC Model-View-Controller. OS Operating System. 158

169 Index 43 #context , 31 #priority , 37 A Ambience context , 11 multimethods syntax B behavioral variation C context , 14, 25, 32 activation , 38 activation age , 96, 98 activation event , 15, 47 activation notification active , 40 deactivation , 39 declaration default context multiple activation events relation , 29 state context manager , 23, 37, 110 context manager architecture context method , 24, 40 candidate , 41 conflict default method , 20, 25, 26, 101 not context original method , 25, 43 original selector precedence , 98 priority , 24, 37, 98 related contexts , 19 scope supercontext , 22, 83 supercontext call context method finder , 94 best context method , 100 next context method , 100 order relation ( o =, o >) , 98 precedence relation ( p =, p >) , 98 context relation composition exclusion inclusion strong inclusion weak inclusion opposite requirement strong inclusion weak inclusion context request context-oriented programming , 7 behavioral variation concepts context language extension layer scope ContextJ ContextL , 9 layer layer t layered block layered class layered function layered method next method thread-local ContextS contextual block

170 INDEX 160 D dynamic method invocation E ECDL , 40 context relations contexts declaration relations declaration relations symbols structure G global context limitations global dispatch limitations L local context , 5, 40, 66 activation activation age activation event activation notification characteristics external activation external activation event pending activation performance proxy strategy request state , 71 local dispatch algorithm argument processor characteristics local dispatcher M method dispatcher , 23, 37 context methods global context activation implementation replacement startup behavior N next context method , 84, 89 NSNotificationCenter NSObject SCResend category O Objective-C original method dispatch mode original selector P pending activation queue , 73 R resend , 82 algorithm call history multiple histories result value S SCAction SCContext , 68 SCContextManager SCContextManager SCContextSelector SCContextSelector SCGlobalContext SCLocalContext , 97 SCLocalContextActivationPending. 73 SCMethod SCMethodDispatcher SCOriginalSelector SCOriginalSelector Subjective-C application behavior context discovery context management general architecture Subjective-C data structures limitations method dispatcher Subjective-C context activation event context method declaration ECDL resend Subjective-C parser #context #priority Translation phase translation phase Subjective-C parser context method ECDL

171 INDEX 161 Subjective-C files supercontext , 82 limitations problems storing result translation T Triangles vii contexts viii contexts graph ix description vii triangle properties vii

172 INDEX 162

Chapter 1. Introduction to ios Development. Objectives: Touch on the history of ios and the devices that support this operating system.

Chapter 1. Introduction to ios Development. Objectives: Touch on the history of ios and the devices that support this operating system. Chapter 1 Introduction to ios Development Objectives: Touch on the history of ios and the devices that support this operating system. Understand the different types of Apple Developer accounts. Introduce

More information

MA-WA1920: Enterprise iphone and ipad Programming

MA-WA1920: Enterprise iphone and ipad Programming MA-WA1920: Enterprise iphone and ipad Programming Description This 5 day iphone training course teaches application development for the ios platform. It covers iphone, ipad and ipod Touch devices. This

More information

Efficient database auditing

Efficient database auditing Topicus Fincare Efficient database auditing And entity reversion Dennis Windhouwer Supervised by: Pim van den Broek, Jasper Laagland and Johan te Winkel 9 April 2014 SUMMARY Topicus wants their current

More information

Progress Report Aspect Oriented Programming meets Design Patterns. Academic Programme MSc in Advanced Computer Science. Guillermo Antonio Toro Bayona

Progress Report Aspect Oriented Programming meets Design Patterns. Academic Programme MSc in Advanced Computer Science. Guillermo Antonio Toro Bayona Progress Report Aspect Oriented Programming meets Design Patterns Academic Programme MSc in Advanced Computer Science Guillermo Antonio Toro Bayona Supervisor Dr. John Sargeant The University of Manchester

More information

Fundamentals of Java Programming

Fundamentals of Java Programming Fundamentals of Java Programming This document is exclusive property of Cisco Systems, Inc. Permission is granted to print and copy this document for non-commercial distribution and exclusive use by instructors

More information

Language Evaluation Criteria. Evaluation Criteria: Readability. Evaluation Criteria: Writability. ICOM 4036 Programming Languages

Language Evaluation Criteria. Evaluation Criteria: Readability. Evaluation Criteria: Writability. ICOM 4036 Programming Languages ICOM 4036 Programming Languages Preliminaries Dr. Amirhossein Chinaei Dept. of Electrical & Computer Engineering UPRM Spring 2010 Language Evaluation Criteria Readability: the ease with which programs

More information

ANALYSIS OF GRID COMPUTING AS IT APPLIES TO HIGH VOLUME DOCUMENT PROCESSING AND OCR

ANALYSIS OF GRID COMPUTING AS IT APPLIES TO HIGH VOLUME DOCUMENT PROCESSING AND OCR ANALYSIS OF GRID COMPUTING AS IT APPLIES TO HIGH VOLUME DOCUMENT PROCESSING AND OCR By: Dmitri Ilkaev, Stephen Pearson Abstract: In this paper we analyze the concept of grid programming as it applies to

More information

Component visualization methods for large legacy software in C/C++

Component visualization methods for large legacy software in C/C++ Annales Mathematicae et Informaticae 44 (2015) pp. 23 33 http://ami.ektf.hu Component visualization methods for large legacy software in C/C++ Máté Cserép a, Dániel Krupp b a Eötvös Loránd University [email protected]

More information

ios Dev Crib Sheet In the Shadow of C

ios Dev Crib Sheet In the Shadow of C ios Dev Crib Sheet As you dive into the deep end of the ios development pool, the first thing to remember is that the mother ship holds the authoritative documentation for this endeavor http://developer.apple.com/ios

More information

Chapter 1. Dr. Chris Irwin Davis Email: [email protected] Phone: (972) 883-3574 Office: ECSS 4.705. CS-4337 Organization of Programming Languages

Chapter 1. Dr. Chris Irwin Davis Email: cid021000@utdallas.edu Phone: (972) 883-3574 Office: ECSS 4.705. CS-4337 Organization of Programming Languages Chapter 1 CS-4337 Organization of Programming Languages Dr. Chris Irwin Davis Email: [email protected] Phone: (972) 883-3574 Office: ECSS 4.705 Chapter 1 Topics Reasons for Studying Concepts of Programming

More information

Glossary of Object Oriented Terms

Glossary of Object Oriented Terms Appendix E Glossary of Object Oriented Terms abstract class: A class primarily intended to define an instance, but can not be instantiated without additional methods. abstract data type: An abstraction

More information

How To Develop Software

How To Develop Software Software Engineering Prof. N.L. Sarda Computer Science & Engineering Indian Institute of Technology, Bombay Lecture-4 Overview of Phases (Part - II) We studied the problem definition phase, with which

More information

So today we shall continue our discussion on the search engines and web crawlers. (Refer Slide Time: 01:02)

So today we shall continue our discussion on the search engines and web crawlers. (Refer Slide Time: 01:02) Internet Technology Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture No #39 Search Engines and Web Crawler :: Part 2 So today we

More information

Java (12 Weeks) Introduction to Java Programming Language

Java (12 Weeks) Introduction to Java Programming Language Java (12 Weeks) Topic Lecture No. Introduction to Java Programming Language 1 An Introduction to Java o Java as a Programming Platform, The Java "White Paper" Buzzwords, Java and the Internet, A Short

More information

Internationalization and Web Services

Internationalization and Web Services Internationalization and Web Services 25 th Internationalization and Unicode Conference Presented by Addison P. Phillips Director, Globalization Architecture webmethods, Inc. 25 th Internationalization

More information

An Easier Way for Cross-Platform Data Acquisition Application Development

An Easier Way for Cross-Platform Data Acquisition Application Development An Easier Way for Cross-Platform Data Acquisition Application Development For industrial automation and measurement system developers, software technology continues making rapid progress. Software engineers

More information

The Phases of an Object-Oriented Application

The Phases of an Object-Oriented Application The Phases of an Object-Oriented Application Reprinted from the Feb 1992 issue of The Smalltalk Report Vol. 1, No. 5 By: Rebecca J. Wirfs-Brock There is never enough time to get it absolutely, perfectly

More information

Aspect-Oriented Programming

Aspect-Oriented Programming Aspect-Oriented Programming An Introduction to Aspect-Oriented Programming and AspectJ Niklas Påhlsson Department of Technology University of Kalmar S 391 82 Kalmar SWEDEN Topic Report for Software Engineering

More information

Integration of Application Business Logic and Business Rules with DSL and AOP

Integration of Application Business Logic and Business Rules with DSL and AOP Integration of Application Business Logic and Business Rules with DSL and AOP Bogumiła Hnatkowska and Krzysztof Kasprzyk Wroclaw University of Technology, Wyb. Wyspianskiego 27 50-370 Wroclaw, Poland [email protected]

More information

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011 INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011 1 Goals of the Lecture Present an introduction to Objective-C 2.0 Coverage of the language will be INCOMPLETE

More information

View Controller Programming Guide for ios

View Controller Programming Guide for ios View Controller Programming Guide for ios Contents About View Controllers 10 At a Glance 11 A View Controller Manages a Set of Views 11 You Manage Your Content Using Content View Controllers 11 Container

More information

The Microsoft Windows Hypervisor High Level Architecture

The Microsoft Windows Hypervisor High Level Architecture The Microsoft Windows Hypervisor High Level Architecture September 21, 2007 Abstract The Microsoft Windows hypervisor brings new virtualization capabilities to the Windows Server operating system. Its

More information

A Java-based system support for distributed applications on the Internet

A Java-based system support for distributed applications on the Internet A Java-based system support for distributed applications on the Internet D. Hagimont 1, D. Louvegnies 2 SIRAC Project INRIA, 655 av. de l Europe, 38330 Montbonnot Saint-Martin, France Abstract: We have

More information

Programming Languages

Programming Languages Programming Languages Programming languages bridge the gap between people and machines; for that matter, they also bridge the gap among people who would like to share algorithms in a way that immediately

More information

ios Design Patterns Jackie Myrose CSCI 5448 Fall 2012

ios Design Patterns Jackie Myrose CSCI 5448 Fall 2012 ios Design Patterns Jackie Myrose CSCI 5448 Fall 2012 Design Patterns A design pattern is a common solution to a software problem They are helpful for speeding up problem solving, ensuring that a developer

More information

UNIVERSITY OF MALTA THE MATRICULATION CERTIFICATE EXAMINATION ADVANCED LEVEL COMPUTING. May 2011

UNIVERSITY OF MALTA THE MATRICULATION CERTIFICATE EXAMINATION ADVANCED LEVEL COMPUTING. May 2011 UNIVERSITY OF MALTA THE MATRICULATION CERTIFICATE EXAMINATION ADVANCED LEVEL COMPUTING May 2011 EXAMINERS REPORT MATRICULATION AND SECONDARY EDUCATION CERTIFICATE EXAMINATIONS BOARD AM Computing May 2011

More information

[Refer Slide Time: 05:10]

[Refer Slide Time: 05:10] Principles of Programming Languages Prof: S. Arun Kumar Department of Computer Science and Engineering Indian Institute of Technology Delhi Lecture no 7 Lecture Title: Syntactic Classes Welcome to lecture

More information

THE IMPACT OF INHERITANCE ON SECURITY IN OBJECT-ORIENTED DATABASE SYSTEMS

THE IMPACT OF INHERITANCE ON SECURITY IN OBJECT-ORIENTED DATABASE SYSTEMS THE IMPACT OF INHERITANCE ON SECURITY IN OBJECT-ORIENTED DATABASE SYSTEMS David L. Spooner Computer Science Department Rensselaer Polytechnic Institute Troy, New York 12180 The object-oriented programming

More information

New Generation of Software Development

New Generation of Software Development New Generation of Software Development Terry Hon University of British Columbia 201-2366 Main Mall Vancouver B.C. V6T 1Z4 [email protected] ABSTRACT In this paper, I present a picture of what software development

More information

CSCI E-65: Mobile Application Development Using Swift and ios

CSCI E-65: Mobile Application Development Using Swift and ios Page 1 of 5 OFFICIAL 25 Jan 2016 CSCI E-65: Mobile Application Development Using Swift and ios Harvard University Extension School: Spring 2016 Instructor: Daniel Bromberg [email protected] TF:

More information

1 Organization of Operating Systems

1 Organization of Operating Systems COMP 730 (242) Class Notes Section 10: Organization of Operating Systems 1 Organization of Operating Systems We have studied in detail the organization of Xinu. Naturally, this organization is far from

More information

Service-Oriented Architecture and Software Engineering

Service-Oriented Architecture and Software Engineering -Oriented Architecture and Software Engineering T-86.5165 Seminar on Enterprise Information Systems (2008) 1.4.2008 Characteristics of SOA The software resources in a SOA are represented as services based

More information

EWeb: Highly Scalable Client Transparent Fault Tolerant System for Cloud based Web Applications

EWeb: Highly Scalable Client Transparent Fault Tolerant System for Cloud based Web Applications ECE6102 Dependable Distribute Systems, Fall2010 EWeb: Highly Scalable Client Transparent Fault Tolerant System for Cloud based Web Applications Deepal Jayasinghe, Hyojun Kim, Mohammad M. Hossain, Ali Payani

More information

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

KITES TECHNOLOGY COURSE MODULE (C, C++, DS) KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php [email protected] [email protected] Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL

More information

History OOP languages Year Language 1967 Simula-67 1983 Smalltalk

History OOP languages Year Language 1967 Simula-67 1983 Smalltalk History OOP languages Intro 1 Year Language reported dates vary for some languages... design Vs delievered 1957 Fortran High level programming language 1958 Lisp 1959 Cobol 1960 Algol Structured Programming

More information

Functional Decomposition Top-Down Development

Functional Decomposition Top-Down Development Functional Decomposition Top-Down Development The top-down approach builds a system by stepwise refinement, starting with a definition of its abstract function. You start the process by expressing a topmost

More information

The BSN Hardware and Software Platform: Enabling Easy Development of Body Sensor Network Applications

The BSN Hardware and Software Platform: Enabling Easy Development of Body Sensor Network Applications The BSN Hardware and Software Platform: Enabling Easy Development of Body Sensor Network Applications Joshua Ellul [email protected] Overview Brief introduction to Body Sensor Networks BSN Hardware

More information

Virtual Credit Card Processing System

Virtual Credit Card Processing System The ITB Journal Volume 3 Issue 2 Article 2 2002 Virtual Credit Card Processing System Geraldine Gray Karen Church Tony Ayres Follow this and additional works at: http://arrow.dit.ie/itbj Part of the E-Commerce

More information

Object-Oriented Software Specification in Programming Language Design and Implementation

Object-Oriented Software Specification in Programming Language Design and Implementation Object-Oriented Software Specification in Programming Language Design and Implementation Barrett R. Bryant and Viswanathan Vaidyanathan Department of Computer and Information Sciences University of Alabama

More information

Embedded Software Development with MPS

Embedded Software Development with MPS Embedded Software Development with MPS Markus Voelter independent/itemis The Limitations of C and Modeling Tools Embedded software is usually implemented in C. The language is relatively close to the hardware,

More information

Chapter 13: Program Development and Programming Languages

Chapter 13: Program Development and Programming Languages 15 th Edition Understanding Computers Today and Tomorrow Comprehensive Chapter 13: Program Development and Programming Languages Deborah Morley Charles S. Parker Copyright 2015 Cengage Learning Learning

More information

The programming language C. sws1 1

The programming language C. sws1 1 The programming language C sws1 1 The programming language C invented by Dennis Ritchie in early 1970s who used it to write the first Hello World program C was used to write UNIX Standardised as K&C (Kernighan

More information

Source Code Translation

Source Code Translation Source Code Translation Everyone who writes computer software eventually faces the requirement of converting a large code base from one programming language to another. That requirement is sometimes driven

More information

Web Presentation Layer Architecture

Web Presentation Layer Architecture Chapter 4 Web Presentation Layer Architecture In this chapter we provide a discussion of important current approaches to web interface programming based on the Model 2 architecture [59]. From the results

More information

THE OPEN UNIVERSITY OF TANZANIA

THE OPEN UNIVERSITY OF TANZANIA THE OPEN UNIVERSITY OF TANZANIA FACULTY OF SCIENCE, TECHNOLOGY AND ENVIRONMENTAL STUDIES ODM 103: INTRODUCTION TO COMPUTER PROGRAMMING LANGUAGES Said Ally i ODM 103 INTRODUCTION TO COMPUTER PROGRAMMING

More information

Last Updated: July 2011. STATISTICA Enterprise Server Security

Last Updated: July 2011. STATISTICA Enterprise Server Security Last Updated: July 2011 STATISTICA Enterprise Server Security STATISTICA Enterprise Server Security Page 2 of 10 Table of Contents Executive Summary... 3 Introduction to STATISTICA Enterprise Server...

More information

Resurrecting Ada s Rendez-Vous in Java

Resurrecting Ada s Rendez-Vous in Java Resurrecting Ada s Rendez-Vous in Java Luis Mateu, José M. Piquer and Juan León DCC - Universidad de Chile Casilla 2777, Santiago, Chile [email protected] Abstract Java is a programming language designed

More information

Managing a Fibre Channel Storage Area Network

Managing a Fibre Channel Storage Area Network Managing a Fibre Channel Storage Area Network Storage Network Management Working Group for Fibre Channel (SNMWG-FC) November 20, 1998 Editor: Steven Wilson Abstract This white paper describes the typical

More information

Computing Concepts with Java Essentials

Computing Concepts with Java Essentials 2008 AGI-Information Management Consultants May be used for personal purporses only or by libraries associated to dandelon.com network. Computing Concepts with Java Essentials 3rd Edition Cay Horstmann

More information

Characteristics of Java (Optional) Y. Daniel Liang Supplement for Introduction to Java Programming

Characteristics of Java (Optional) Y. Daniel Liang Supplement for Introduction to Java Programming Characteristics of Java (Optional) Y. Daniel Liang Supplement for Introduction to Java Programming Java has become enormously popular. Java s rapid rise and wide acceptance can be traced to its design

More information

Decomposition into Parts. Software Engineering, Lecture 4. Data and Function Cohesion. Allocation of Functions and Data. Component Interfaces

Decomposition into Parts. Software Engineering, Lecture 4. Data and Function Cohesion. Allocation of Functions and Data. Component Interfaces Software Engineering, Lecture 4 Decomposition into suitable parts Cross cutting concerns Design patterns I will also give an example scenario that you are supposed to analyse and make synthesis from The

More information

1/20/2016 INTRODUCTION

1/20/2016 INTRODUCTION INTRODUCTION 1 Programming languages have common concepts that are seen in all languages This course will discuss and illustrate these common concepts: Syntax Names Types Semantics Memory Management We

More information

Table of Contents. CHAPTER 1 Web-Based Systems 1. CHAPTER 2 Web Engineering 12. CHAPTER 3 A Web Engineering Process 24

Table of Contents. CHAPTER 1 Web-Based Systems 1. CHAPTER 2 Web Engineering 12. CHAPTER 3 A Web Engineering Process 24 Table of Contents CHAPTER 1 Web-Based Systems 1 The Web 1 Web Applications 2 Let s Introduce a Case Study 3 Are WebApps Really Computer Software? 4 Are the Attributes of WebApps Different from the Attributes

More information

Apex Code: The World s First On-Demand Programming Language

Apex Code: The World s First On-Demand Programming Language WHIT EP AP ER Apex Code: The World s First On-Demand Programming Language Contents Extending the Power of the Apex Platform... 1 Multi-tenancy and Programming Languages... 1 Apex Code Design and Syntax...

More information

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition Java 6 'th edition Concepts INTERNATIONAL STUDENT VERSION CONTENTS PREFACE vii SPECIAL FEATURES xxviii chapter i INTRODUCTION 1 1.1 What Is Programming? 2 J.2 The Anatomy of a Computer 3 1.3 Translating

More information

Object Oriented Programming and the Objective-C Programming Language 1.0. (Retired Document)

Object Oriented Programming and the Objective-C Programming Language 1.0. (Retired Document) Object Oriented Programming and the Objective-C Programming Language 1.0 (Retired Document) Contents Introduction to The Objective-C Programming Language 1.0 7 Who Should Read This Document 7 Organization

More information

Java Application Developer Certificate Program Competencies

Java Application Developer Certificate Program Competencies Java Application Developer Certificate Program Competencies After completing the following units, you will be able to: Basic Programming Logic Explain the steps involved in the program development cycle

More information

VMware Virtualization and Software Development

VMware Virtualization and Software Development VMware Virtualization and Software Development 1 VMware Virtualization and Software Development Mark Cloutier Undergraduate Student, Applied Math and Computer Science Keywords: Virtualization, VMware,

More information

SOACertifiedProfessional.Braindumps.S90-03A.v2014-06-03.by.JANET.100q. Exam Code: S90-03A. Exam Name: SOA Design & Architecture

SOACertifiedProfessional.Braindumps.S90-03A.v2014-06-03.by.JANET.100q. Exam Code: S90-03A. Exam Name: SOA Design & Architecture SOACertifiedProfessional.Braindumps.S90-03A.v2014-06-03.by.JANET.100q Number: S90-03A Passing Score: 800 Time Limit: 120 min File Version: 14.5 http://www.gratisexam.com/ Exam Code: S90-03A Exam Name:

More information

Domains and Competencies

Domains and Competencies Domains and Competencies DOMAIN I TECHNOLOGY APPLICATIONS CORE Standards Assessed: Computer Science 8 12 I VII Competency 001: The computer science teacher knows technology terminology and concepts; the

More information

RUnit - A Unit Test Framework for R

RUnit - A Unit Test Framework for R RUnit - A Unit Test Framework for R Thomas König, Klaus Jünemann, and Matthias Burger Epigenomics AG November 5, 2015 Contents 1 Introduction 2 2 The RUnit package 4 2.1 Test case execution........................

More information

Data Modeling Basics

Data Modeling Basics Information Technology Standard Commonwealth of Pennsylvania Governor's Office of Administration/Office for Information Technology STD Number: STD-INF003B STD Title: Data Modeling Basics Issued by: Deputy

More information

To Java SE 8, and Beyond (Plan B)

To Java SE 8, and Beyond (Plan B) 11-12-13 To Java SE 8, and Beyond (Plan B) Francisco Morero Peyrona EMEA Java Community Leader 8 9...2012 2020? Priorities for the Java Platforms Grow Developer Base Grow Adoption

More information

Building Applications Using Micro Focus COBOL

Building Applications Using Micro Focus COBOL Building Applications Using Micro Focus COBOL Abstract If you look through the Micro Focus COBOL documentation, you will see many different executable file types referenced: int, gnt, exe, dll and others.

More information

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture Last Class: OS and Computer Architecture System bus Network card CPU, memory, I/O devices, network card, system bus Lecture 3, page 1 Last Class: OS and Computer Architecture OS Service Protection Interrupts

More information

Web Services for Management Perl Library VMware ESX Server 3.5, VMware ESX Server 3i version 3.5, and VMware VirtualCenter 2.5

Web Services for Management Perl Library VMware ESX Server 3.5, VMware ESX Server 3i version 3.5, and VMware VirtualCenter 2.5 Technical Note Web Services for Management Perl Library VMware ESX Server 3.5, VMware ESX Server 3i version 3.5, and VMware VirtualCenter 2.5 In the VMware Infrastructure (VI) Perl Toolkit 1.5, VMware

More information

How To Teach Object Oriented Programming At An Introductory Level Course

How To Teach Object Oriented Programming At An Introductory Level Course 149 TEACHING OBJECT ORIENTED PROGRAMMING AT THE INTRODUCTORY LEVEL Mehmet C. OKUR * ABSTRACT Teaching object oriented programming has become a rapidly expanding preference at various educational environments.

More information

IST STREP Project. Deliverable D3.3.1u Middleware User s Guide Multi-Radio Device Management Layer. http://www.ist-plastic.org

IST STREP Project. Deliverable D3.3.1u Middleware User s Guide Multi-Radio Device Management Layer. http://www.ist-plastic.org IST STREP Project Deliverable D3.3.1u Middleware User s Guide Multi-Radio Device Management Layer http://www.ist-plastic.org Project Number : IST-26955 Project Title : PLASTIC Deliverable Type : Report

More information

How To Test Your Web Site On Wapt On A Pc Or Mac Or Mac (Or Mac) On A Mac Or Ipad Or Ipa (Or Ipa) On Pc Or Ipam (Or Pc Or Pc) On An Ip

How To Test Your Web Site On Wapt On A Pc Or Mac Or Mac (Or Mac) On A Mac Or Ipad Or Ipa (Or Ipa) On Pc Or Ipam (Or Pc Or Pc) On An Ip Load testing with WAPT: Quick Start Guide This document describes step by step how to create a simple typical test for a web application, execute it and interpret the results. A brief insight is provided

More information

Object Oriented Programming. Risk Management

Object Oriented Programming. Risk Management Section V: Object Oriented Programming Risk Management In theory, there is no difference between theory and practice. But, in practice, there is. - Jan van de Snepscheut 427 Chapter 21: Unified Modeling

More information

Example of Standard API

Example of Standard API 16 Example of Standard API System Call Implementation Typically, a number associated with each system call System call interface maintains a table indexed according to these numbers The system call interface

More information

Elemental functions: Writing data-parallel code in C/C++ using Intel Cilk Plus

Elemental functions: Writing data-parallel code in C/C++ using Intel Cilk Plus Elemental functions: Writing data-parallel code in C/C++ using Intel Cilk Plus A simple C/C++ language extension construct for data parallel operations Robert Geva [email protected] Introduction Intel

More information

CSE 373: Data Structure & Algorithms Lecture 25: Programming Languages. Nicki Dell Spring 2014

CSE 373: Data Structure & Algorithms Lecture 25: Programming Languages. Nicki Dell Spring 2014 CSE 373: Data Structure & Algorithms Lecture 25: Programming Languages Nicki Dell Spring 2014 What is a Programming Language? A set of symbols and associated tools that translate (if necessary) collections

More information

Lecture 1: Introduction

Lecture 1: Introduction Programming Languages Lecture 1: Introduction Benjamin J. Keller Department of Computer Science, Virginia Tech Programming Languages Lecture 1 Introduction 2 Lecture Outline Preview History of Programming

More information

The Best of Both Worlds Sharing Mac Files on Windows Servers

The Best of Both Worlds Sharing Mac Files on Windows Servers The Best of Both Worlds Sharing Mac Files on Windows Servers March, 2008 1110 North Glebe Road Suite 450 Arlington, VA 22201 phone: 800.476.8781 or +1.703.528.1555 fax: +1.703.527.2567 or +1.703.528.3296

More information

Finger Paint: Cross-platform Augmented Reality

Finger Paint: Cross-platform Augmented Reality Finger Paint: Cross-platform Augmented Reality Samuel Grant Dawson Williams October 15, 2010 Abstract Finger Paint is a cross-platform augmented reality application built using Dream+ARToolKit. A set of

More information

Xcode Project Management Guide. (Legacy)

Xcode Project Management Guide. (Legacy) Xcode Project Management Guide (Legacy) Contents Introduction 10 Organization of This Document 10 See Also 11 Part I: Project Organization 12 Overview of an Xcode Project 13 Components of an Xcode Project

More information

Integration of Application Business Logic and Business Rules with DSL and AOP

Integration of Application Business Logic and Business Rules with DSL and AOP e-informatica Software Engineering Journal, Volume 4, Issue, 200 Integration of Application Business Logic and Business Rules with DSL and AOP Bogumiła Hnatkowska, Krzysztof Kasprzyk Faculty of Computer

More information

PART IV Performance oriented design, Performance testing, Performance tuning & Performance solutions. Outline. Performance oriented design

PART IV Performance oriented design, Performance testing, Performance tuning & Performance solutions. Outline. Performance oriented design PART IV Performance oriented design, Performance testing, Performance tuning & Performance solutions Slide 1 Outline Principles for performance oriented design Performance testing Performance tuning General

More information

Chapter 2: Remote Procedure Call (RPC)

Chapter 2: Remote Procedure Call (RPC) Chapter 2: Remote Procedure Call (RPC) Gustavo Alonso Computer Science Department Swiss Federal Institute of Technology (ETHZ) [email protected] http://www.iks.inf.ethz.ch/ Contents - Chapter 2 - RPC

More information

Xcode User Default Reference. (Legacy)

Xcode User Default Reference. (Legacy) Xcode User Default Reference (Legacy) Contents Introduction 5 Organization of This Document 5 Software Version 5 See Also 5 Xcode User Defaults 7 Xcode User Default Overview 7 General User Defaults 8 NSDragAndDropTextDelay

More information

What is Data Virtualization?

What is Data Virtualization? What is Data Virtualization? Rick F. van der Lans Data virtualization is receiving more and more attention in the IT industry, especially from those interested in data management and business intelligence.

More information

SERVICE-ORIENTED MODELING FRAMEWORK (SOMF ) SERVICE-ORIENTED SOFTWARE ARCHITECTURE MODEL LANGUAGE SPECIFICATIONS

SERVICE-ORIENTED MODELING FRAMEWORK (SOMF ) SERVICE-ORIENTED SOFTWARE ARCHITECTURE MODEL LANGUAGE SPECIFICATIONS SERVICE-ORIENTED MODELING FRAMEWORK (SOMF ) VERSION 2.1 SERVICE-ORIENTED SOFTWARE ARCHITECTURE MODEL LANGUAGE SPECIFICATIONS 1 TABLE OF CONTENTS INTRODUCTION... 3 About The Service-Oriented Modeling Framework

More information

CA Data Protection. Content Provider Development Guide. Release 15.0

CA Data Protection. Content Provider Development Guide. Release 15.0 CA Data Protection Content Provider Development Guide Release 15.0 This Documentation, which includes embedded help systems and electronically distributed materials (hereinafter referred to as the Documentation

More information

GenericServ, a Generic Server for Web Application Development

GenericServ, a Generic Server for Web Application Development EurAsia-ICT 2002, Shiraz-Iran, 29-31 Oct. GenericServ, a Generic Server for Web Application Development Samar TAWBI PHD student [email protected] Bilal CHEBARO Assistant professor [email protected] Abstract

More information

Introduction to Software Paradigms & Procedural Programming Paradigm

Introduction to Software Paradigms & Procedural Programming Paradigm Introduction & Procedural Programming Sample Courseware Introduction to Software Paradigms & Procedural Programming Paradigm This Lesson introduces main terminology to be used in the whole course. Thus,

More information

CHAPTER THREE, Network Services Management Framework

CHAPTER THREE, Network Services Management Framework CHAPTER THREE, Acronyms and Terms 3-3 List of Figures 3-4 1 Introduction 3-5 2 Architecture 3-6 2.1 Entity Identification & Addressing 3-7 2.2 Management Domain Registration and Information Service 3-7

More information

Dashlane Security Whitepaper

Dashlane Security Whitepaper Dashlane Security Whitepaper November 2014 Protection of User Data in Dashlane Protection of User Data in Dashlane relies on 3 separate secrets: The User Master Password Never stored locally nor remotely.

More information

Departamento de Investigación. LaST: Language Study Tool. Nº 143 Edgard Lindner y Enrique Molinari Coordinación: Graciela Matich

Departamento de Investigación. LaST: Language Study Tool. Nº 143 Edgard Lindner y Enrique Molinari Coordinación: Graciela Matich Departamento de Investigación LaST: Language Study Tool Nº 143 Edgard Lindner y Enrique Molinari Coordinación: Graciela Matich Noviembre 2005 Para citar este documento: Lindner, Edgard; Enrique Molinari,

More information

Software: Systems and. Application Software. Software and Hardware. Types of Software. Software can represent 75% or more of the total cost of an IS.

Software: Systems and. Application Software. Software and Hardware. Types of Software. Software can represent 75% or more of the total cost of an IS. C H A P T E R 4 Software: Systems and Application Software Software and Hardware Software can represent 75% or more of the total cost of an IS. Less costly hdwr. More complex sftwr. Expensive developers

More information

Electronic Ticket and Check-in System for Indico Conferences

Electronic Ticket and Check-in System for Indico Conferences Electronic Ticket and Check-in System for Indico Conferences September 2013 Author: Bernard Kolobara Supervisor: Jose Benito Gonzalez Lopez CERN openlab Summer Student Report 2013 Project Specification

More information

PIE. Internal Structure

PIE. Internal Structure PIE Internal Structure PIE Composition PIE (Processware Integration Environment) is a set of programs for integration of heterogeneous applications. The final set depends on the purposes of a solution

More information