Exploring the flexibility of Scala's Implicits towards an Extensible Live Environment
Full text
FACULDADE DE ENGENHARIA DA UNIVERSIDADE DO PORTO Exploring the flexibility of Scala Implicits towards an Extensible Live Environment Vasco André Costa Grilo Master in Informatics and Computing Engineering Supervisor: Hugo José Sereno Lopes Ferreira (PhD) Second Supervisor: Tiago Boldt Sousa February 13th, 2013
Exploring the flexibility of Scala Implicits towards an Extensible Live Environment Vasco André Costa Grilo Master in Informatics and Computing Engineering Approved in oral examination by the committee: Chair: Prof. Doutor Luís Filipe Pinto de Almeida Teixeira External Examiner: Prof. Doutor Maximino Esteves Correia Bessa Supervisor: Prof. Doutor Hugo José Sereno Lopes Ferreira February 13th, 2013
Abstract This thesis presents the research and implementation details of an extensible live development environment for the Scala programming language called Visual Scala. It also describes the exploration of the flexibility of Scala’s implicits towards such an environment. Scala is an Object- Functional programming language created by Martin Odersky which has been growing in popularity over the past few years. When talking about development environments which support dynamic execution of code during runtime probably the most famous example are Read-Eval-Print Loops. REPLs are interactive top-level environments usually associated with dynamic or functional languages. Although they provide quick ways of inspecting and exploring a certain programming language, they stick to verbose textual representations of the intermediate values that are being generated by the programmer. We feel such an approach is rather limiting to our understanding of data structures and the effects of computation and so we propose to develop a development environment for Scala built on top of the Scala’s standard REPLs with an associated library for converting type values to graphical representations. Using the power of Scala’s Implicits conversions we want to explore how flexible they can be when implementing an innovative mechanism of converting data structures to rich, interactive visualizations. As a web application, benefiting from HTML, CSS and JavaScript, along with the power of D3, a library for easily create graphical representations of data, Visual Scala offers an easily extensible and innovative conversions library for Scala’s native type values. In this way, end users can interact with Visual Scala in a command-line fashion, with expressions resulting in rich graphical “widgets” instead of verbose text. From reviewing the state of the art we find that there are similar tools which provide graphical representations of data structures, however they are usually intended for more technical and mathematical computing. The Julia Language is a very interesting example of such tools, although it provides graphical conversions in an explicit way and does not allow for new conversions to be created by the end-user. We feel that such a component, implicitly generating these graphics, for a more general purpose programming language, like Scala, is an interesting subject to explore and can have a significant impact on the community. From implementing and exploring Visual Scala we conclude that Scala’s Implicits provide high flexibility for developing a mechanism of invoking the right conversion for the right type value at hand. The resulting Conversions Library apart from being extremely flexible, is also easily extensible as it is not part of the running backend system and instead an external resource component. By evaluating user code by using the standard Scala’s interpreter, Visual Scala also provides a “live” environment which maximizes graphical conversion of intermediate data throughout development. i
ii
Resumo Esta tese descreve o estudo e os detalhes de implementação de um ambiente de desenvolvimento vivo e extensível para a linguagem de programação Scala, chamado de Visual Scala. Descreve também o processo de exploração da flexibilidade dos Implícitos de Scala quando se pretende caminhar em direcção a um ambiente desta natureza. Scala é uma linguagem de programação que mistura dois paradigmas, Orientado a Objectos e Funcional, crescendo em popularidade nos últimos anos. Quando se fala em ambientes de desenvolvimento que suportam a execução dinâmica de código durante o seu runtime, o exemplo mais famoso são os Read-Eval-Print Loops. REPLs, ou Interpretadores, são ambientes interactivos de alto-nível, frequentemente associados a linguagens dinâmicas ou funcionais. Embora ofereçam um ambiente de rápida inspeção e exploração de uma linguagem de programação, restringem-se a apresentar os resultados e as estruturas de dados em formatos textuais bastante simples. Nós sentimos que esta aproximação é bastante limitativa na nossa percepção e análise das estruturas de dados e dos efeitos da computação sobre elas e como tal, propomos criar um ambiente para Scala que, construído com base no interpretador de Scala, oferece uma biblioteca de conversões gráficas de resultados. Utilizando o poder das conversões implícitas de Scala, pretendemos explorar o quão flexível elas são quando se implementa um mecanismo inovador de converter tipos de dados para representações gráficas, ricas e interactivas. Apresentando-se como uma aplicação Web, beneficiando do HTML, CSS e JavaScript, juntamente com o poder de D3 (uma biblioteca de fácil geração de representações gráficas de dados), Visual Scala oferece uma inovadora e extensível biblioteca de conversões gráficas. Desta forma, os utilizadores podem interagir com o Visual Scala submetendo expressão a expressão, sendo que estas produzirão resultados gráficos em vez de apenas texto. Da revisão do estado da arte descobrimos que já existem projectos similares, que oferecem representações gráficas de dados, no entanto, estas ferramentas estão geralmente associadas a contextos de computação te´ cnica ou matemática. The Julia Language é um exemplo bastante interessante de tal ambiente, no entanto, este tipo de ferramentas oferece representações gráficas de forma explícita e não permite a criação de novas conversões, por parte do utilizador. Nós acreditamos que esta componente de conversão implícita, dirigida a uma linguagem de programação de um âmbito mais geral, é um tema bastante interessante de ser explorado e pode criar algum impacto na comunidade. Da implementação e exploração do Visual Scala, concluímos que os Implícitos de Scala permitem construir um mecanismo de invocar correctamente a conversão apropriada para o tipo de dados a converter de uma forma altamente flexível. A Biblioteca de Conversões resultante, para além de ser flexível, é também facilmente extensível pois ela não é parte integrante do sistema backend do Visual Scala. Ela faz parte do conjunto externo de recursos, em que modificações produzem efeitos imediatos na componente de conversão. Como a interpretação de código é feita recorrendo ao interpretador oficial de Scala, Visual Scala também oferece um ambiente “vivo” que maximiza a conversão gráfica de resultados intermédios enquanto se escreve código. iii
iv
Contents 1 Introduction 1 1.1 Goals ........................................ 2 1.2 Methodology .................................... 3 1.3 Outline ....................................... 4 2 State of the Art 5 2.1 Context ....................................... 5 2.1.1 TypeSystems................................ 5 2.1.2 Static vs Dynamic Languages . . . . . . . . . . . . . . . . . . . . . . . 6 2.1.3 Software Development Environments . . . . . . . . . . . . . . . . . . . 7 2.1.4 Read-Eval-PrintLoop ........................... 9 2.1.5 Reflection.................................. 9 2.1.6 Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . 10 2.1.7 Scala .................................... 11 2.2 RelatedSolutions.................................. 12 2.2.1 ScalaWorksheet .............................. 12 2.2.2 SimplyScala ................................ 13 2.2.3 Scripster .................................. 13 2.2.4 TheJuliaLanguage............................. 14 2.2.5 OnlinePythonTutor ............................ 15 2.3 Summary ...................................... 16 3 Designing Visual Scala 19 3.1 Requirements .................................... 19 3.1.1 Functional ................................. 19 3.1.2 Usability .................................. 20 3.2 Theapproach .................................... 21 3.2.1 Methodology................................ 21 3.2.2 Decisions.................................. 21 3.3 Summary ...................................... 24 4 Implementation 25 4.1 High-LevelArchitecture .............................. 25 4.2 Frontend (HTML/CSS/JavaScript) . . . . . . . . . . . . . . . . . . . . . . . . . 25 4.2.1 Cookies................................... 27 4.3 Backend(Scala)................................... 28 4.3.1 TheScalaWebServer ........................... 29 4.3.2 EvaluationModule............................. 31 v
Chapter 1 Introduction The presented dissertation describes the process of exploring the flexibility of Scala’s implicits towards an extensible live development environment called Visual Scala. Nowadays, there is huge collection of software development tools available for programmers. Usually referred to as Software Development Environments, SDEs come in various forms and sizes. They range from simple libraries to complex development environments that can manage every stage of the software development life-cycle, from project source files management, source code editors to compilation, debugging, execution and even deployment tools. From simple interpreters to complex environments capable of coordinating large software development teams and manage the entire process of developing software from early user stories definition to implementation and deployment. One example of a rather simple software development tool are Read-Eval-Print Loops (REPL). They are top-level interactive environments, usually associated with dynamic or functional programming languages, offering a quick way of evaluating expressions/instructions. REPLs follow a command-line approach in which end-users type one instruction or expression at a time and see them interpreted. Because of this interpreting approach, REPLs are usually referred to as Interpreters. A rather significant element when developing software is output, produced from computation. Some code is meant for explicitly produce output, namely using Input/Output (I/O) modules of programming languages. When developing, programmers frequently use I/O code to print out data structures, current values of variables, and other relevant information. Output can be used to inform end-users relevant program’s state information guiding its usage and workflow. On another level, as a popular way of debugging a program while in development phase, developers use I/O modules to output data structures to continuously check for desired outcomes of computation. Interpreters, as they usually process user code one expression at a time, generate output for each input that is received. Typically this output is rendered in a verbose way, a textual representa- 1
Introduction tion of values produced by expressions1. While helpful, this verbose rendering offers little insight about the data structures that are being generated and modified. In more mathematical-purposed programming languages, such as MATLAB for instance, it is useful to offer other representations of certain values than a verbose textual representation. If you think of a mathematical function like cos(x), producing output like f1: Function = cos(x) offers no additional information from what the programmer already knows. Because of this, many tools for programming with these languages developed more visual, graphical representations of values. Such tools would render 2cos(x) as a 2-dimensional graphical plot illustrating the behavior of the cosine function, among other helpful visual representations one could think of. Output, and the interpretation that can be extracted from it, is very important and can help enriching and powering the end-user understanding of type values. If I’m developing some program that produces lists of numerals, those lists may, in different contexts, represent bar charts, statistical distributions, binary heap trees, etc. And so, a simple textual representation of the contained values in those lists is rather limiting to my quick understanding of the program’s overall behavior. When using such tools that already provide graphical representations of some type values, we find that tools often provide such visualizations in a explicit way. That is to say, end-users request such visualizations in an explicit way. Graphical User Interfaces (GUIs) have become the major means of communicating and otherwise interacting with computer programs. Graphical visualizations leads to better understanding of data structures which provides, for computer science beginners, a stronger foundation and better preparation for their future. The human visual system and human visual information processing are optimized for multi-dimensional data [Mye86]. Clarisse [CC86] states that graphical programming processes information in a format close to the user’s mental representations of them. And thus, can allow data to be processed in a closer way to how we process data in real world. Graphical representations of data or algorithms, have long been known to be helpful aids in program understanding [Smi77]. The work of Smith [Smi77] describes a number of psychological reasons for using visual displays for programs or data. Motivated by this, we wanted to develop and explore a live, extensible development environment in which data structures have an implicit conversion to a visual representation. The biggest goal is to study how Scala’s implicits can offer a flexible way of converting such data structures. Such environment, for end-users to program in the Scala programming language, aims to incorporate a top-level conversions library for Scala’s type values that can be easily extensible as well as a liveness nature provided by evaluating code with the Scala’s standard REPL, or interpreter. Scala expressions are evaluated with the Scala interpreter and then converted to an HTML version to be displayed on the web application. 1.1 Goals The main goals of this dissertation are listed below: 1Expressions that don’t perform I/O operations. 2
Introduction 1. Review dynamic development environments (i.e., REPLs) What are these REPLs? Are they actually live environments? 2. Explore the flexibility of Scala implicits towards an extensible live development environment. How can we offer an implicit conversion library in a flexible way? Does it make it scalable? Extensible? Live? What can we gain from it? What will we possibly lose? What lessons can be learned from exploring such an environment? 3. Secondary Goal: Research environments which offer graphical representations of data structures How do these environments convert values to graphical outputs? Is this done in a explicit way or implicit way? Is there any related solution that already achieved our goals? 1.2 Methodology A categorization proposed at Dagstuhl workshop [THP93], groups research methods in four general categories, quoted from Zelkowitz and Wallace [ZW98]: •Scientific method. “Scientists develop a theory to explain a phenomenon; they propose a hypothesis and then test alternative variations of the hypothesis. As they do so, they collect data to verify or refute the claims of the hypothesis.” •Engineering method. “Engineers develop and test a solution to a hypothesis. Base upon the results of the test, they improve the solution until it requires no further improvement.” •Empirical method. “A statistical method is proposed as a means to validate a given hypothesis. Unlike the scientific method, there may not be a formal model or theory describing the hypothesis. Data is collected to verify the hypothesis.” •Analytical method. “A formal theory is developed, and results derived from that theory can be compared with empirical observations.” These categories apply to science in general however, effective experimentation in software engineering may require more specific approaches. Because sometimes software engineering research comprises computer science issues, human issues and organizational issues it is often convenient to use combinations of research approaches both from computer science and social science. The taxonomy described by Zelkowitz and Wallace [ZW98] identifies twelve different types of experimental approaches for software engineering, grouped into three broad categories: Observational methods. “An observational method collects relevant data as a project develops. There is relatively little control over the development process other than through using the new technology that is being studied.” There are four types: project monitoring, case study, assertion, and field study. 3
Introduction Historical methods. “A historical method collects data from projects that have already been completed. The data already exist; it is only necessary to analyze what has already been collected.” There are four methods: literature search, legacy data, lessons learned, and static analysis. Controlled methods. “A controlled method provides for multiple instances of an observational for statistical validity of the results. This method is the classical method of experimental design in other scientific disciplines.” There are four types of controlled methods: replicated experiment, synthetic environment experiment, dynamic analysis, and simulation. The optimal combination of methods to use in a concrete research approach is however, strongly dependent on the specific characteristics of the research study to perform, viz. its purpose, environment and resources. In this dissertation, the Engineering Method was used, in which we have established our hypothesis and developed a solution that would verify those hypothesis. Additional increments and re-development of the solution were made in order to improve the solution’s validation of hypothesis. 1.3 Outline This report is structured into three different parts, with the following contents: Part 1: State of the Art The first part of this dissertation’ report gives the reader an overview tour on Visual Scala’s context and the motivation for the study of the flexibility of Scala’s implicits towards the development of an extensible live environment for Scala. We’ll describe the current state of the art on software development environments and development environments which offer graphical representations of data structures. We’ll finalize by presenting a list and description of a few examples of such products that were found, as well an analysis on each product on certain desired functionalities for Visual Scala. Part 2: Design and Implementation The second part contains our pragmatic approach to the problem at hand. Covering the design process, the methodology that was used as well as some design/technological decisions. Part 2 will continue on by extensively describing the implementation process, describring each of the system’s components and how success was achieved. Part 3: Conclusions The last part of this dissertation’ report will present the conclusions from our collective work. Starting by summarizing the hypotheses and goals, the last chapter will cover the obtained results for every hypotheses. We’ll continue on by describing the advantages and disadvantages of the system that was built and also describing the lessons we have learned from studying Scala’s implicits flexibility towards the Conversions library. We’ll finish this report presenting the future work to be done on Visual Scala. 4
Chapter 2 State of the Art In this chapter, we’ll cover the current state of the art regarding the context of our project. Beginning with a detailed explanation of the context in which Visual Scala emerges, we’ll tour on different background concepts that are key to understanding some innovative traits of Visual Scala After we’re done presenting concepts and related work on the field we’ll finish this chapter by presenting some examples of related solutions that were researched. Each one of them will be described, presented with a screenshot of their usage and analyzed on some specific features we aim at Visual Scala so we can compare them to our project. The features that were topic of analysis can be read at section 2.2. 2.1 Context The software development world is demanding and the speed and quality of how software is developed is critical to a project’s success. Nowadays, little software is produced without the aid of software development tools. Tools can improve productivity and how fast you can develop code. Tools can also influence how well you learn a programming language and how well do you understand data structures. Creativity thrives best if languages get out of your way and development environments submerge you in a sea of live objects [Ung07]. A survey by Tiobe Software, a software-quality consultancy that maintains an index of programming languages’ popularity, says C, C++ and Java are the most popular. However, it also indicates that dynamically typed languages’ adoption has increased recently [Pau07]. By comparing the quality of development environments, or software tools, from those available for statically typed languages and those available for dynamically typed languages, it’s no wonder the former group has a higher adoption rate. 2.1.1 Type Systems In computation, type systems can be classified as trackable syntactic frameworks for classifying phrases according to the kinds of values they compute [Pie02]. They are used with a programming 5
State of the Art language to help reduce bugs in computer programs [CDJ+97]. Type systems provide conceptual tools to correctly judge adequacy of certain important aspects of language definitions. For instance, informal or natural languages often fail to specify type structures in enough detail in order to allow unambiguous implementations. By extending the syntax of the language to include some sort of constraints to indicate types that can be associated to a certain value in the language, type checks can be performed to ensure consistency of programs when running. Program variables can assume different ranges of values during the execution of the program. As an example, a variable of type Int is assumed to only store values of that type throughout the entire execution life-cycle. As part of type systems, type checking can happen at different program life-cycle phases such as compile time or run time, and even combinations of those two. Programming languages where type checking happens at compile time are called statically typed or static languages. On the other hand, languages where type checking occurs at run time are called dynamically typed or dynamic languages. The latter group may not have types or have universal types that contain all possible values [CDJ+97]. These differences on programming languages nature shape the way and possible features certain software development tools can offer to end-users. 2.1.2 Static vs Dynamic Languages As stated before, static languages enforce type checking at compile time. Because of this, the whole state of a program can be checked for consistency prior to execution. This translates in higher amounts of time for a developer to write his code since he has to worry about type consistency. However, this offers a great deal of advantages when building software tools to help development because continuous compilation of the code can provide type consistency errors, rich code completion or method suggestion regarding a variable type, etc. On the other hand, as dynamic languages don’t enforce these constraints, they use late binding of types and do them at run time. Due to the lack of type restrictions, this may translate in less worries for the programmer when coding and may result in lower amounts spent on type consistency and more time spent on creativity. In terms of performance however, dynamic languages are considerately slower in execution due to high amounts of type checking when executing a program. Statically typed languages end up with large amounts of code lines as opposed to dynamic languages. Lower amounts of code is very appealing to programmers, procedures with several lines of code can sometimes be reduced to a single line. And while it may be appealing to any developer, when building large software systems, the possibility of having a huge number of code lines of dynamic languages can be maintenance nightmares [Yeg08] because they don’t have static types. From the mainstream’s perspective, dynamically typed languages have finally come of age [Tra09]. They are used to build widely used real-world systems, often for the web, but increasingly 6
State of the Art for domains that were previously the sole preserve of statically typed languages (e.g. [KG07]), often because of lower development costs and increased flexibility [MM90,Nor92]. 2.1.3 Software Development Environments There are different taxonomies for tools that help programmers develop code. These tools can range from small tool-sets used by a single developer to full-on, complex environments that helps managing and coordinate large software development teams. Software Development Environments (SDE) are large sets of tools that support the coding process as well as any other related software development activities. They usually offer a GUI- based environment with all sorts of functionalities from creating projects, to editing source code files, managing library dependencies, compiling and running the code as well as debugging it and sometimes deploying it. 2.1.3.1 Integrated Development Environments Integrated Development Environments (IDE) can be classified as SDEs. An IDE is software that helps programmers with many stages of software development process. IDEs contain all functionalities of those described for SDEs and in some cases, they are even richer, containing interpreters, version control systems, GUI construction tools, etc. They provide a helpful abstraction regarding the needed configuration to piece together all steps into a cohesive unit and as complex systems, there is more than one application running simultaneously that are perceived by the end-user as just one single program. IDEs for statically typed languages are very mature and very capable of increasing productivity [Jav10]. Usually an IDE is bound to a specific programming language, matching the language paradigm to the available feature set, although there are multi-language IDEs. Type checking at compilation time paves way to a huge set of useful information that can be gathered while the programmer is typing his code. Everything that is to know about a certain variable like related methods or applicable operations can be detected continuously and result in rich code suggestion/completion to the end-user, among other features. Rich refactoring, specially in a project-wide range can be provided as well when using static languages. As such, IDEs for statically typed languages have been evolving since their dawn and they almost offer everything a programmer needs to efficiently improve software development. Sadly, in comparison, software development tools for dynamic languages do not show the same maturity and do not offer as much features as those available for static languages. Due to not enforcing type consistency at compilation time, information about variable types can only be obtained when running the program and inspecting it’s state. This results in little information available when the programmer is typing his code. So, what features does one IDE for a dynamic language should have? Ted Leung [Leu08] describes such tools with the need to support most refactoring described in the book “Refactoring: 7
State of the Art Improving the Design of Existing Code” [Fow99] while still maintaining performance and a small footprint. Bernstein wrote on the relevance of dynamic debuggers for dynamic languages [Ber10]. The gap on the quality IDEs offer for developing with static and dynamic languages is wide due to, we believe, applying the same design concepts that were created to solve problems in a static context. Common IDE features like static code analysis in dynamically typed languages are possible but are unable to completely solve programmer’s basic needs such as project-wide refactoring, auto-complete, advanced debugging techniques or advanced error detection. Understanding dynamic types [ACPP89] is very hard, if not impossible, to analyze through static parsing. Is it possible, to bring the dynamism from dynamic languages to statically typed languages? 2.1.3.2 Live Development Environments Live Development Environment (LDE) concepts are not, per se, a new idea. They have been around since the early days of reflective languages. In 1996 Squeak, an IDE for the programming language Smalltalk, offered a fully reflective environment with real live objects, where the IDE is part of the runtime environment of the applications it hosts [Squ12]. This approach and principles offered a new reality for programming with Smalltalk. Smalltalk is a reflective, object-oriented, dynamically typed programming language that originated in 1972. Squeak was built on top of a Smalltalk Virtual Machine (VM) and provides a fully portable, self-hosted development environment for the language. It can be used for a wide range of projects from multimedia applications, educational platforms to commercial web application development. This IDE provided a live system, so there is no need to lengthy recompilation and restart. Anything you modify will be compiled and take effect immediately. Implementing the development environment in a reflective and dynamic language allows to leverage the runtime infra-structured to assist on typical IDE functionalities, and gives the programmer an environment where creating, modifying and running code are no longer separated activities. Bracha claims that with a dynamic IDE, or a somewhat LDE, we can have live and inspectable code, opposed to dead compiled code from static contexts [Bra08], hence the name Live Development Environment. Squeak provides the best example of what a live development environment should be. But, why do current software development tools for programming with dynamic languages still lack maturity when comparing them to those for static languages? We believe that such a gap comes from applying principles that work on static contexts, in statically typed languages, to dynamic contexts from dynamic languages. For example, in a static context, an IDE can easily inspect (without actually running) the program for structural components, such as classes, methods, fields, and thus it can acquire a complete model from it. This is paramount to provide accurate code-completion functionalities as well as refactoring facilities. Dynamic languages do not share the same rationale. Coupled with an extensive native usage of meta-programming, as to say, manipulating structural and behavioral elements during runtime, 8
State of the Art IDEs for dynamic languages have been uncommon, and surely not on par with respect to modern expectations. Without executing the program from a dynamic language code, it would be undecidable to list, for example, the methods available for the programmer to invoke in the context of a certain class. As to overcome these problems, the LDE would have to gain knowledge of the executing environment, thus becoming an integral part of the runtime infrastructure. The program would have to be, partially, executed while it was being written. 2.1.4 Read-Eval-Print Loop As a type of live environments, Read-Eval-Print Loops (REPL) are known as an interactive toplevel environments. They are simple and interactive. Usually the term is used to refer to a Lisp interactive environment, however it can be applied to command line shells or similar environments. The name comes from the names of the original Lisp primitive functions which enable this functionality, namely: 1. read responsible for accepting expressions from the user and parse it into some data structure. 2. eval responsible for evaluating the internal data structure, result of the read function. 3. print responsible for printing out the result of the eval function. If complex, it may be pretty-printed making it easier to understand. Providing quick feedback to the user, REPLs often come as an essential part of learning a new programming language. REPLs can be seen as live environments, where the user continuously submits expressions to be evaluated and the system’s state is iteratively evolving with no need for re-evaluating previous expressions. They don’t, however, allow for insertion of than one expression in a continuously evaluation process. It is possible to input several expressions at once but they will only be evaluated when the programmer triggers the end of that code block. One can argue if REPLs are truly live systems or rather a tight background evaluation cycle, however, from a programmer’s coding perspective, they can be perceived as actual live environments. Powerful tools that they are, REPLs are not suitable environments for building large software systems with several source files and dependencies between them, as well as external libraries or components. 2.1.5 Reflection Reflection can be shortly defined as the property of a system that allows to observe and alter its own structure or behavior during execution. Brian Smith in 1982 first introduced the notion of computational reflection in programming languages in his doctoral dissertation [Smi82] and we 9
State of the Art Scripster Dynamic injection of code No Graphical output on data structures No Create new conversions Possible because it is for Scala, but would not be rendered as graphics Intent Web application designed to be an online code editor for Scala, evaluating lines or chunks of code Table 2.3: Feature analysis on Scripster 2.3 Summary From researching the state of the art on this dissertation’ context, we’ve learned that Integrated Development Environments are very mature tools and capable of providing many improvements on programmer’s productivity. However, these tools apply best for statically typed languages where user code is compiled and then executed. With new additions of code having to be re-compiled and executed again. And generally these tools don’t support dynamic execution of code during runtime. As to Live Development Environments, the concept is still growing and eventually we will have highly capable and mature tools for programming with dynamic languages. With a good example in Adobe Brackets, for instance. We’ve also learned that some tools for development, implement dynamic execution of code by means of an interpreting approach, like a simple REPL does. On another topic, some of these tools provide graphical representations of data structures, which is the main focus of this dissertation. Normally associated with more technical or mathematical computation, these tools enrich the visualization of data by powerful graphics and widgets. These visualizations are however, explicitly invoked by the end-user, which is not the case for Visual Scala, where the goal is implicit conversions. We can safely conclude that no tool exists that does exactly what Visual Scala aims to do. There are environments which convert data to graphics, but not in an implicit way. They also don’t allow for new conversions to be created, whereas Visual Scala does. 16
State of the Art Figure 2.3: Example of using the Julia Language to visualize mathematical plots The Julia Language Dynamic injection of code Yes Graphical output on data structures Yes Create new conversions No Intent Dynamic language for technical computing, offering an interpreter-like component for entering code and see it render graphically Table 2.4: Feature analysis on Julia Language 17
State of the Art Figure 2.4: Screenshot of an execution trace from Online Python Tutor Online Python Tutor Dynamic injection of code No Graphical output on data structures Yes Create new conversions No Intent Powerful web application for visualizing the execution trace of Python code. Data structures have graphical visualizations and they change as we iterate through the code’s execution Table 2.5: Feature analysis on Online Python Tutor 18
Chapter 3 Designing Visual Scala The main goal is to explore the flexibility of Scala’s implicits towards an extensible live environment. In order to do so, successfully implementing and simulating such an extensible and live environment was necessary so we could, in fact, explore the flexibility of Scala’s implicits. The current chapter tours over the design process that took place before implementing Visual Scala. This chapter will be covering the necessary requirements as well as a higher-level architecture and several decisions when tackling some issues. Although it might seem that this process followed a linear approach to development starting with designing, requirements outlining, implementation, etc., a circular iterative process in which all development phases were repeated as many times necessary to correctly refine and optimize Visual Scala. 3.1 Requirements At the starting point for almost every software development are requirements. Key traits and features Visual Scala should have were discussed and outlined and the resulting requirements were grouped into two categories: functional and usability. Functional requirements refer to those that are part of Visual Scala’s core. They are absolutely essential because as the name suggests, they provide functionality. Usability requirements refer to those specific to the usage of Visual Scala, they define overall features and interaction of the end-user with the system. 3.1.1 Functional At the core of Visual Scala are important requirements like: •Dynamic evaluation of user code during runtime of the system; We want to the development environment to be live, and as to achieve it we needed to dynamically execute user code during runtime of the system. Some tools researched provide this functionality, like Simply Scala,Scala Worksheet and The Julia Language. •Extensible resource libraries of graphical conversions; 19
Designing Visual Scala We want Visual Scala’s conversions library to grow easily with the help of the community. By placing the conversions library on the resources of the web server, new additions or changes do not represent a new re-compilation and initialization of the system. We want to provide an easy way for end users to send new conversions that they think are worthy of being part of the system. We found no evidence that state of the art artifacts allow for this contributions. •Convert Scala’s type values to HTML visual representations; We want Scala’s native type values and data structures to have an implicit conversion to an HTML representation. Since there is no product that offers visual representations of Scala’s types, this trait distinguishes our project from the rest. •Create new conversions during runtime, without the need for restarting; We want Visual Scala to allow for new conversions to be created by users during runtime. Either by using a form which helps users to create them or by directly submitting code for new conversions, we want to extend the conversions library throughout Visual Scala’s usage without the need for re-compilations or restarting the system. No related tool was found that provides this functionality, making our project innovative. •Online REPL in order to target more users and avoid installations and download times; We want a development environment that can target many users and avoid them having to download and install Visual Scala. The web offers a portable environment ensuring that every user is using the most up-to-date system, allowing as well for easier sessions sharing and cooperative usage. Other researched tools offer an online environment, like Simply Scala,Online Python Tutor,The Julia Language and Scripster. •Multiple users accessing the web server; As to provide an individual evaluation session for an end user, we need Visual Scala to allow access for multiple users. By instantiating a new interpreter session for each user, other user’s code will not interfere with each other’s environment state. Almost every tool found that is web based offer this functionality, being a standard requirement. They seem like few requirements but these are the ones considered core features, from which everything else is constructed and derived. 3.1.2 Usability From an usability standpoint, several requirements were also discussed and outlined in order to begin to fully envision the GUI component for interacting with Visual Scala’s backend. And so, as a user I must be able to: 1: Submit code for evaluation;2: Interact with the system in a command-line fashion;3: Whilst typing, hitting Enter should insert a newline if the instruction is not complete;4: Navigate 20
Designing Visual Scala through the history of submitted instructions with the up and down arrow keys;5: Collapse and show the graphical visualization of a result;6: Keep an history of previous results on the output body;7: See the list of available conversions for a certain result type;8: See all active conversions; 9: Edit any source file of the conversions library;10: Revert changes made on those source files; 11: Create new conversions during runtime;12: Refresh the web page and keep previous results; 13: Possibly interact with graphical visualizations and create new values from changes. 3.2 The approach In the previous section the reader learned about the requirements that were established for the implementation of Visual Scala. Besides requirements, once a more general view of what needed to be done was clearly set, settling several decisions needed to be done. These decisions range from what should be the high-level architecture of the system, communication protocols, technologies to be used, programming languages, etc. 3.2.1 Methodology In section 1.2 we introduced some research methodologies. Regarding this dissertation’s nature and hypothesis we followed an Engineering Method, where we developed a solution to test a set of hypothesis. The implementation process followed an interactive and incremental methodology, in which the solution was refined and re-designed/re-developed in order to better meet the dissertation’ goals. 3.2.2 Decisions Let’s review some of the decisions made regarding the design of Visual Scala. 3.2.2.1 High-Level Architecture As a way to target more users, avoiding downloads, installations or updates, Visual Scala was intended to be a web application. As a result, the environment must follow a client-server system model. Client Server Model This model is an approach to computer network programming, being prevalent in computer networks. Widely used, Email, the World Wide Web as well as network printing all apply the client-server architecture principles. The goal of this model is to assign two roles to computer/nodes of a system: client or server. Aserver acts as a system that aims to selectively share resources, perform computation or other services. A client acts as a system which goal is to initiate contact with the server and request resources, computation, etc. The Client-Server model allows for multiple clients to access the same server at the same time. 21
Designing Visual Scala The two-way exchange of messages/data is a request-response messaging pattern. Clients and servers exchange request and response messages via, usually, HTTP requests through a network. In light of this model, every browser acts a client and our Scala backend as the server. Figure 3.1 depicts the system’s parts and how they interact. Figure 3.1: Visual Scala’s high-level architecture In the following sections we’ll present some decisions regarding both nodes of Visual Scala’s system. 3.2.2.2 Backend As the goal is to explore flexibility of Scala’s Implicits towards an extensible live environment, the programming language to implement the system’s backend was quite clear, Scala. There was no need for implementing the Web Server in another language and then to invoke Scala modules for evaluating user code and the Conversions mechanism. And so, everything in the backend is implemented with Scala. As a key component of every client server model, it is necessary to implement a Scala web server to receive and send HTTP requests. Building one from scratch was not an option and so a decision on which Scala web framework to work with was necessary. They were several options available, like Scalatra, the Play Framework, Unfiltered, Bowler, Socko Web Server, among many others. Lacking previous experience with Scala, some experiences were made with different web frameworks but Unfiltered (You can read more about Unfiltered in section 4.6) was the choice due to its obvious simplicity. So, the web server was to be implemented using Unfiltered. What about dynamic user code evaluation? Would we write a compiler/interpreter for Scala? There was no actual need for this, since there are already available implementations for evaluating Scala code. At first Twitter’s Eval library was considered a viable option, which offers an extensive 22
Designing Visual Scala API for dynamically evaluating Scala code. We tried it, but results lacked behind expectation and it lead us to trying out a smaller GitHub project named ScalaInterpreterPane (You can read more about ScalaInterpreterPane in section 4.6), that offered an API for forking standard Scala’s interpreters with an abstraction layer for manipulating results from interpretations. Despite its limitations, as it does not provide a way of evaluating several expressions and obtaining result objects for each result produced, it was quite simple to use and provided a nice way of evaluating user code. And so, forking new instances of the Scala interpreter and dynamically evaluating user code is done using ScalaInterpreterPane. Upon tackling the most important features of Visual Scala, the design of Visual Scala’s backend architecture began its process. Visual Scala’s presents a quite simple and small architecture. It is composed of three main components, namely, the Web Server, the Evaluation module and a Miscellaneous module for general purpose procedures. The conversions library is part of the system’s resources as it is not part of the running backend. Each component’s implementation will be discussed in chapter 4. Figure 3.2 shows the architecture of Visual Scala’s backend with the typical flow of interactions between the different classes when evaluating user code, the typical interaction. Figure 3.2: Diagram representing Visual Scala’s backend architecture with the typical flow of interactions 3.2.2.3 Frontend The backend for our system was to be implemented in Scala, but what about the frontend? Earlier from the start we wanted Visual Scala to be a web application since there are many popular JavaScript libraries that enable more convenient data manipulation [jQua,Pro13,too13, Wic09]. By supporting HTML, CSS and JavaScript libraries we believe we can power the creation of graphical representations of data more easily than graphical Java libraries like Swing. It also 23
Designing Visual Scala makes it easy for users to try it out since no installations or regular updates are required. With a simple way to integrate new conversions onto the environment and with a support for different existing graphical libraries we believe the community can easily expand the system. Web applications can create a bigger impact on the community and Visual Scala will walk amongst the World Wide Web. Regarding the design of the GUI component, at first, inspired by Scala Worksheet (You can read more about Scala Worksheet in section 2.2), we wanted to have a file editing interaction, where end users would write in a code editor area and the evaluation would take place automatically. However, regarding issues of detecting starting and ending points of expressions and other issues associated with continuous evaluation, we felt it was best to approach a command-line fashion. By simulating a typical Interpreter environment, in which users type expressions one at a time, we achieved faster results towards implicitly converting data structures and Twitter’s Bootstrap (You can read more about Twitter’s Bootstrap in section 4.6) made it easy and elegant to implement the GUI component of Visual Scala. 3.3 Summary In this chapter the reader had a chance to read about the design process of Visual Scala. From requirements to high-level architecture and to specific decisions regarding both frontend and backend were also discussed. The system is rather simple as it does not present a complex architecture. The idea was pretty much straightforward, to develop a bridge to a background Web server running standard Scala interpreters to evaluate user code. Regarding the Scala server, apart from evaluating user code as is, only a component for acting as a type value’s conversions library was to be designed. The main issues relied on allowing for such a conversions library to be part of the running interpreter, and thus, be extensible while the user is playing around with it. Liveness was easily achieved following an command-line approach which made easy the use of the default Scala interpreter to evaluate user code and produce output. 24
Chapter 4 Implementation The previous chapter described the requirements and the design process of the project. The current chapter will detail the implementation process of the dissertation’ project. Elements such as the system’s architecture, API, protocols, etc, will be presented and described. The project followed an incremental process with several approaches that were tested regarding the Web app frontend. However, only the final solution will be target of discussion. We’ll start by presenting the high-level architecture of Visual Scala and detailed descriptions of both frontend and backend components of the system. Section 4.2 will explain how the frontend was implemented as well as an overview on its GUI component. The backend node, its architecture and detailed description of each of its component will be presented in section 4.3. The conversions library explanation, how Scala’s implicits work and how the conversion are actually implemented are covered in section 4.3.3 and 4.4, respectively. We’ll continue on by listing the implemented conversions on some Scala’s type values in section 4.5 and finish this chapter by presenting the technologies used, in section 4.6. 4.1 High-Level Architecture The system’s architecture follows a simple client-server approach, as previously discussed in section 3.2.2.1, having different clients accessing resources from a Web server. Every browser acts as a single client, issuing requests to the Web server, be it the main page or code evaluations and the respective obtained result. From here on out, we will be referring to the Server as the Backend and to the Client as the Frontend. 4.2 Frontend (HTML/CSS/JavaScript) The frontend, or a client, of this system consists of any device with an active network connection and a browser. The browser issues a GET request of the main page from the Web server and it engages on an active Scala development environment session. 25
Implementation For the first and most common interaction, which is type Eval, the evaluation process is not straightforward. Once user typed code is received on the Web server, is it sent over to the Evaluation module which will interpret the code and return a result. Three different phases define the evaluation process and are represented in Figure 4.5. Figure 4.5: Diagram representing the different stages of the evaluation process Phase One starts out by simply interpreting the user’s code as is. The code is submitted to the target interpreter and evaluated by using ScalaInterpreterPane’s API. We then gather the result’s identifier and move on to phase two. Phase Two in which we inspect the result type and if it matches some pre-defined types we need to apply additional operations to it. As an example, if the obtained result is an instance of a Scala Iterable, we want to slice it. Since the default toHtml conversion for Iterable’s is a paginated list, we don’t want to show a big number of elements and so we slice the Iterable to a fixed, pre-established size. After that or if no pre-conversion operations are needed for the type value of the result we move on to phase 3. Phase Three corresponds to the last phase, in which we invoke the toHtml method on the result’s identifier. The invocation on the identifier from Phase 1 or 2 is submitted to the target interpreter via the ScalaInterpreterPane’s API. The conversion result is sent over to the Web server which will, in turn, encapsulate it in an HTML element and send it over to the user’s browser. 4.3.2.2 Conversion Process The HTML element that encapsulates the result from the standard evaluation contains a list of other possible conversion for that result. Say, res0 has a conversion option called to Binary Tree. When the user explicitly asks for that conversion (using the dropdown list View as) the frontend issues a request of type Partial. The Web server detects the type Partial and that this results in a conversion for an existing result and invokes the code received. Since it is a new visualization for a previous result, there is no 32
Implementation need to build a full response to be appended to the main output body on the client’s page. Instead, only the graphical visualization code resulting from invoking the desired operation is returned in order to replace the previous visualization on that same result. 4.3.2.3 New Conversion New conversions are represented by the type New in the messages received by the Web server. Although designed for new conversion, this behavior is used for either new conversions or new changes on conversions files. This is because the main aspect of such a procedure is to submit code for evaluation on the target interpreter and produce no HTML responses. The goal is to simply submit code for evaluation and if successful, reply with SUCCESS or FAILURE. The frontend only needs to know if such an operation was successful or not so it can inform the end-user. 4.3.3 Conversions Library The Conversions library contains Scala source files that define different graphical conversions for Scala type values. This library is the most important component of the project, because without it it would just be an online web version of a typical Scala interpreter, just like Simply Scala. Each source file should contain only the conversions for a specific type value. This fragmentation is important to separate conversions so the end user can select which source files to load onto the interpreter. This library is easily extensible by editing the existing source files or by adding new ones. The library is part of the backend system’s resources and thus, there is no need to re-compile new changes in the sources. A conversion file should follow a specific structure, explained further down. Figure 4.6 shows a draft of a valid conversion file. Figure 4.6: Example of a valid Conversion library source file for Map conversions All conversion source files must declare a new object, with no special requirements for its name. The object must contain an implicit definition of a method, again with no restrictions to its name, that receives the value type for conversion, as a parameter. This method must return an object which will contain the definition of the different conversions to be applied. Although it has been presented now as an anonymous object with no specific traits or classes, in section 4.4.3 we will cover the necessary changes to add recursiveness in conversions. Regarding this 33
Implementation solution example, no recursiveness is implied in the conversion process, so a composite type like List[List[Int]] would not convert the inner lists. The standard conversion applied by default is called toHtml and in Figure 4.6 we can see toHtml converting the Map to an HTML defined table. Any number of conversions can be included in the implicit method that will, later on, be presented to the user as possible conversions. You will learn more about Scala’s implicits and how conversions work on section 4.4. 4.4 Scala’s Implicits As part of the conversions library, one aspect worth mentioning and detailing is the mechanism which allows for implicitly converting a Scala type value into an HTML representation. In this section we’ll start by explaining what Scala’s implicit keywords are and what they do as well as how we used it to elegantly solve our problem at hand. 4.4.1 Scala’s implicit conversions From Programming in Scala: A Comprehensive Step-by-step Guide, written by one of Scala’s creator, Martin Odersky [OSV08]: There’s a fundamental difference between your own code and libraries of other people: you can change or extend your own code as you wish, but if you want to use someone else’s libraries, you usually have to take them as they are. Scala’s answer is implicit conversions and parameters. These can make existing libraries much more pleasant to deal with by letting you leave out tedious, obvious details that obscure the interesting parts of your code. Used tastefully, this results in code that is focused on the interesting, non-trivial parts of your program. So, how do implicits2work? Implicit conversions are often helpful for working with bodies of software that were developed independently, without each other in mind. Libraries have different ways of encoding a concept that is often essentially the same thing. Implicit conversions come to help reducing explicit conversions that are needed from one type to another. We’ll take a look at a possible use case for implicit conversions. Let’s say you are implementing your own version of a print method called printty that receives a String and it outputs it somewhere. Also, let’s say you want to call printty without having to explicitly converting certain type values to Strings. By using Scala implicit keyword you can define a method that converts one type value to a String. Like this: 1implicit def intToString(x: Int) = x.toString 2There are implicit conversions and implicit parameters, this section will only cover implicit conversions as they were the only ones used. 34
Implementation In this example you are simply calling the toString operation on your Int parameter but you can do whatever you like inside it to achieve the type value you want as a result. The previously defined method intToString implicitly converts any Int to String whenever you provide Ints to methods which require Strings. And so, if you went on defining an implicit conversion for every type value you want your printty method, you would simply need to call printty(3),printty(4.5), etc, and have your parameter be implicitly converted to a String without you having to call toString on every parameter. This powerful Scala feature works as follows. Every time an expression, for example x+y doest not type check, then the Scala compiler might try and change it to convert(x) + y,x + convert(y) or a combination of both, where convert is an available implicit conversion. And so, if convert changes xinto something that has a +method, then this can fix the type check inconsistency detected earlier. Various rules apply to the correct use of implicits3[OSV08]. So, whenever the compiler sees an X, but in turns needs an Y, it will look for an implicit conversion that turn X into a Y. As in the previous example described earlier, you don’t need to explicitly call for conversions as the compiler implicitly applies them for you, if they exist. 4.4.2 Visual Scala implicit conversions In Visual Scala, the goal was to create implicit conversions for Scala’s type values to HTML representations to be displayed in a web application. Providing just a single conversion for a certain type seems limiting and poor, so we wanted to have many possible conversions for the same type value to different HTML representations. To achieve this, we followed a different approach as to simple implicit functions that convert one type value to an HTML representation. And as to fragment the conversions library into separate source files containing all conversions for a specific type value, we define Scala objects to contain our implicit conversions. At every result from evaluating user code, before sending it over to the web application frontend, we invoke a toHtml method to convert it to HTML. This is the default implicit conversion on certain type values. Although the Evaluation module of our Web server calls this conversion explicitly, from a end-user perspective, this conversion is made implicitly. We could have done this in an entirely implicit way but for having multiple conversions for one type value, implicitness would end past the default conversion toHtml. Let’s take a look at an example of a set of conversions for Scala’s Lists. 1object ListConversions { 2implicit def fromList[A](list: List[A]) = new Object { 3def toHtml = <ul>{ list.map( x => <li>{ x }</li> ) }</ul> 4def toOrderedList = <ol>{ list.map(x => <li>{ x }</li>) }</ol> 3You can learn all about implicits and their rules in the book Programming in Scala: A Comprehensive Step-by-step Guide 35
Implementation 5} 6} In this example, we start by declaring an object called ListConversions4which shall contain only one implicit function declared inside it. We make use of Scala’s keyword implicit to define the conversion function fromList[A]5. This function is parameterized to accept different types of Lists, like List[Int],List[Double], and so on. If we wanted to restrict the conversion for certain sub-type of Lists we could do so by explicitly defining the values contained in such Lists. Last, but not least, all there was left was to define one or multiple conversions for List. The implicit function returns a new object which will define our conversions. In the example, we have defined two conversions: the default toHtml, to be called by the Evaluation module, and a toOrderedList which converts the input List to an HTML ordered list. Once the conversions objects for multiple type values are coded, the Evaluation module injects, as to say submits their code for evaluation, all conversion objects onto the interpreter session configured for the end-user. After that, it imports them to the interpreter’s environment, like import ListConversions._. Once that is done, the Evaluation module can invoke toHtml or toOrderedList on Lists and obtain the desired conversion. The power of Scala’s implicits provided us with a an, we could say, elegant way of defining multiple conversions and for the Evaluation module to ignore the type value at hand and simply call toHtml letting the Scala’s compiler find the appropriate toHtml to be applied. 4.4.3 Recursive Conversions Sometimes is interesting and useful to provide recursive conversions on certain data types. Consider for example a Map[Int,List[Int]] which maps Ints to List[Int], in this case, we might want to convert the map to an HTML table but instead of simply verbosely displaying the Lists in the table we may want to convert them as well. Also, we wanted to apply this recursiveness in an flexible manner, without explicitly searching for certain data types and re-define their conversions inside this one. This is not feasible and thus it is necessary to implement a mechanism for recursive conversions by only invoking toHtml on each value that is being inserted into the conversion. Consider the following example of such a mechanism: 1implicit def fromMap[A,B](m: Map[A,B]) = new Object { 2def toHtml = (table code...) { m.map(e => <tr> <td> { toHtml(e._1) } </td> <td> { toHtml(e._2) } </td> </tr>) } (more table code...) 3} 4There are no restrictions for naming these objects. Any name can be used. 5Again, no restrictions apply for naming as long as the method takes the desired type value as a parameter. 36
Implementation If we were to implement the recursiveness like the previous example the Scala compiler would throw a compilation error saying that types Aand Bdo not have the toHtml method, which makes perfect sense. And so, there is a need to, instead of returning an anonymous object like (...) = new Object (...) , to return an object that the compiler knows it implements the toHtml method. To achieve it, we can define a Scala trait for the returned object, like this: 1trait HTML[T] { 2def toHtml(obj: T): String 3} With this trait, we are creating something like Java’s interfaces, in which we are stating that an HTML object must implement his version of the toHtml method. And so, we go on by defining a general invocation of the toHtml with the implicitly keyword. And of course, the new implicit conversion method would return this new object type, like this: 1def toHtml[A: HTML](a: A) = implicitly[HTML[A]].toHtml(a) 2 3implicit def fromMap[A: HTML, B: HTML] = new HTML[Map[A,B] { 4def toHtml(m: Map[A,B]) = (table code...) { m.map(e => <tr> <td> { toHtml(e. _1) } </td> <td> { toHtml(e._2) } </td> </tr>) } (more table code...) 5} With this approach, the compiler does not throw any error and can safely call the toHtml method on inner values of the Map. As a result, if the Map was to contain, inside it, other Maps would be converted as well. 4.4.3.1 Recursive Conversions Limitations When we want flexible and elegant recursiveness some limitations were found. On section 4.4.3 we exposed how implicit recursiveness can be implemented. We are talking about recursiveness that is not explicitly explored, one can simulate recursiveness by exhaustively perform pattern matching on every element of a composite data type and apply different conversions regarding its type. This works but it’s not flexible nor elegant. In section 4.4.3 we presented a solution that involves traits. This solution works quite well when we are only considering that data types will have only one conversion, the default toHtml. Every result of the implicit conversions yields an object that shares the trait we have stated earlier, for example trait HTML. In this trait we are declaring that an object of this type must implement a method called toHtml. With this we are able to recursively invoke toHtml on inner types of composite types. Consider the following example of such a mechanism. 1trait HTML[T] { 2def toHtml(obj: T): String 37
Implementation 3} 4 5def toHtml[A: HTML](a: A) = implicitly[HTML[A]].toHtml(a) 6 7implicit def fromList[A: HTML] = new HTML[List[A]] { 8def toHtml(lst: List[A]) = <ul> { lst.map(e => <li> { implicitly[HTML[A]]. toHtml(e) } </li>) } </ul> toString 9} With this example we are defining a trait HTML that defines object which implement the method toHtml which receives any type and produces a String. We move on to define how to call toHtml with the implicitly declaration and finally define the implicit conversion on List. This conversion yields an object HTML which implements toHtml as a unordered HTML list. As we are invoking toHtml on every inner value of our parameter List, if such a List were to contain other Lists, they would in turn be converted as well. This is elegant and provides a short way of working around recursiveness. This approach has however, some disadvantages. It is necessary to define conversions for every type that could be contained in List, like Int,Double,String, etc., even if it is simply calling toString. One way around is to define the conversion for Any which maps to every Scala type value. This disadvantage results in a bigger amount of conversions code to be injected in the target interpreter, resulting in a higher loading time. Another disadvantage arises when we want to define multiple conversions for the same type and not just toHtml. If we were to define just one trait as we did before, and add it another conversion, like: 1trait HTML[T] { 2def toHtml(obj: T): String 3def toOrderedList(obj: T): String 4} This would result in having to define the toOrderedList on possible inner types, as for types like Int or Double this conversion does not make sense. Of course we could always overcome this by defining those conversions as simply calling toString on those types but it feels like redundant and unnecessary code. A different approach to this could be defining different traits for certain types, like trait ListHTML and trait SimpleHTML but we wouldn’t be able to parameterize the parameters on the implicit functions. 4.4.4 Flexibility of Scala’s Implicits Visual Scala’s conversions basically consists on functions that, when provided with certain inputs, generates Strings containing HTML code that, complemented with JavaScript, represent in 38
Implementation graphical manners, the provided input. Almost every programming language can implement such functions. But how to correctly apply each conversion function to specific native type values? 4.4.4.1 Conversions without Scala’s Implicits In possibly every programming language, there are conditional statements, usually referred to as If then else which provide ways of conditionally executing behavior when certain conditions are true, or false. Regarding such conditional control mechanisms, a conversion library can be built using Ifs. We would have to check if results are instances of certain type values and if so, apply the correct conversion functions. Apart from object-oriented programming languages where programs are sets of functions that define behavior, functions with the same name are not allowed and so if we wanted to have the same toHtml function to convert both Integers and Doubles, for example, we would have to give them different names, like toHtmlInt or toHtmlDouble. This restriction is quite annoying. Such an approach would like this (in pseudo-code): 1if resultType == Int then 2toHtmlInt(result); 3elseif resultType == Double then 4toHtmlDouble(result); 5else (...) As an alternative, other common conditional statements like switch (in Java), usually referred to as pattern matching could be used. It is basically the same as using Ifs but in a more elegant and concise way. Such an approach would like this (in pseudo-code): 1switch(resultType) { 2case Int: toHtmlInt(result); 3case Double: toHtmlDouble(result); 4(...) 5} Of course this approach implies that we need to obtain resultType as a textual, or in other format, representation of the result’s type value. This seems feasible for simple types like Int but what if there are parameterized types, like List[Int] or List[String]? Or even List[List[Int]]? We start to reach the conclusion that such an approach is not flexible at all. We would have to exhaustively list every possible type value to be converted, which is not practical, and a very painful and error-prone mechanism. In object-oriented languages, we could define Objects that encapsulate different conversions methods. We could have methods with the same name, like toHtml, but we would still have to inspect the result’s type and explicitly call the appropriate method. Consider the following code as an example of the same approach, but in an object-oriented domain. 39
Implementation 1switch(resultType) { 2case Int: IntConversions.toHtml(result); 3case Double: DoubleConversions.toHtml(result); 4(...) 5} Well, we have surpassed naming the same conversion with different names but we’re still with an ugly mechanism for type detection and conversion invocation. This is where Scala’s implicits do their magic and provide an exceptionally flexible way of correctly invoking the appropriate conversion depending on the input type value. If you don’t recall how Scala’s implicits work you can read about it in section 4.4. 4.4.4.2 Conversions with Scala’s Implicits With Scala’s implicits, because the compiler checks for implicit conversions available for converting the input type value, a lot of work is done in an abstract way and away from the programmers eyes. After correctly defining and declaring implicit conversions (as explained in section 4.3.3), we can simply invoke conversions functions like this (in Scala code): 1val list = List(1,2,3,4) 2 33.toHtml() 4(1 to 10).toHtml() 5list.toHtml() Because every value is an object in Scala, and because the compiler searches for the correct implicit conversion to apply, it is this simple to invoke conversions on identifiers without worrying about pre-detecting the identifier’s type. As explained in section 4.3.2.1, the conversion process of Visual Scala simply calls toHtml on the resulting identifier from evaluating expressions. This is highly flexible. If we want more conversions we simply need to define more methods and invoke them when necessary without having to expand a type-detecting mechanism presented in the first example, turning it into an unmanageable and huge control sequence that would need to be re-compiled or re-evaluated every time a new conversion is added. As such, Scala’s implicits offer highly flexible ways of invoking methods according to specific types. Figure 4.7 shows an example of such flexibility in action. Scala’s implicit conversions are flexible when defining conversions for different data types. It is not possible for defining multiple conversions with the same name for the same type value. Although possible to define, When faced with ambiguity, the Scala compiler does not randomly invokes one of the conversion and instead throws an error message saying that conversions are ambiguous when invoking the methods. Figure 4.8 shows such behavior in action. 40
Implementation Figure 4.7: Example of the flexibility of Scala’s implicits conversions 4.4.4.3 Conversions hierarchy When dealing with parameterized type values, like List or Map, it is probably a best practice to define implicit conversions for the different sub-types for these data structures. It is possible to define general applicable conversions by parameterizing the input type values, as List[A] or Map[A,B], however, sometimes the conversion we want to define does not apply to all possible sub-types. We may want to define an implicit conversion that makes sense for List[Int] but not for List[String]. Scala’s implicits provide a flexible way of overcoming this by allowing to define parameterized conversions and more specific conversions and according to the input type value, Scala’s compiler invokes the most specific method. Figure 4.9 shows such a mechanism in action. With this, the programmer can define multiple conversions for the same type value in different object, by controlling the exact conversions desired for the correct sub-types, without worrying with such a detection on general applicable conversions. 4.5 Implemented Conversions In the previous sub-section we learned about the Conversions Library component of the Backend system and how it is structured. We saw a small example of a valid conversion source file for converting Scala’s Maps to HTML tables and now we are going to present every conversion that was implemented as well as their results and difficulties. Conversions are grouped and are to be presented according to the Scala’s type value they convert. 4.5.1 Iterable[A] Scala’s Iterables are collection classes that provide method elements which return iterators over all the elements contained in the collection. The goal for converting Iterables was to 41
Implementation Figure 4.16: Screenshot showing the toPieChart conversion on Scala’s Maps. Cookies and deliver the results through HTTP. 4.6.1.2 ScalaInterpreterPane ScalaInterpreterPane7is a Swing component for editing code in the Scala programming language and executing it in an interpreter. It offers an API to either instantiate a full GUI component containing a code editing section with the associated output results from the interpreter, as well as instantiating the separate parts. ScalaInterpreterPane forks new Scala’s Read-Eval-Print Loops with a top-level abstraction API for executing code and control results. This is helpful because we only needed a simple way of creating new instance of interpreters as well as an easy way to inspect results, regarding the obtained identifiers and result values. As such, every instance of Scala’s interpreters used in Visual Scala are created through ScalaInterpreterPane’s API. ScalaInterpreterPane was developed by Hanns Holger Rutz and released under the GNU Lesser General Public License. 7Free open-source project available at https://github.com/Sciss/ScalaInterpreterPane Figure 4.17: Screenshot showing the default toHtml conversion on Scala’s Strings. 48
Implementation 4.6.2 JavaScript, CSS and HTML 4.6.2.1 jQuery jQuery is one of the most famous JavaScript libraries [Sur13], simplifying client-side scripting of HTML. It aims for a rapid development simplifying a wide range of operations like HTML document traversing, event handling, animations and AJAX interactions. Stating their website jQuery is designed to change the way that you write JavaScript [jQua]. Capabilities for creating plug-ins on top of the JavaScript library are also available and there are many jQuery plug-ins to choose from. This library is used for creating abstractions for low-level interactions and animation. The standard operations of editing, creating and removing DOM elements are implement through jQuery quickly using the selector API implement according to the CSS selectors specification [jQub]. Maitaining and editing the DOM tree of the HTML page as well as all AJAX requests are done by jQuery. One plug-in is used, the jQuery Autosize plug-in to enable automatic height for textarea elements by Jack Moore.8 jQuery is free, open source software and licensed under the MIT License [jQu13]. 4.6.2.2 Bootstrap Twitter’s Bootstrap is a free collection of software tools containing HTML and CSS-based design templates for typography, buttons, forms, and other interface components, providing rapid development of websites or web applications. Advanced features like the grouping of buttons, buttons with drop-down lists, navigation, pagination, labels, advanced typographic capabilities thumbnails, formattable warning messages and progress bar comprise of a subset of the full potential of Bootstrap. It also contains JavaScript components that are based on the jQuery JavaScript library for additional user-interface elements such as dialogs, carousels, tooltips, drop-down, etc. At its heart, Bootstrap is just CSS, but it’s built with Less, a flexible pre-processor that offers much more power and flexibility than regular CSS [Dev11]. It is the most popular project in GitHub [Git13], compatible with all major browsers. This library is used to style the main elements that are used for rendering the user-interface from the main interpreter output, labels, result boxes, collapsing result boxes and modal forms to the page title. 4.6.2.3 D3, Data Driven Documents Data-Driven Documents, or D3, is a JavaScript library for displaying data as dynamic graphical representations. It is the successor of the previous Protovis9framework. 8You can read more about jQuery Autosize plug-in at http://www.jacklmoore.com/autosize 9You can read more at http://mbostock.github.com/d3/tutorial/protovis.html 49
Implementation The library, embedded within an HTML page, uses pre-built functions creating SVG elements, style them, add transitions or other dynamic effects. Standard CSS styling can also be applied to these SVG elements. The data that is rendered can come in various formats, most commonly JSON, CSV, geoJSON, however, any format suits as long as the developer writes code that can convert it to supported ones. This is the probably the most important library used in this dissertation. The abstraction level it provides allows for a more painless way to create graphical visualizations for HTML, allying with extensive documentation and examples. D3 also allows for a deeper control over the the final visual result [Via12]. D3’s core contribution is a visualization “kernel” rather than a framework [BOH11]. The project’s development environment needs to be easily extensible and we believe that with the popularity of D3 and the amount of tutorials and examples, users can quickly contribute with more Scala type values graphical conversions. 4.6.2.4 Session.js Session.js is a JavaScript script that implements cookie-less JavaScript session variables. Used for storing and accessing variables that stay persistent throughout refreshes on the web page. Only when either the tab or browser is closed the session’s variables are lost. It has a very simple API comprising only four interactions. Session.set(name, object) stores a new object under the key name on the session. Consequently Session.get(name) returns the object stored under the provided key. The remaining operations are Session.dump() which returns the entire session variable with all it’s values and Session.clear() which erases all contents. The main purpose for using Session.js was to preserve previous results on the web page whenever the user refreshed it. Although all history is preserved server-side, if the user accidentally refreshed the web page, regarding client-side, all contents would be lost. And so, we keep track of the “instruction counter”, every previous result object as well as the instructions history for navigating previous instructions submitted by the user. 4.7 Summary In this chapter we described the implementation process of Visual Scala. Visual Scala consists of a Client-Server system, in which the client side, or frontend, is a web application, implemented with standard web technologies: HTML, CSS and JavaScript. The server side, or backend, is written entirely in Scala implementing a web server responsible for managing HTTP requests as well as an evaluation module responsible for evaluating user code. The conversions library is part of the backend, however, it is a resource of the Scala evaluation module, as their sources are not compiled when building the system’s backend. A comprehensive overview of the technologies used is presented, regarding programming languages used, frameworks/libraries used and other open-source projects available for use. 50
Chapter 5 Conclusions In this dissertation, we started by looking into the current state of the art regarding software development environments and related tools. This broad and more generalized research grew more and more specific regarding systems that provide data structures visualization and dynamic execution of code during runtime. From that research, we learned that several work has been done in data visualization systems. However, these systems do not offer dynamism when executing user code, lengthy re-compilations and restarts are needed. This static approach makes such systems “closed” during execution, one is able to develop code that, when compiled, is executed and produces graphical outputs. This is not what we wanted. Because those same systems were implemented using statically typed languages which generally struggle to provide that dynamic behavior, however, Visual Scala was implemented with a statically typed language, Scala, and provides the dynamism that we wanted. In our vision to walk towards live development environments, we needed a system that could be dynamically injected1with code to be executed during runtime. Some examples were found that can be classified as live systems, detailed in section 2.2, where user code is evaluated as the programmer is typing it. Environments or tools which offered graphical representations of data structures were also found but none was found that could offer both. For example, Online Python Tutor (see section 2.2.5) provides great graphical visualizations on data structures throughout the execution trace of Python code, but does not provide a live environment for programming in Python, while still providing graphical representations of data. Julia (see section 2.2.4), provides a typical command-line interaction in which the programmer submits one expression at a time and see them evaluated and if applicable, a graphical visualization of the produced output. But while very powerful, specially regarding performance, Julia’s goal is to be used for technical computing, in a more mathematical context and does not enable end-users to create new graphical conversions. From this research we felt confident that our vision for Visual Scala was truly innovative. 1As to say, submit code to be dynamically executed during runtime. 51
Conclusions 5.1 Summary of Hypotheses This dissertation’ fundamental research question can be described as: Can Scala’s Implicits provide a flexible and elegant way of implementing a conversions library for different Scala’s native type values? What advantages or disadvantages arise from using such a mechanism? What lessons can we learn from it? From decomposing the main research topic other hypotheses and goals were obtained. The following list summarizes other hypotheses: •H1: Can Scala’s Implicits provide a flexible mechanism for converting data structures? •H2: Can such a mechanism integrate a development environment for Scala? •H3: Can such an environment provide a means to dynamically execute user code during runtime? •H4: Can such an environment be easily extensible for new user-defined conversions? Even during runtime? 5.2 Main Results From the previous list of hypotheses, the following items summarize the obtained results regarding each hypotheses and goal. •H1 Can Scala’s Implicits provide a flexible mechanism for converting data structures? Scala’s Implicits can, in fact, provide a flexible mechanism of converting Scala’s type values into rich HTML representations. The lessons learned about this flexibility and results obtained are explained in more detail in section 4.4.4. •H2 Can such a mechanism integrate a development environment for Scala? Yes, the conversions mechanism represents the whole Conversions library implemented in Visual Scala. The results obtained from integrating such a library into an online development environment and the implemented conversions are presented in detail in section 4.5. •H3 Can such an environment dynamically execute user code during runtime? Yes, one of the goals was to develop an environment which could be seen as a live environment. By using Scala’s standard interpreters for evaluating user code, Visual Scala can dynamically execute user code during runtime, in a sandboxed environment provided by the Java Virtual Machine. 52
Conclusions •H4 Can such an environment be easily extensible for new user-defined conversions during runtime? Yes, the implemented conversions library is part of Visual Scala’s resources folder. As explained in section 4.3.3, the conversions library are a set of Scala source files containing the conversions methods for different data structures. The code from these source files is injected onto the target interpreter session for the end-user. Because of this approach the user can define new conversions through the use of a form, explained in section 4.2, and the code is injected onto the interpreter without the need for a re-compilation or restart. Changes and additions to the conversions library resource folder is also possible during runtime of the system because they are not part of the actual running code. We can safely conclude that Visual Scala is easily extensible. 5.3 Contributions This dissertation research and development has provided with some contributions to the community. State of the Art on LDEs This dissertation researched the current state of the art on Live Development Environments. They are not, clearly, a new idea, however they are still a working concept. LDEs do not possess an highly evolved maturity when comparing with IDEs, possibly because of the dynamic typing nature they have to tackle. Smalltalk, from 1996 is probably the best example of what a truly LDE would aim to be but no advances were made on bringing Smalltalk’s features onto modern dynamic languages. Still, some good examples like Light Table or Adobe’s Brackets might be a new future for LDEs. Online LDE/REPL architecture for Scala We have contributed with a simple architecture for an online Live Development Environment/Read-Eval-Print Loop for the Scala programming language. Based on the standard Scala’s REPL, Visual Scala results in an extensible architecture for a web application to simulate an approach of a LDE. Implementing such an architecture From the architecture designed, this dissertation implemented that same architecture and successfully deployed Visual Scala to the Web. It contributed with a working web application that dynamically evaluates user code and converts data structures to rich graphical representations. Visual Scala can have different impacts and contributions for the community from helping beginners to better understand data structures and computation concepts to even serve as a collaborative tool for code development. Conversion Library We have successfully developed an easily extensible and highly flexible Conversions Library that convert different Scala’s native type values to rich, interactive HTML graphical representations. This library is easily extensible as it is not part of the running system’s backend, located on the system’s resources. It can serve as a case study for 53
Conclusions the elegant flexibility Scala’s Implicits provide when implementing mechanisms of invoking implicit conversions on data structures. Open-Source code Visual Scala’s code is open-source and made available for the community on GitHub. It is available at https://github.com/vascogrilo/LDE. Article for the CDVE This dissertation overall work on Visual Scala resulted in a draft article for submission on the 10th International Conference on Cooperative Design, Visualization & Engineering. We believe that with session sharing among different client’s, Visual Scala can become a great tool for collaborative and cooperative development of algorithms and data structures as well as discussion or particular snippets of code. 5.4 Lessons Learned Not everything in Software Engineering can be properly evaluated with the six-month time window that we were given to development of this dissertation. In order to correctly prepare and engage in controlled experiments with programmers using Visual Scala, it would take a least a year to gather meaningful results and opinions. As a result, we can only go so far as detailing the lessons learned from exploring this tool we have developed. Visual Scala, as expected, turned out to be an extensible live environment for the Scala programming language. From the implementation process of this web application we took some remarks, we learned that such a conversion component has many powerful advantages and benefits but also some disadvantages. 5.4.1 Advantages One advantage we feel Visual Scala can offer is a better understanding environment for beginners in programming, or computer science. With the visual representations of data structures, and often interactive as well, we believe Visual Scala can help beginners in their understanding of computation concepts, specially regarding data structures. The author remembers his path when learning to program, and his first programming language experience was Haskell and if such a similar tool was available for Haskell, many concepts would have been quicker to grab and the experience would be richer. And so we believe Visual Scala has many advantages regarding to the learning curve and experience of programming and programming in Scala. Unfortunately, there was no sufficient time to conduct quasi-experiments with controlled audiences and because of this we cannot state with certainty that Visual Scala really helps productivity or understanding but we do believe it can. Specially in collaboration, with that feature on the list of future work, session sharing with other users can help collaborative development and teaching. Apart from impacts it may have on the end-user, Visual Scala has other advantages. Its conversion library is easily extensible. Since this library is part of the backend resources and not part of the running web server, one change to the conversions library doesn’t require recompilation and execution of the web server. The contents of the library are simply loaded onto every new interpreter session and so, every changes made can take effect immediately. Even if 54
Conclusions we’re talking about extending the already loaded conversion in a specific session, it is quite simple because the user can do it freely during runtime, and the backend can do it as well since it only requires to submit code to be evaluated by the target interpreter. From this we can see that Visual Scala is highly extensible. The environment supports dynamic evaluation of user code during runtime. This provides a key aspect for interaction, as the user continuously types expressions for evaluation and see them being interpreted and converted to “widgets”. Because of this REPL-like approach, Visual Scala appeals for quicker and more interactive interactions, discarding some, sometimes, boring steps of compilation and execution triggering by the end-user. Specially when compared to an approach of having to edit a file-like code editor and trigger the evaluation of the entire source file. This would result in a static context of usage, where the user would make new changes and see the backend system re-evaluate previous expressions, or if he was to erase the contents and develop some new code he would lose all previous work. And so, the command-line approach seemed better for achieving the purpose of liveness. 5.4.2 Disadvantages As a web application, with a backend system responsible for user code evaluation, Scala code that performs I/O operations are not recommended. Every print or println method will print whatever the user specifies to the backend system’s log files. In order to provide to the user the results from these operations, the backend would have to read output files and send the contents to the frontend. Not only from prints but every I/O operation like file manipulation, etc., is not the intended use for Visual Scala. These operations result in side-effects on server side and since the client’s browser is on another separate system, the desired outcomes are not achieved. Another disadvantage of the conversions library is that all conversions code must be injected, i.e., evaluated by the target Scala interpreter so it can be available to the users. As the conversions library grows in size, so does the time needed for the target interpreter to evaluate its code. This presents an ugly bottleneck on performance and speed of configuration of the interpreting session for end-users. Currently Visual Scala injects all conversions code onto the target interpreter which takes a few seconds before the main page can be presented to the user. However, this can be fixed by forking a new interpreter, presenting the main page to the user, and have a thread injecting in a parallel fashion, the conversions code. That way the user can get the main page in a quick way. Other approach would be for the user to select which conversion modules he wants active on the interpreter session, adding them one by one. 5.4.3 Flexibility of Scala’s Implicits Please refer to section 4.4.4 for an extensive discussion on the flexibility of Scala’s implicit conversions regarding the implementation of the conversion mechanism. 55
Conclusions 5.5 Use Cases Scenarios Despite the mail goal was to explore the flexibility of Scala’s Implicits towards an Extensible Live Environment for Scala, this dissertation contributed with a successful project named Visual Scala, online and working. Visual Scala can have different applications/usages, or use cases scenarios. For one, Visual Scala can act as a standard interpreter for Scala, as an online version. We believe it can also create a significant impact on the community with its flexible and extensible conversions library. By turning abstract data structures into rich, interactive HTML representations, a programmer can better understand, manipulate and reason about certain data structures and effects of algorithms. A beginner student in computation might learn in a quicker way when comparing to using other tools. On another scenario, it can be used to generate graphical representations of data to be exported for including them in external sources. For example, generating bar charts of different data for later use in some report/article, etc. Lastly, but not least, Visual Scala can act as an interesting and powerful collaborative platform for developing Scala code. Users might use it cooperatively to develop algorithms, teach other users about data structures, cooperate in implementing new graphical conversions and even discuss and reason about programming practices in Scala. 5.6 Future Work Developing every possible graphical conversion for every Scala type value was not feasible. It would take a long time as it was simply not possible during the time we had for development of this dissertation. As a result, we aimed for extensibility and we hope that, when correctly deployed and advertised, the community would help enhancing Visual Scala with graphical conversions. Although the time for this dissertation has ended, Visual Scala’s project has not. We feel like it can be an important tool and that it can have an impact on the Scala community as well as in other programming communities. We will keep on working on Visual Scala, developing more graphical conversions and some more features. Features like session sharing, where an user can evaluate some Scala code and share the current state of their session with other users using a specific URL. Other users would open up that URL and see the current state from the other developer and the environment would be shared among the two users, or more, eventually. This can help collaboration between Scala programmers. General optimizations are also on the checklist for future work as we want Visual Scala to be as robust as it can be. Also, since we feel it can have a large impact on the community, we will be working on turning Visual Scala into an online cooperative development environment for Scala. Through session sharing, we want for multiple users to share the same interpreting session and develop 56
Conclusions Scala code, discuss code, collaboratively develop new conversions, and learn Scala with the help of others. The author will be working with the supervisors and possibly with a team of developers who may want to take on Visual Scala from here on out. 57