tuprolog with exceptions

Similar documents
Part I Logic programming paradigm

tuprolog Manual tuprolog version: 2.5 Enrico Denti Alma Mater Studiorum Università di Bologna, Italy September 20, 2012

What needs to be kept track of ffl The current substitution ffl The current goal ffl The clause currently in use ffl Backtrack Information 2

Implementação de Linguagens 2016/2017

Operational Semantics

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

Software Testing Prof. Meenakshi D Souza Department of Computer Science and Engineering International Institute of Information Technology, Bangalore

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

Chapter 16. Logic Programming. Topics. Unification. Resolution. Prolog s Search Strategy. Prolog s Search Strategy

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

Information technology - Programming languages - Prolog - Part 1: General Core

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Lecture 21: Relational Programming II. November 15th, 2011

BCS THE CHARTERED INSTITUTE FOR IT. BCS Higher Education Qualifications BCS Level 6 Professional Graduate Diploma in IT EXAMINERS' REPORT

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

This lecture covers: Prolog s execution strategy explained more precisely. Revision of the elementary Prolog data types

Table : IEEE Single Format ± a a 2 a 3 :::a 8 b b 2 b 3 :::b 23 If exponent bitstring a :::a 8 is Then numerical value represented is ( ) 2 = (

The tupinjade package

Object-Oriented Design Lecture 21 CSU 370 Fall 2008 (Pucella) Tuesday, Dec 9, 2007

COMPUTER SCIENCE TRIPOS

CSCI0330 Intro Computer Systems Doeppner. Lab 02 - Tools Lab. Due: Sunday, September 23, 2018 at 6:00 PM. 1 Introduction 0.

CMSC 331 Final Exam Section 0201 December 18, 2000

Programming Languages Third Edition. Chapter 10 Control II Procedures and Environments

Lecture 9: Parameter Passing, Generics and Polymorphism, Exceptions

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

More Non-logical Features of Prolog

CAP 5602 Summer, Lesson 4: Loops. The topics 1. the cut and some of its uses 2. the while loop 3. the do until loop

COP4020 Fall 2006 Final Exam

CS112 Lecture: Exceptions and Assertions

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 11

A second life for Prolog

Lecture 2: SML Basics

Information technology Programming languages Prolog Part 1: General core

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

Fall 2017 CISC124 9/16/2017

6.821 Programming Languages Handout Fall MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Compvter Science


CS4215 Programming Language Implementation

Chapter 14. Exception Handling and Event Handling ISBN

Maciej Sobieraj. Lecture 1

Chapter 7 Control I Expressions and Statements

Lecture Overview Code generation in milestone 2 o Code generation for array indexing o Some rational implementation Over Express Over o Creating

INTRODUCTION TO PROLOG

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore

Course on Artificial Intelligence and Intelligent Systems. A short introduction to CHR and its application for rule-based expert systems

Lecture 11: Feb. 10, 2016

1. true / false By a compiler we mean a program that translates to code that will run natively on some machine.

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

R13 SET Discuss how producer-consumer problem and Dining philosopher s problem are solved using concurrency in ADA.

Debugging and Handling Exceptions

C++ Programming: From Problem Analysis to Program Design, Third Edition

Composable Shared Memory Transactions Lecture 20-2

On the BEAM Implementation

Sardar Vallabhbhai Patel Institute of Technology (SVIT), Vasad M.C.A. Department COSMOS LECTURE SERIES ( ) (ODD) Code Optimization

Supplemental Handout: Exceptions CS 1070, Spring 2012 Thursday, 23 Feb 2012

mywbut.com Exception Handling

The Procedure Abstraction

1007 Imperative Programming Part II

Type Systems, Type Inference, and Polymorphism

#using <System.dll> #using <System.Windows.Forms.dll> using namespace System; using namespace System::Windows::Forms;

Numerical Precision. Or, why my numbers aren t numbering right. 1 of 15

CS Introduction to Data Structures How to Parse Arithmetic Expressions

Programming II (CS300)

CS 3L (Clancy) Solutions and grading standards for exam 1

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

Infinite Derivations as Failures

Logic Programming and Resolution Lecture notes for INF3170/4171

Faculty of Electrical Engineering, Mathematics, and Computer Science Delft University of Technology

APCS Semester #1 Final Exam Practice Problems

Research on the Novel and Efficient Mechanism of Exception Handling Techniques for Java. Xiaoqing Lv 1 1 huihua College Of Hebei Normal University,

CS 321 Homework 4 due 1:30pm, Thursday, March 15, 2012 This homework specification is copyright by Andrew Tolmach. All rights reserved.

3.1 DATA REPRESENTATION (PART C)

And Parallelism. Parallelism in Prolog. OR Parallelism

17 CIF Converter Tools

The Idea Underlying Logic Programming. CSci 8980, Fall 2012 Specifying and Reasoning About Computational Systems An Introduction to Logic Programming

Prolog. Intro to Logic Programming

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)

COMP2411 Lecture 20: Logic Programming Examples. (This material not in the book)

Object-Oriented Principles and Practice / C++

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

Chapter 3 Structured Program Development

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

6.001 Notes: Section 6.1

Backtracking. Backtracking. Backtracking. Backtracking. Backtracking. Backtracking. Functional & Logic Programming - Backtracking October, 01

Defensive Programming

Lecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

CSE Theory of Computing Fall 2017 Project 1-SAT Solving

Compiler Theory. (Semantic Analysis and Run-Time Environments)

Pace University. Fundamental Concepts of CS121 1

Testing Exceptions with Enforcer

Programming Languages and Compilers Qualifying Examination. Answer 4 of 6 questions.

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

Absolute C++ Walter Savitch

Transcription:

tuprolog with exceptions Enrico Denti December 16, 2010 Abstract This document describes the new support for ISO Prolog exceptions in tuprolog 2.2. Please notice that this document is not intended to replace a tutorial nor a full manual about exception support in Prolog: rather, it means to provide a short yet effective reference to the exception support added in this tuprolog version. 1 Exceptions in ISO Prolog The ISO Prolog standard (ISO/IEC 13211-1) has been published in 1995. Among the many additions, it introduces the catch/3 e throw/1 constructs for exception handling. The first distinction has to be made between errors and exceptions. An error is a particular circumstance that interrupts the execution of a Prolog program: when a Prolog engine encounters an error, it raises an exception. The exception handling support is supposed to intercept the exception and transfer the execution flow to a suitable exception handler, with any relevant information. Two basic principles are followed during this operation: error bounding an error must be bounded and not propagate through the entire program: in particular, an error occurring inside a given component must either be captured at the component s frontier, or remain invisible and be reported nicely. According to ISO Prolog, this can be done via the catch/3 predicate. atomic jump the exception handling mechanism must be able to exit atomically from any number of nested execution contexts. According to ISO Prolog, this is done via the throw/1 predicate. In practice, throw(error ) raises an exception, while the controlled execution of a goal is launched via the catch(goal, Catcher, Handler ) predicate, which is very much like the try/catch construct of many imperative languages. Here, Goal is first executed: if an error occurs, the subgoal where the error occurred is replaced by the corresponding throw(error ), which raises the exception. Then, a matching catch/3 clause that is, a clause whose second argument unifies with Error is searched among the antenate nodes in the resolution tree: if one is found, the path in the resolution tree is cut, the catcher itself is removed (because it only applies to the protected goal, not to the handler), and the Handler predicate is executed. If, instead, no such matching clause is found, the execution simply fails. So, catch(goal, Catcher, Handler ) performs exactly like Goal if no exception are raised: otherwise, all the choicepoints generated 1

by Goal are cut, a matching Catcher is looked for, and if a one is found then Handler is executed, maintaining the substitutions made during the previous unification process. In the very end, the execution continues with the subgoal which follows catch/3. However, any side effects possibly occurred during the execution of a goal are not undone in case of exceptions, exactly as it normally happens when a predicate fails. Summing up, catch/3 is true if: call(goal ) is true; or call(goal ) is interrupted by a call to throw(error ) whose Error unifies with Catcher, and the subsequent call(handler ) is true; If Goal is non-deterministic, it can obviously be executed again in backtracking. However, it should be clear that Handler is possibly executed just once, since all the choicepoints of Goal are cut in case of exception. 1.1 Examples As a first, basic example, let us consider the following toy program: p(x):- throw(error), write( --- ). p(x):- write( +++ ). and let us consider the behaviour of the program in response to the execution of the goal:?:- catch(p(0), E, write(e)), fail. which tries to execute p(0), catching any exception E and handling the error by just printing it on the standard output (write(e)). Perhaps surprisingly, the program will just print error, not error--- or error+++. The reason is that once the exception is raised, the execution of p(x) is aborted, and after the handler terminates the execution proceeds with the subgoal which follows catch/3, i.e. fail. So, write( --- ) is never reached, nor is write( +++ ) since all the choicepoints are cut upon exception. In the following we report a small yet complete set of mini-examples, thought to put in evidence one single aspect of tuprolog compliance to the ISO standard. Example 1: Handler must be executed maintaining the substitutions made during the unification process between Error and Catcher Query:?- catch(p(0), E, atom length(e, Length)). Substitutions: E/error, Length/5 Example 2: the selected Catcher must be the nearest in the resolution tree whose second argument unifies with Error p(1). Query:?- catch(p(1), E, fail), catch(p(0), E, true). 2

Substitutions: E/error Example 3: execution must fail if an error occurs during a goal execution and there is no matching catch/3 predicate whose second argument unifies with Error Query:?- catch(p(0), error(x), true). Answer: no. Example 4: execution must fail if Handler is false Query:?- catch(p(0), E, false). Answer: no. Example 5: if Goal is non-deterministic, it is executed again on backtracking, but in case of exception all the choicepoints must be cut, and Handler must be executed only once Program: p(0). p(1) :- throw(error). p(2). Query:?- catch(p(x), E, true). Substitutions: X/0, E/error Choice: Next solution? Substitutions: X/1, E/error Choice: Next solution? Answer: no. Example 6: execution must fail if an exception occurs in Handler Query:?- catch(p(0), E, throw(err)). Answer: no. 1.2 Error classification So far we have just said that, when an exception is raised, throw(error ) is executed, and a matching catch/3 is looked for, but no specifications have been given about the possible structure of the Error term. According to the ISO Prolog standard, such a term should follow the pattern error(error term, Implementation defined term ) where Error term is constrained by the standard to a pre-defined set of possible values, in order to represent the error category: Implementation defined term, instead, is left for implementationspecific details, and could also be omitted. The error classification induced by Error term is flat, so as to easily support pattern matching. Ten error classes are identified by the ISO standard: 1. instantiation error: when the argument of a predicate or one of its components is a variable, while it should be instantiated. A typical example is X is Y+1 if Y is not instantiated when is/2 is evaluated. 3

2. type error(validtype, Culprit ): when the type of an argument of a predicate, or one of its components, is instantiated, but nevertheless incorrect. In this case, ValidType represents the expected data type (one of atom, atomic, byte, callable, character, evaluable, in byte, in character, integer, list, number, predicate indicator, variable), while Culprit is the wrong type found. For instance, if a predicate operates on dates and expects months to be represented as integers between 1-12, calling the predicate with an argument like march instead of 3 would raise a type error(integer, march), since an integer was expected and march was found instead. 3. domain error(validdomain, Culprit ): when the argument type is correct, but its value falls outside the expected range. ValidDomain is one of character code list, close option, flag value, not empty list, not less than zero, io mode, operator priority, operator specifier, prolog flag, read option, source sink, stream, stream option, stream or alias, stream position, stream property, write option. In the example above, a domain error could be raised if, for instance, a value like 13 was provided for the month argument. 4. existence error(objecttype, ObjectName : when the referenced object to be accessed does not exist. Again, ObjectType is the type of the unexisting object, and ObjectName its name. ObjectType is procedure, source sink, or stream. If, for instance, the file usr/goofy does not exist, an existence error(stream, usr/goofy ) would be raised. 5. permission error(operation, ObjectType, Object ): when Operation is not allowed on Object, which is of type ObjectType. Operation is one of access, create, input, modify, open, output, or reposition, while ObjectType falls among binary stream, operator, past end of stream, private procedure, static procedure, source sink, stream, flag, and text stream. 6. representation error(flag ): when an implementation-defined limit, whose category is given by Flag, is violated during execution. Flag is one of character, character code, in character code, max arity, max integer, min integer. 7. evaluation error(error ): when the evaluation of a function produces an exceptional value. Accordingly, Error is one of float overflow, int overflow, undefined, underflow, zero divisor. 8. resource error(resource ): when the Prolog engine does not have enough resources to complete the execution of the current goal. Typical examples are the reach of the maximum number of opened files, no further available memory, etc. Accordingly, resource error(resource) can be any valid term. 9. syntax error(message ): when external data, read from an external source, have an incorrect format or cannot be processed for some reason. This kind of error typically occurs during read operations. Message can be any valid (simple or compound) term describing the occurred problem. 4

10. system error: this latter category represents any other unexpected error which does not fall in any of the above categories. 2 Implementing Exceptions in tuprolog Implementing exceptions in tuprolog does not mean just to extend the engine to support the above mechanisms: given its library-based design, and its intrinsic support to multi-paradigm programming, adding exceptions in tuprolog has also meant (1) to revise all the existing libraries, modifying any library predicate so that it raises the appropriate type of exception instead of just failing; and (2) to carefully define and implement a model to make Prolog exceptions not only coexist, but also fruitfully operate with the Java (or C#/.NET) imperative world, which brings its own concept of exception and its own handling mechanism. As a preliminary step, the finite-state machine which constitutes the core of the tuprolog engine was extended with a new Exception state, between the existing Goal Evaluation and Goal Selection states. Then, all the tuprolog libraries were revised, according to clearness and efficiency criteria that is, the introduction of the new checks required for proper exception raising should not reduce performance unacceptably. This issue was particularly relevant for runtime checks, such as existence errors or evaluation errors; moreover, since tuprolog libraries could also be implemented partly in Prolog and partly in Java, careful choices had to be made so as to introduce such checks at the most adequate level in order to intercept all errors while maintaining code readability and overall organisation, while guaranteeing efficiency. This led to intervene with extra Java checks for libraries fully implemented in Java, and with new Java guards for predicates implemented in Prolog, keeping the use of Prolog meta-predicates (such as integer/1) to a minimum. With respect to the third aspect, which will be discussed more in depth below, one key aspect to be put in evidence right now concerns the handling of Java objects accessed from the Prolog world via Javalibrary. At a first sight, one might think of re-mapping Java exceptions and constructs onto the Prolog one, but this approach is unsatisfactory for three main reasons: the semantics of the Java mechanism should not be mixed with the Prolog one, and vice-versa; the Java construct admits also a finally clause which has no counterpart in ISO Prolog; the Java catching mechanisms operates hierarchically, while the catch/3 predicate operates via pattern matching and unification, allowing for multiple granularities. For these reasons, supporting Java exceptions from tuprolog programs called for two further, ad hoc predicates which are not present in ISO Prolog because ISO Prolog does not consider multi-paradigm programming: java throw/1 and java catch/3. 2.1 Java exceptions from tuprolog The java throw/1 predicate has the form 5

java throw(javaexception (Cause, Message, StackTrace )) where JavaException is named after the specific Java exception to be launched (e.g., java.io.filenotfoundexception, and its three arguments represent the typical properties of any Java exception. More precisely, Cause is a string representing the cause of the exception, or 0 if the cause is unknown; Message is the message associated to the error (or, again, 0 if the message is missing); StackTrace is a list of strings, each representing a stack frame. The java catch/3 predicate takes the form java catch(jgoal, [(Catcher1, Handler1 ),..., (CatcherN, HandlerN )], Finally ) where JGoal is the goal (representing a Java operation in the Java world) to be executed under the protection of the handlers specified in the subsequent list, each associated to a given type of Java exception and expressed in the form java exception(cause, Message, StackTrace ), with the same argument semantics explained above. The third argument Finally expresses the homonomous Java clause, and therefore represents the predicate to be executed at the very end either of the Goal or one of the Handler s. If no such a clause is actually needed, the conventional atom ( 0 ) has to be used as a placeholder. The predicate behaviour can be informally expressed as follows. First, JGoal is executed. Then, if no exception is raised via java throw/1, the Finally goal is executed. If, instead, an exception is raised, all the choicepoints generated by JGoal (in the case of a non-deterministic predicate like java object bt/3, of course) are cut: if a matching handler exists, such a handler is executed, maintaining the variable substitutions. If, instead, no such a handler is found, the resolution tree is backsearched, looking for a matching java catch/3 clause: if none exists, the predicate fails. Upon completion, the Finally part is executed anyway, then the program flow continues with the subgoal following java catch/3. As already said above, side effects possibly generated during the execution of JGoal are not undone in case of exception. So, summing up, java catch/3 is true if: JGoal and Finally are both true; or call(jgoal ) is interrupted by a call to java throw/1 whose argument unifies with one of the Catcher s, and both the execution of the catcher and of the Finally clause are true. Even if JGoal is a non-deterministic predicate, like java object bt/3, and therefore the goal itself can be re-executed in backtracking, in case of exception only one handler is executed, then all the choicepoints generated by JGoal are removed: so, no further handler would ever be executed for that exception. In other words, java catch/3 only protects the execution of JGoal, not the handler execution or the Finally execution. 2.2 Examples First, let us consider the following program: 6

[( java.lang.classnotfoundexception (Cause, Msg, StackTrace), write(msg))], write(+++)). which tries to allocate an instance of Counter, bind it to the atom c, and if everything goes well print the +++ message on the standard output. Indeed, this is precisely what happens if, at runtime, the class Counter is actually available in the file system. However, it might also happen that, for some reason, the required class is not present in the file system when the above predicate is executed. Then, a java.lang.classnotfoundexception (Cause, Msg, StackTrace) exception is raised, no side effects occur so, no object is actually created and the Msg is printed on the standard output, followed by +++ as required by the Finally clause. Since the Msg in this exception is the name of the missing class, the global message printed on the console is Counter+++. In the following we report a small yet complete set of mini-examples, thought to put in evidence one single aspect of tuprolog compliance to the ISO standard. Example 1: the handler must be executed maintaining the substitutions made during the unification process between the exception and the catcher: then, the Finally part must be executed. [( java.lang.classnotfoundexception (Cause, Message, _), X is 2+3)], Y is 2+5). Substitutions: Cause/0, Message/ Counter, X/5, Y/7. Example 2: the selected java catch/3 must be the nearest in the resolution tree whose second argument unifies with the launched exception [( java.lang.classnotfoundexception (Cause, Message, _), true], true), java_catch(java_object( Counter, [ MyCounter2 ], c2), [( java.lang.classnotfoundexception (Cause2, Message2, _), X is 2+3], true). Substitutions: Cause/0, Message/ Counter, X/5, C/0, Message2/ Counter. Example 3: execution must fail if an exception is raised during the execution of a goal and no matching java catch/3 can be found [( java.lang.exception (Cause, Message, _), true)], true)). Answer: no. Example 4: java catch/3 must fail if the handler is false [( java.lang.exception (Cause, Message, _), false)], true)). 7

Answer: no. Example 5: java catch/3 must fail also if an exception is raised during the execution of the handler [( java.lang.classnotfoundexception (Cause, Message, _), java_object( Counter, [ MyCounter ], c))], true). Answer: no. Example 6: the Finally must be executed also in case of success of the goal?- java_catch(java_object( java.util.arraylist, [], l), [E, true], X is 2+3). Substitutions: X/5. Example 7: the Handler to be executed must be the proper one among those available in the handlers list [( java.lang.exception (Cause, Message, _), X is 2+3), ( java.lang.classnotfoundexception (Cause, Message, _), Y is 3+5)], true). Substitutions: Cause/0, Message/ Counter, Y/8. 3 Library predicates All tuprolog library predicates have been revised so as to raise the proper exceptions, instead of failing, as specified by ISO standards. Please refer to such standards for specific information on this topic. With respect to tuprolog multi-paradigm programming, supported by JavaLibrary, two further predicates have been introduced beyond the ISO standard discussed above: java throw/1 and java catch/3. These predicates work similarly to the standard throw/1 and catch/3 predicates, but refer to exceptions raised inside the Java world, instead of Prolog-raised ones. More info on this topic will be added in a future version of this document. However, some (hopefully clear) usage examples can be found in the test source file JavaLibraryExceptionsTestCase.java in the exceptions-test folder. 8