Presentation is loading. Please wait.

Presentation is loading. Please wait.

S. Haridi and P. Van Roy1 Declarative Computation Model Seif Haridi KTH Peter Van Roy UCL.

Similar presentations


Presentation on theme: "S. Haridi and P. Van Roy1 Declarative Computation Model Seif Haridi KTH Peter Van Roy UCL."— Presentation transcript:

1 S. Haridi and P. Van Roy1 Declarative Computation Model Seif Haridi KTH Peter Van Roy UCL

2 S. Haridi and P. Van Roy2 Programming A computation model: describes a language and how the sentences (expressions, statements) of the language are executed by an abstract machine A set of programming techniques: to express solutions to the problems you want to solve A set of reasoning techniques: to reason about programs to increase the confidence that they behave correctly and calculate their efficiency

3 S. Haridi and P. Van Roy3 Declarative Programming Model Guarantees that the computations are evaluating functions on (partial) data structures The core of functional programming (LISP, Scheme, ML, Haskell) The core of logic programming (Prolog, Mercury) Stateless programming vs. stateful (imperative) programming We will see how declarative programming underlies concurrent and object-oriented programming (Erlang, Java)

4 S. Haridi and P. Van Roy4 Defining a programming language Syntax (grammar) Semantics (meaning)

5 S. Haridi and P. Van Roy5 Language syntax Defines what are the legal programs, i.e. programs that can be executed by a machine (interpreter) Syntax is defined by grammar rules A grammar defines how to make ‘sentences’ out of ‘words’ For programming languages: sentences are called statements (commands, expressions) For programming languages: words are called tokens Grammar rules are used to describe both tokens and statements

6 S. Haridi and P. Van Roy6 Language syntax (2) A statement is a sequence of tokens A token is a sequence of characters A program that recognizes a sequence of characters and produces a sequence of tokens is called a lexical analyzer A program that recognizes a sequence of tokens and produces a sequence of statement representation is called a parser Normally statements are represented as (parse) trees Lexical analyzer Parser characters tokens sentences

7 S. Haridi and P. Van Roy7 Extended Backus-Naur Form EBNF (Extended Backus-Naur Form) is a common notation to define grammars for programming languages Terminal symbols and non-terminal symbols Terminal symbol is a token Nonterminal symbol is a sequence of tokens, and is represented by a grammar rule  nonterminal  ::=  rule body 

8 S. Haridi and P. Van Roy8 Grammar rules  digit  ::= 0 | 1 | 2 | 3 | 5 | 6 | 7 | 8 | 9 |  digit  is defined to represent one of the ten tokens 0, 1, …, 9 The symbol ‘ | ’ is read as ‘or’ Another reading is that  digit  describes the set of tokens {0,1,…, 9} Grammar rules may refer to other nonterminals  integer  ::=  digit  {  digit  }  integer  is defined as the sequence of a  digit  followed by a zero or more  digit  ’s

9 S. Haridi and P. Van Roy9 How to read grammar rules  x  : is a nonterminal x  x  ::= Body :  x  is defined by Body  x  |  y  : either  x  or  y  (choice)  x   y  : the sequence  x  followed by  y  {  x  } : a sequence of zero or more occurrences of  x  {  x  } + : a sequence of one or more occurrences of  x  [  x  ] : zero or one occurrences of  x  Read the grammar rule from left to right to give the following sequence: –Each terminal symbol is added to the sequence –Each nonterminal is replaced by its definition –For each  x  |  y  pick any of the alternatives –For each  x   y  is the sequence  x  followed by the sequence  y 

10 S. Haridi and P. Van Roy10 Context-free and context-sensitive grammars Grammar rules can be used to either –verify that a statement is legal, or –to generate all possible statements The set of all possible statements generated from a grammar and one nonterminal symbol is called a (formal) language EBNF notation defines a class of grammars called context-free grammars Expansion of a nonterminal is always the same regardless of where it is used For practical languages context-free grammar is not enough, usually a condition on the context is sometimes added

11 S. Haridi and P. Van Roy11 Context-free and context-sensitive grammars It is easy to read and understand defines a superset of the language Expresses restrictions imposed by the language (e.g. variable must be declared before use) Makes the grammar rules context sensitive Context-free grammar (e.g. with EBNF) + Set of extra conditions

12 S. Haridi and P. Van Roy12 Examples  statement  ::= skip |  expression  ‘=‘  expression  | …  expression  ::=  variable  |  integer  | …  statement  ::= if  expression  then  statement  { elseif  expression  then  statement  } [ else  statement  ] end | …

13 S. Haridi and P. Van Roy13 Example: (Parse Trees) if  expression  then  statement  1 else  statement  2 end conditional expressionstatement 1 statement 2 ifthenelse

14 S. Haridi and P. Van Roy14 Language Semantics Semantics defines what a program does when it executes Semantics should be simple and yet allows a programmer to reason about programs (correctness, execution time, and memory use) How can this be achieved for a practical language that is used to build complex systems (millions lines of code) ? The kernel language approach

15 S. Haridi and P. Van Roy15 Kernel Language Approach Define a very simple language (kernel language) Define the computation model of the kernel language By defining how the constructs (statements) of the language manipulate (create and transform) the data structures (the entities) of the language Define a mapping scheme (translation) of full programming language into the kernel language Two kinds of translations: linguistic abstractions and syntactic sugar

16 S. Haridi and P. Van Roy16 Kernel Language Approach Practical language kernel language Translation fun {Sqr X} X*X end B = {Sqr {Sqr A}} proc {Sqr X Y} { * X X Y} end local T in {Sqr A T} {Sqr T B} end Provides useful abstractions for the programmer Can be extended with linguistic abstractions Is easy to understand and reason with Has a precise (formal) semantics

17 S. Haridi and P. Van Roy17 Linguistic abstractions vs. syntactic sugar Linguistic abstractions, provide higher level concepts that the programmer can use to model, and reasons about programs (systems) Examples: functions ( fun ), iterations ( for ), classes and objects ( class ), mailboxes ( receive ) The functions (calls) are translated to procedures (calls) The translation answers questions about the functions: {F1 {F2 X} {F3 X}}

18 S. Haridi and P. Van Roy18 Linguistic abstractions vs. syntactic sugar Linguistic abstractions, provide higher level concepts that the programmer can use to model, and reasons about programs (systems) Syntactic sugar are short cuts and conveniences to improve readability if N==1 then [1] else local L in … end end if N==1 then [1] else L in … end

19 S. Haridi and P. Van Roy19 Approaches to semantics Programming Language Kernel Language Operational model Formal calculusAbstract machine Aid the programmer in reasoning and understanding Mathematical study of programming (languages) -calculus, predicate calculus,  -calculus Aid to the implementer Efficient execution on a real machine

20 S. Haridi and P. Van Roy20 Sequential declarative computation model The single assignment store, declarative (dataflow) variables, and values (together are called entities) The kernel language syntax The environment: maps textual variable names (variable identifiers) into entities in the store Interpretation (execution) of the kernel language elements (statements) by the use of an execution stack of statements (define control), and the store Execution transforms the store by a sequence of steps

21 S. Haridi and P. Van Roy21 Single assignment store A single assignment store is a store (set) of variables Initially the variables are unbound, i.e. do not have a defined value Example: a store with three variables, x 1, x 2, and x 3 unbound The Store x1x1 unbound x2x2 x3x3

22 S. Haridi and P. Van Roy22 Single assignment store (2) Variables in the store may be bound to values Example: assume we allow as values, integers and lists of integers unbound The Store x1x1 unbound x2x2 x3x3

23 S. Haridi and P. Van Roy23 Single assignment store (3) Variables in the store may be bound to values Assume we allow as values, integers and lists of integers Example: x 1 is bound to the integer 314, x 2 is bound to the list [1 2 3], and x 3 is still unbound The Store x1x1 x2x2 unbound x3x3 314 1 |2 |3 | nil

24 S. Haridi and P. Van Roy24 Declarative (single-assignment) variables A declarative variable starts out as being unbound when created It can be bound to exactly one value Once bound it stays bound through the computation, and is indistinguishable from its value The Store x1x1 x2x2 unbound x3x3 314 1 |2 |3 | nil

25 S. Haridi and P. Van Roy25 Value store A store where all variables are bound to values is called a value store Example: a value store where x 1 is bound to integer 314, x 2 to the list [1 2 3], and x 3 to the record (labeled tree) person(name: “George” age: 25) Functional programming computes functions on values, needs only a value store This notion of value store is enough for functional programming (ML, Haskell, Scheme) 314 1 |2 |3 | nil person “George”25 nameage The Store x1x1 x2x2 x3x3

26 S. Haridi and P. Van Roy26 Operations on the store (1) Single assignment  x  =  v  x 1 = 314 x 2 = [1 2 3] This assumes that  x  is unbound unbound The Store x1x1 unbound x2x2 x3x3

27 S. Haridi and P. Van Roy27 Single-assignment  x  =  value  x 1 = 314 x2 = [1 2 3] 314 The Store x1x1 unbound x2x2 x3x3

28 S. Haridi and P. Van Roy28 Single-assignment (2)  x  =  v  x 1 = 314 x 2 = [1 2 3] The single assignment operation (‘=‘) constructs the  v  in the store and binds the variable  x  to this value If the variable is already bound, the operation will test the compatibility of the two values if the test fails an error is raised 314 The Store x1x1 x2x2 unbound x3x3 1 |2 |3 | nil

29 S. Haridi and P. Van Roy29 Variable identifiers Variable identifiers refers to store entities (variables or value) The environment maps variable identifiers to variables declare X : local X in … ”X” is a (variable) identifier This corresponds to ’environment’ {”X”  x 1 } The Store ”X””X” Unbound x1x1

30 S. Haridi and P. Van Roy30 Variable-value binding revisited (1) The Store “X” x1x1 X = [1 2 3] Once bound the variable is indistinguishable from its value 1 |2 |3 | nil

31 S. Haridi and P. Van Roy31 Variable-value binding revisited (2) The Store “X” x1x1 X = [1 2 3] Once bound the variable is indistinguishable from its value The operation of traversing variable cells to get the value is known as dereferencing and is invisible to the programmer 1 |2 |3 | nil

32 S. Haridi and P. Van Roy32 Partial Values Is a data structure that may contain unbound variables The store contains the partial value: person(name: “George” age: x 2 ) declare Y X X = person(name: “George” age: Y) The identifier ’Y’ refers to x 2 person “George”Unbound nameage The Store “X” “Y” x1x1 x2x2

33 S. Haridi and P. Van Roy33 Partial Values (2) Partial Values may be complete declare Y X X = person(name: “George” age: Y) Y = 25 person “George”25 nameage The Store “X” “Y” x1x1 x2x2

34 S. Haridi and P. Van Roy34 Variable to variable binding  x 1  =  x 2  It is to perform the bind operation between variables Example: X = Y X = [1 2 3] The operations equates (merges) the two variables unbound The Store x1x1 unbound x2x2 X Y

35 S. Haridi and P. Van Roy35 Variable to variable binding (2)  x 1  =  x 2  It is to perform a single assignment between variables Example: X = Y X = [1 2 3] The operations equates the two variables (forming an equivalence class) The Store x1x1 x2x2 X Y

36 S. Haridi and P. Van Roy36 Variable to variable binding (3)  x 1  =  x 2  It is to perform a single assignment between variables Example: X = Y X = [1 2 3] All variables (X and Y) are bound to [1 2 3] The Store x1x1 x2x2 X Y 1 |2 |3 | nil

37 S. Haridi and P. Van Roy37 Summary Variables and partial values Declarative variable: –is an entity that resides in a single-assignment store, that is initially unbound, and can be bound to exactly one (partial) value –it can be bound to several (partial) values as long as they are compatible with each other Partial value: –is a data-structure that may contain unbound variables –When one of the variables is bound, it is replaced by the (partial) value it is bound to –A complete value, or value for short is a data-structure that does not contain any unbound variables

38 S. Haridi and P. Van Roy38 Declaration and use of variables Assume that variables can be declared (introduced) and used separately What happens if we try to use a variable before it is bound? 1.Use whatever value happens to be in the memory cell occupied by the variable (C, C++) 2.The variable is initialized to a default value (Java), use the default 3.An error is signaled (Prolog). Makes sense if there is a single activity running (pure sequential programs) 4.An attempt to use the variable will wait (suspends) until another activity binds the variable (Oz/Mozart)

39 S. Haridi and P. Van Roy39 Declaration and use of variables (2) An attempt to use the variable will wait (suspends) until another activity binds the variable (Oz/Mozart) Declarative (single assignment) variables that have this property are called dataflow variables It allows multiple operations to proceed concurrently giving the correct result Example: A = 23 running concurrently with B = A+1 Functional (concurrent) languages do not allow the separation between declaration and use (ML, Haskell, and Erlang)

40 S. Haridi and P. Van Roy40 Kernel language syntax  s  ::= skip empty statement |  x  =  y  variable-variable binding |  x  =  v  variable-value binding |  s 1   s 2  sequential composition |local  x  in  s 1  end declaration |if  x  then  s 1  else  s 2  end conditional |{  x   y 1  …  y n  } procedural application |case  x  of  pattern  then  s 1  else  s 2  end pattern matching  v  ::=... value expression  pattern  ::=... The following defines the syntax of a statement,  s  denotes a statement

41 S. Haridi and P. Van Roy41 Variable identifiers  x ,  y ,  z  stand for variables In the concrete kernel language variables begin with upper- case letter followed by a (possibly empty) sequence of alphanumeric characters or underscore Any sequence of printable characters within back-quote Examples: –X, Y1 –Hello_World –`hello this is a $5 bill` (back-quote)

42 S. Haridi and P. Van Roy42 Values and types A data type is a set of values and a set of associated operations Example: Int is the the data type ”Integer”, i.e set of all integer values 1 is of type Int Int has a set of operations including +,-,*,div, etc The model comes with a set of basic types Programs can define other types, e.g., abstract data types ADT

43 S. Haridi and P. Van Roy43 Data types Value Number Literal RecordProcedure IntIntFloat AtomBoolean TrueFalse Char Tuple List String

44 S. Haridi and P. Van Roy44 Data types (2) Value Number Literal RecordProcedure IntIntFloat AtomBoolean TrueFalse Char Tuple List String

45 S. Haridi and P. Van Roy45 Value expressions  v  ::=  procedure  |  record  |  number   procedure  ::= proc {$  y 1  …  y n  }  s  end  record ,  pattern  ::=  literal  |  literal  (  feature 1  :  x 1  …  feature n  :  x n  )  literal  ::=  atom  |  bool   feature  ::=  int  |  atom  |  bool   bool  ::= true | false  number  ::=  int  |  float 

46 S. Haridi and P. Van Roy46 Numbers Integers –314, 0 –~10 (minus 10) Floats –1.0, 3.4, 2.0e2, 2.0E2 ( 2  10 2 )

47 S. Haridi and P. Van Roy47 Atoms and booleans A sequence starting with a lower-case character followed by characters or digits, … –person, peter –‘Seif Haridi’ Booleans : –true –false

48 S. Haridi and P. Van Roy48 Records Compound representation (data-structures) –  l  (  f 1  :  x 1  …  f n  :  x n  ) –  l  is a literal Examples –person(age:X1 name:X2) –person(1:X1 2:X2) –‘|’(1:H 2:T) –nil –person

49 S. Haridi and P. Van Roy49 Syntactic sugar (tuples) Tuples  l  (  x 1  …  x n  )(tuple) This is equivalent to the record  l  (1:  x 1  … n:  x n  ) Example: person(‘George’ 25) This is the record person(1:‘George’ 2:25)

50 S. Haridi and P. Van Roy50 Syntactic sugar (lists) Lists  x 1  |  x 2  (a cons with the infix operator ‘|’) This is equivalent to the tuple ‘|’ (  x 1   x 2  ) Example: H | T This is the tuple ‘|’(H T)

51 S. Haridi and P. Van Roy51 Syntactic sugar (lists) Lists  x 1  |  x 2  |  x 3  ‘|’ associates to the right  x 1  | (  x 2  |  x 3  ) Example: 1 | 2 | 3 | nil Is 1 | ( 2 | (3 | nil )) ‘|’ 1 2 3nil

52 S. Haridi and P. Van Roy52 Syntactic sugar (complete lists) Lists Example: [1 2 3] Is 1 | ( 2 | (3 | nil )) ‘|’ 1 2 3nil

53 S. Haridi and P. Van Roy53 Strings A string is a list of character codes enclosed with double quotes Ex: ”E=mc^2” Means the same as [69 61 109 99 94 50]

54 S. Haridi and P. Van Roy54 Procedure declarations According to the kernel language  x  = proc {$  y 1  …  y n  }  s  end is a legal statement It binds  x  to a procedure value This statement actually declares (introduces a procedure) Another syntactic variant which is more familiar is proc {  x   y 1  …  y n  }  s  end This introduces (declares) the procedure  x 

55 S. Haridi and P. Van Roy55 Operations of basic types Arithmetics –Floating point numbers: +,-,*, and / –Integers: +,-,*,div (integer division, i.e. truncate fractional part), mod (the remainder after a division, e.g.10 mod 3 = 1) Record operations –Arity, Label, and ”.” –X = person(name:”George” age:25) –{Arity X} = [age name] –{Label X} = person, X.age = 25 Comparisons –Boolean comparisons, including ==, \= (equality) –Numeric comparisons, = =, compares integers, floats, and atoms

56 S. Haridi and P. Van Roy56 Value expressions  v  ::=  procedure  |  record  |  number  |  basicExpr   basicExpr  ::=... |  numberExpr  |...  numberExpr  ::=  x  1 +  x  2 |........

57 S. Haridi and P. Van Roy57 Syntactic sugar (multiple variables) Multiple variable introduction local X Y in  statement  end Is transformed to local X in local Y in  statement  end end

58 S. Haridi and P. Van Roy58 Syntactic sugar (basic expressions) Basic Expression nesting if  basicExpr  then  statement  1 else  statement  2 end Is transformed to local T in T =  basicExpr  if T then  statement  1 else  statement  2 end end T is a ’new’ variable identifier

59 S. Haridi and P. Van Roy59 Syntactic sugar (variables) Variable initialization local X =  value  in  statement  end Is transformed to local X in X =  value   statement  end

60 S. Haridi and P. Van Roy60 Kernel language syntax  s  ::= skip empty statement |  x  =  y  variable-variable binding |  x  =  v  variable-value binding |  s 1   s 2  sequential composition |local  x  in  s 1  end declaration |if  x  then  s 1  else  s 2  end conditional |{  x   y 1  …  y n  } procedural application |case  x  of  pattern  then  s 1  else  s 2  end pattern matching  v  ::=... value expression  pattern  ::=... The following defines the syntax of a statement,  s  denotes a statement

61 S. Haridi and P. Van Roy61 Kernel language syntax  s  ::= skip empty statement |  x  =  y  variable-variable binding |  x  =  v’  variable-value binding |  s 1   s 2  sequential composition |local  x  in  s 1  end declaration |if  x  then  s 1  else  s 2  end conditional |{  x   y 1  …  y n  } procedural application |case  x  of  pattern  then  s 1  else  s 2  end pattern matching | proc {  x   y 1  …  y n  }  s 1  end procedure introduction The following defines the syntax of a statement,  s  denotes a statement

62 S. Haridi and P. Van Roy62 Examples (1) local X in X = 1 end local X Y T Z in X = 5 Y = 10 T = (X>=Y) if T then Z = X else Z = Y end {Browse Z} end

63 S. Haridi and P. Van Roy63 Examples (2) local X in X = 1 end local Browse in proc {Browse X} … end local X in X = 1 {Browse X} end end

64 S. Haridi and P. Van Roy64 Procedure abstraction Any statement can be abstracted to a procedure by selecting a number of the ’free’ variable identifiers and enclosing the statement into a procedure with the identifiers as paramenters if X >= Y then Z = X else Z = Y end Abstracting over all variables proc {Max X Y Z} if X >= Y then Z = X else Z = Y end end Abstracting over X and Z proc {LowerBound X Z} if X >= Y then Z = X else Z = Y end end

65 S. Haridi and P. Van Roy65 Computations (abstract machine) A computation defines how the execution state is transformed step by step from the initial state to the final state A single assignment store  is a set of store variables, a variable may be unbound, bound to a partial value, or bound to a group of other variables An environment E is mapping from variable identifiers to variables or values in , e.g. {X  x 1, Y  x 2 } A semantic statement is a pair (  s , E ) where  s  is a statement ST is a stack of semantic statements

66 S. Haridi and P. Van Roy66 Computations (abstract machine) A computation defines how the execution state is transformed step by step from the initial state to the final state The execution state is pair ( ST,  ) ST is a stack of semantic statements A computation is a sequence of execution states ( ST 0,  0 )  ( ST 1,  1 )  ( ST 2,  2 ) ...

67 S. Haridi and P. Van Roy67 Semantics To execute a program (i.e., a statement)  s  the initial execution state is ( [ (  s ,  ) ],  ) ST has a single semantic statement (  s ,  ) The environment E is empty, and the store  is empty [... ] denotes the stack At each step the first element of ST is popped and execution proceeds according to the form of the element The final execution state (if any) is a state in which ST is empty

68 S. Haridi and P. Van Roy68 Calculating with environments E is mapping from identifiers to entities (both store variables and values) in the store The notation E(  y  ) retrieves the entity associated with the identifier  x  from the store The notation E + {  y  1  x 1,  y  2  x 2,...,  y  n  x n } –denotes adjunction: a new environment E’ constructed from E by adding the mappings {  y  1  x 1,  y  2  x 2,...,  y  n  x n } – E’(  z  ) is x k if  z  is equal to  y  k, otherwise E’(  z  ) is equal to E(  z  ) The notation E| {  y  1,  y  2,...,  y  n} denotes the restriction of the domain of E to the set {  y  1,  y  2,...,  y  n }

69 S. Haridi and P. Van Roy69 Calculating with environments (2) E = { X  1, Y  [2 3], Z  x i } E’ = E + { X  2} E’( X ) = 2, E( X ) = 1 E| {X,Y} restricts E to the ’domain’ {X,Y}, i.e., it is equal to { X  1, Y  [2 3]}

70 S. Haridi and P. Van Roy70 Calculating with environments (3) local X in X = 1(E) local X in X = 2(E’) {Browse X} end(E) {Browse X} end

71 S. Haridi and P. Van Roy71 skip The semantic statement is ( skip, E) Continue to next execution step

72 S. Haridi and P. Van Roy72 skip The semantic statement is ( skip, E) Continue to next execution step ( skip, E) ST  +  +

73 S. Haridi and P. Van Roy73 Sequential composition The semantic statement is (  s 1   s 2 , E) Push (  s 2 , E) and then push (  s 1 , E) on ST Continue to next execution step (  s 1   s 2 , E) ST  (  s 1 , E) (  s 2 , E) ST  + +

74 S. Haridi and P. Van Roy74 Variable declaration The semantic statement is ( local  x  in  s  end, E) Create a new store variable x in the Store Let E’ be E+{  x   x}, i.e. E’ is the same as E but the identifier  x  is mapped to x. Push (  s , E’) on ST Continue to next execution step

75 S. Haridi and P. Van Roy75 Variable declaration The semantic statement is ( local X in  s  end, E) ( local X in  s  end, ) ST  (  s , ) ST ’’ + + E E X = x i xixi unbound  +

76 S. Haridi and P. Van Roy76 Variable-variable equality The semantic statement is (  x  =  y , E ) Bind E(  x  ) and E(  y  ) in the store

77 S. Haridi and P. Van Roy77 Variable-value equality The semantic statement is (  x  =  v , E ) Where  v  is a record, a number, or a procedure Construct the value in the store and refer to it by the variable y. Bind E(  x  ) and y in the store We has seen how to construct records and numbers, but what is a procedure value?

78 S. Haridi and P. Van Roy78 Lexical scoping Free and bound identifier occurrences An identifier occurrence is bound with respect to a statement  s  if it is in the scope of a declaration inside  s  A variable identifier is declared either by a ‘local’ statement, as a parameter of a procedure, or implicitly declared by a case statement An identifier occurrence is free otherwise In a running program every identifier is bound (i.e., declared)

79 S. Haridi and P. Van Roy79 Lexical scoping (2) P YY Yproc {P X} local Y in Y = 1 {Browse Y} end X = Y end Bound Occurrences Free Occurrences

80 S. Haridi and P. Van Roy80 Lexical scoping (3) Reslocal Arg1 Arg2 in Arg1 = 111*111 Arg2 = 999*999 Res = Arg1*Arg2 end Bound Occurrences Free Occurrences This is not a runnable program!

81 S. Haridi and P. Van Roy81 Lexical scoping (4) Reslocal Res in local Arg1 Arg2 in Arg1 = 111*111 Arg2 = 999*999 Res = Arg1*Arg2 end {Browse Res} end

82 S. Haridi and P. Van Roy82 Lexical scoping (5) Q Q local P Q in proc {P …} {Q …} end proc {Q …} {Browse hello} end local Q in proc {Q …} {Browse hi} end {P …} end end

83 S. Haridi and P. Van Roy83 Procedure values Constructing a procedure value in the store is not simple because a procedure may have external references Q Q local P Q in P = proc {$ …} {Q …} end Q = proc {$ …} {Browse hello} end local Q in Q = proc {$ …} {Browse hi} end {P …} end end

84 S. Haridi and P. Van Roy84 Procedure values (2) Q Q local P Q in P = proc {$ …} {Q …} end Q = proc {$ …} {Browse hello} end local Q in Q = proc {$ …} {Browse hi} end end {P …} end end x1x1 (, ) Q proc {$ …} {Q …} end Q  x 2 x2x2 (, ) proc {$ …} {Browse hello} end Browse  x 0 P

85 S. Haridi and P. Van Roy85 Procedure values (3) The semantic statement is ( proc {  x   y 1 ...  y n  }  s  end, E)  y 1 ...  y n  are the (formal) parameters of the procedure Other free identifiers of  s  are called external references  z 1 ...  z k  These are defined by the environment E where the procedure is declared (lexical scoping) The contextual environment of the procedure CE is E | {  z1 ...  zk  } When the procedure is called CE is used to construct the environment of  s  ( proc {$  y 1 ...  y n  }  s  end, CE)

86 S. Haridi and P. Van Roy86 Procedure values (4) Procedure values are pairs: ( proc {$  y 1 ...  y n   s  end, CE) They are stored in the store just as any other value ( proc {$  y 1 ...  y n  }  s  end, CE)

87 S. Haridi and P. Van Roy87 Procedure introduction The semantic statement is ( proc {  x   y 1 ...  y n  }  s  end, E) Environment is {  x   x P,... } Create a new procedure value of the form: ( proc { $  y 1 ...  y n  }  s  end, CE), refer to it by the variable x P Bind the store variable E(  x  ) and x P Continue to next execution step

88 S. Haridi and P. Van Roy88 Suspendable statements  s  ::= … |if  x  then  s 1  else  s 2  end conditional |{  x   y 1  …  y n  } procedural application |case  x  of pattern matching  pattern  then  s 1  else  s 2  end The remaining statements require  x  to be bound in order to execute The activation condition (  x  is determined), i.e., bound to a number, record or a procedure value

89 S. Haridi and P. Van Roy89 Life cycle of a thread Running Terminated Suspended ST not empty Top(ST) activation condition is true A B A & B / Execute not A /Terminate A & not B/ Suspend B/Resume

90 S. Haridi and P. Van Roy90 Conditional The semantic statement is ( if  x  then  s 1  else  s 2  end, E) The activation condition E(  x  ) is true: –If E(  x  ) is not Boolean ( true, false ), raise an error –E(  x  ) is true, push (  s 1 , E) on the stack –E(  x  ) is false, push (  s 2 , E) on the stack The activation condition E(  x  ) is false: suspend

91 S. Haridi and P. Van Roy91 Procedure application The semantic statement is ( {  x   y 1  …  y n  }, E) The activation condition E(  x  ) is true: –If E(  x  ) is not procedure value, or a procedure with arity that is not equal n, raise an error –E(  x  ) is ( proc { $  z 1 ...  z n  }  s  end, CE), push (  s , CE + {  z 1   E(  y 1  ) …  z n   E(  y n  )} ) on the stack The activation condition E(  x  ) is false: suspend

92 S. Haridi and P. Van Roy92 Case statement The semantic statement is ( case  x  of  l  (  f 1  :  x 1  …  f n  :  x n  ) then  s 1  else  s 2  end, E) The activation condition E(  x  ) is true: –The label of E(  x  ) is  l  and its arity is [  f 1  …  f n  ]: push ( local  x 1  =  x .  f 1  …  x n  =  x .  f n  in  s 1  end, E) on the stack –Otherwise push (  s 2 , E) on the stack The activation condition E(  x  ) is false: suspend

93 S. Haridi and P. Van Roy93 Execution examples local Max C in proc {Max X Y Z}  s  3 if X >= Y then Z=X else Z=Y end end {Max 3 5 C} end s2s2 s1s1

94 S. Haridi and P. Van Roy94 Execution examples (2) Initial state ([(  s  1,  )],  ) After local Max C in … ( [(  s  2, { Max  m, C  c}) ], {m, c} ) After Max binding ( [(  s  4, { Max  m, C  c}) ], {m = ( proc {$ X Y Z}  s  3 end,  ), c} ) local Max C in proc {Max X Y Z}  s  3 if X >= Y then Z=X else Z=Y end end  s  4 {Max 3 5 C} end s2s2 s1s1

95 S. Haridi and P. Van Roy95 Execution examples (3) After Max binding ( [(  s  4, { Max  m, C  c}) ], {m = ( proc {$ X Y Z}  s  3 end,  ), c} ) After procedure call ( [(  s  3, { X  t 1, Y  t 2, Z  c}) ], {m = ( proc {$ X Y Z}  s  3 end,  ), t 1 =3, t 2 =5, c} ) local Max C in proc {Max X Y Z}  s  3 if X >= Y then Z=X else Z=Y end end  s  4 {Max 3 5 C} end s2s2 s1s1

96 S. Haridi and P. Van Roy96 Execution examples (4) After procedure call ( [(  s  3, { X  t 1, Y  t 2, Z  c}) ], {m = ( proc {$ X Y Z}  s  3 end,  ), t 1 =3, t 2 =5, c} ) After T = (X>=Y) ( [(  s  3, { X  t 1, Y  t 2, Z  c, T  t}) ], {m = ( proc {$ X Y Z}  s  3 end,  ), t 1 =3, t 2 =5, c, t=false} ) ( [(Z=Y, { X  t 1, Y  t 2, Z  c, T  t}) ], {m = ( proc {$ X Y Z}  s  3 end,  ), t 1 =3, t 2 =5, c, t=false} ) local Max C in proc {Max X Y Z}  s  3 if X >= Y then Z=X else Z=Y end end  s  4 {Max 3 5 C} end s2s2 s1s1

97 S. Haridi and P. Van Roy97 Execution examples (5) ( [(Z=Y, { X  t 1, Y  t 2, Z  c, T  t}) ], {m = ( proc {$ X Y Z}  s  3 end,  ), t 1 =3, t 2 =5, c, t=false} ) ( [ ], {m = ( proc {$ X Y Z}  s  3 end,  ), t 1 =3, t 2 =5, c=5, t=false} ) local Max C in proc {Max X Y Z}  s  3 if X >= Y then Z=X else Z=Y end end  s  4 {Max 3 5 C} end s2s2 s1s1

98 S. Haridi and P. Van Roy98 Procedures with external references local LB Y C in Y = 5 proc {LB X Z}  s  3 if X >= Y then Z=X else Z=Y end end {LB 3 C} end s2s2 s1s1

99 S. Haridi and P. Van Roy99 Procedures with external references local LB Y C in Y = 5 proc {LB X Z}  s  3 if X >= Y then Z=X else Z=Y end end {LB 3 C} end s2s2 s1s1 The procedure value of LB is ( proc {$ X Z}  s  3 end, { Y  y}) The store is {y = 5, …}

100 S. Haridi and P. Van Roy100 Procedures with external references local LB Y C in Y = 5 proc {LB X Z}  s  3 if X >= Y then Z=X else Z=Y end end {LB 3 C} end s2s2 s1s1 The procedure value of LB is ( proc {$ X Z}  s  3 end, { Y  y}) The store is {y = 5, …} STACK: [( {LB T C}, { Y  y, LB  lb, C  c, T  t}) ] STORE: {y = 5, lb = ( proc {$ X Z}  s  3 end, { Y  y}), t = 3, c}

101 S. Haridi and P. Van Roy101 Procedures with external references local LB Y C in Y = 5 proc {LB X Z}  s  3 if X >= Y then Z=X else Z=Y end end {LB 3 C} end s2s2 s1s1 STACK: [( {LB T C}, { Y  y, LB  lb, C  c, T  t}) ] STORE: {y = 5, lb = ( proc {$ X Z}  s  3 end, { Y  y}), t = 3, c} STACK: [(  s  3, { Y  y, X  t, Z  c}) ] STORE: {y = 5, lb = ( proc {$ X Z}  s  3 end, { Y  y}), t = 3, c}

102 S. Haridi and P. Van Roy102 Procedures with external references local LB Y C in Y = 5 proc {LB X Z}  s  3 if X >= Y then Z=X else Z=Y end end {LB 3 C} end s2s2 s1s1 STACK: [(  s  3, { Y  y, X  t, Z  c}) ] STORE: {y = 5, lb = ( proc {$ X Z}  s  3 end, { Y  y}), t = 3, c} STACK: [(Z=Y, { Y  y, X  t, Z  c}) ] STORE: {y = 5, lb = ( proc {$ X Z}  s  3 end, { Y  y}), t = 3, c} STACK: [ ] STORE: {y = 5, lb = ( proc {$ X Z}  s  3 end, { Y  y}), t = 3, c = 5}

103 S. Haridi and P. Van Roy103 From the kernel language to a practical language Interactive interface –the declare statement and the global environment Extend kernel syntax to give a full, practical syntax –nesting of partial values –implicit variable initialization –expressions –nesting the if and case statements –andthen and orelse operations Linguistic abstraction –functions

104 S. Haridi and P. Van Roy104 The interactive interface ( declare ) The interactive interface is a program that has a single global environment declare X Y Augments (and overrides) the environment with new mappings for X and Y {Browse X} Inspects the store and shows partial values, and incremental changes

105 S. Haridi and P. Van Roy105 The interactive interface ( declare ) Browse F X Y procedure value value a b Environment Store

106 S. Haridi and P. Van Roy106 declare X Y Browse F X Y procedure value value a b Environment Store unbound xixi x i+1

107 S. Haridi and P. Van Roy107 Syntactic extensions Nested partial values –person(name: “George” age:25) local A B in A= “George” B=25 person(name:A age:B) end Implicit variable initialization –local  pattern  =  expression  in  statement  end Example: assume T is tree(key:a left:L right:R value:1), then local tree(key:A left:B right:C value:D) = T in  statement  end is the same as: local A B C D then {Label T} = tree A = T.key B = T.left C = T.right D = T.value end

108 S. Haridi and P. Van Roy108 Extracting fields in local statement declare T : T = tree(key:seif age:48 profession:professor) : local tree(key:A...) = T in  statement  end

109 S. Haridi and P. Van Roy109 Nested if and case statements Observe a pair notation is: 1 # 2, is the tuple ‘#’(1 2) case Xs # Ys of nil # Ys then  s  1 []Xs # nil then  s  2 [](X|Xr) # (Y|Yr) andthen X=<Y then  s  3 else  s  4 end Is translated into case Xs of nil then  s  1 else case Ys of nil then  s  2 else case Xs of X|Xr then case Ys of Y|Yr then if X=<Y then  s  3 else  s  4 end else  s  4 end else  s  4 end end end

110 S. Haridi and P. Van Roy110 Expressions An expression is a sequence of operations that returns a value A statement is a sequence of operations that does not return a value. Its effect is on the store, or outside of the system (e.g. read/write a file) 11*11X=11*11 expression statement

111 S. Haridi and P. Van Roy111 Functional nesting Nested notations that allows expressions as well as statements local R in {F X1... Xn R} {Q R...} end Is written as (equivalent to): {Q {F X1... Xn}...} expression statement

112 S. Haridi and P. Van Roy112 Nesting in data structures Ys = {F X}|{Map Yr F} Is unnested to: local Y Yr in Ys = Y|Yr {F X Y} {Map Xr F Yr} end The unnesting of the calls occurs after the data structure

113 S. Haridi and P. Van Roy113 Functions as linguistic abstraction {F X1... Xn R} R = {F X1... Xn} fun {F X1... Xn}  statement   expression  end  statement  proc {F X1... Xn R}  statement  R =  expression  end  statement 

114 S. Haridi and P. Van Roy114 Conditional expressions R = if  expr  1 then  expr  2 else  expr  3 end  expression   statement  if  expr  1 then R =  expr  2 else R =  expr  3 end fun {Max X Y} if X>=Y then X else Y end end proc {Max X Y R} R = ( if X>=Y then X else Y end ) end

115 S. Haridi and P. Van Roy115 Example fun {Max X Y} if X>=Y then X else Y end end proc {Max X Y R} R = ( if X>=Y then X else Y end ) end proc {Max X Y R} if X>=Y then R = X else R = Y end end

116 S. Haridi and P. Van Roy116 andthen and orelse  expr  1 andthen  expr  2 if  expr  1 then  expr  2 else false end  expr  1 orelse  expr  2 if  expr  1 then true else  expr  2 end

117 S. Haridi and P. Van Roy117 Function calls {F1 {F2 X} {F3 Y}} local R1 R2 in R1 = {F2 X} R2 = {F3 Y} {F1 R1 R2} end Observe The arguments of a function are evaluated first from left to right

118 S. Haridi and P. Van Roy118 A complete example fun {Map Xs F} case Xs of nil then nil [] X|Xr then {F X}|{Map Xr F} end end proc {Map Xs F Ys} case Xs of nil then Ys = nil [] X|Xr then Y Yr in Ys = Y|Yr {F X Y} {Map Xr F Yr} end end

119 S. Haridi and P. Van Roy119 Back to semantics Efficient loops in the declarative model –recursion used for looping –is efficient because of last call optimization –memory management and garbage collection Exceptions Functional programming

120 S. Haridi and P. Van Roy120 Last call optimization Consider the following procedure proc {Loop10 I} if I ==10 then skip else {Browse I} {Loop10 I+1} end end This procedure does not increase the size of the STACK It behaves like a looping construct

121 S. Haridi and P. Van Roy121 Last call optimization proc {Loop10 I} if I ==10 then skip else {Browse I} {Loop10 I+1} end end ST: [ ({Loop10 0}, E 0 ) ] ST: [({Browse I}, {I  i 0,...}) ({Loop10 I+1}, {I  i 0,...}) ]  : {i 0 =0,...} ST: [({Loop10 I+1}, {I  i 0,...}) ]  : {i 0 =0,...} ST: [({Browse I}, {I  i 1,...}) ({Loop10 I+1}, {I  i 1,...}) ]  : {i 0 =0, i 1 =1,...}

122 S. Haridi and P. Van Roy122 Garbage collection proc {Loop10 I} if I ==10 then skip else {Browse I} {Loop10 I+1} end end ST: [({Browse I}, {I  i k,...}) ({Loop10 I+1}, {I  i k,...}) ]  : {i 0 =0, i 1 =1,..., i k-i =k-1, i k =k,... } Garbage collection is an algorithm (a task) that removes from memory (store) all cells that are not accessible from the stack ST: [({Browse I}, {I  i k,...}) ({Loop10 I+1}, {I  i k,...}) ]  : { i k =k,... }

123 S. Haridi and P. Van Roy123 The memory use cycle Active memory is what the program needs to continue execution (semantic stack + reachable part of store) Memory that is no longer needed is of two kinds: –Can be immediately deallocated (i.e., semantic stack) –Simply becomes inactive (i.e., store) Reclaiming inactive memory is the hardest part of memory management –Garbage collection is automatic reclaiming ActiveFree Inactive Allocate/ deallocate Become inactive (program execution) Reclaim (garbage collection)

124 S. Haridi and P. Van Roy124 Exceptions How to handle exceptional situations in the program? Examples: –divide by 0 –opening a nonexistent file Some errors are programming errors Some errors are imposed by the external environment Exception handling statements allow programs to handle and recover from errors

125 S. Haridi and P. Van Roy125 Exceptions Exception handling statements allow programs to handle and recover from errors The error confinement principle: –Define your program as a structured layers of components –Errors are visible only internally and a recovery procedure corrects the errors: either errors are not visible at the component boundary or are reported (nicely) to a higher level In one operation, exit from arbitrary depth of nested contexts –Essential for program structuring; else programs get complicated (use boolean variables everywhere, etc.)

126 S. Haridi and P. Van Roy126 Basic concepts A program that encounters an error (exception) should transfer execution to another part, the exception handler and give it a (partial) value that describes the error try  s  1 catch  x  then  s  2 end raise  x  end Introduce an exception marker on the semantic stack The execution is equivalent to  s  1 if it executes without raising an error Otherwise,  s  1 is aborted and the stack is popped up to the marker, the error value is transferred through  x , and  s  2 is executed

127 S. Haridi and P. Van Roy127 Exceptions (Example) fun {Eval E} if {IsNumber E} then E else case E of plus(X Y) then {Eval X}+{Eval Y} [] times(X Y) then {Eval X}*{Eval Y} else raise illFormedExpression(E) end end end end plus times5 6 4

128 S. Haridi and P. Van Roy128 Exceptions (Example) try {Browse {Eval plus(5 6) }} {Browse {Eval plus(times(5 5) 6) }} {Browse {Eval plus(minus(5 5) 6) }} catch illFormedExpression(E) then {System.showInfo ”**** illegal expresion ****” # E} end

129 S. Haridi and P. Van Roy129 Try semantics The semantic statement is ( try  s  1 catch  x  then  s  2 end, E) Push the semantic statement ( catch  x  then  s  2 end, E) on ST Push (  s  1, E) on ST Continue to next execution step

130 S. Haridi and P. Van Roy130 Raise semantics The semantic statement is ( raise  x  end, E) Pop elements off ST looking for a catch statement: –If a catch statement is found, pop it from the stack –If the stack is emptied and no catch is found, then stop execution with the error message ”Uncaught exception” Let ( catch  y  then  s  end, E c ) be the catch statement that is found Push (  s  1, E c +{  E( )}) on ST Continue to next execution step

131 S. Haridi and P. Van Roy131 Catch semantics The semantic statement is ( catch  x  then  s  end, E) Continue to next execution step (like skip )

132 S. Haridi and P. Van Roy132 Full exception syntax Exception statements (expressions) with multiple patterns and finally clause Example: : FH = {OpenFile ”xxxxx”} : try {ProcessFile FH} catch X then {System.showInfo ”***** Exception when processing *****” # X} finally {CloseFile FH} end

133 S. Haridi and P. Van Roy133 Strictly functional Restrict the language to make the language functional (I.e.without dataflow variables) –Language similar to Scheme (dynamically typed functional language) This is done by disallowing variable declaration (without initialization) and disallowing procedural syntax –Only use implicit variable initialization –Only use functions

134 S. Haridi and P. Van Roy134 Exercises 1.Practice with the basic operations on numbers, records, and Booleans 2.Explain the behavior of the declare statement in the interactive environment 3.Give some examples in the kernel language and try to execute by hand. The example should illustrate iterative vs. recursive computation 4.Examples where programs may suspend, terminate, loop 5.Unification examples 6.Translation examples to the kernel language 7.Late binding vs. lexical binding 8.Explain virtual strings

135 S. Haridi and P. Van Roy135 Exercise Translate the following function to the kernel language fun {AddList L1 L2} case L1 of H1|T1 then case L2 of H2|T2 then H1+H2|{AddList T1 T2} end else nil end end Execute the call declare X in X = {AddList [1 2] [3 4]}


Download ppt "S. Haridi and P. Van Roy1 Declarative Computation Model Seif Haridi KTH Peter Van Roy UCL."

Similar presentations


Ads by Google