Types and Semantics - PowerPoint PPT Presentation

1 / 49
About This Presentation
Title:

Types and Semantics

Description:

'When I use a word,' Humpty Dumpty said, in rather a scornful tone, 'it means ... 'The question is,' said Humpty Dumpty, 'which is to be master-that's all. ... – PowerPoint PPT presentation

Number of Views:40
Avg rating:3.0/5.0
Slides: 50
Provided by: Kenny77
Category:

less

Transcript and Presenter's Notes

Title: Types and Semantics


1
Types and Semantics
2
Type Systems
  • A type is a well-defined set of values and
    operations on those values
  • Examples
  • boolean type has values true, false and
    operations AND, OR, NOT, XOR
  • int type has values ,-1,0,1, and operations
    ADD, SUBTRACT, MULT,
  • A type-system is a precise definition of the
    bindings between variables and their types.
  • A type-error occurs when an operation is
    attempted on a value for which the operation is
    not defined

3
Type Systems
  • Types are assigned in two ways
  • Statically typed languages
  • The types of all variables/objects are known at
    compile time
  • Examples are C, C, Java
  • Dynamically typed languages
  • The types of all variables/objects are assigned
    at runtime
  • Examples are Lisp, Scheme, Perl

4
Type Checking
  • Languages are classified in two ways
  • Strongly typed language
  • A language that detects all type errors
  • Weakly typed language
  • A language that does not detect all type errors
  • Type checking can occur during
  • compilation
  • execution

5
Java Example
class ClassTester public static void
method1(Object x) System.out.println(((String)x
).length()) public static void
main(String args) throws Exception Class
theClass Class.forName(args0) Object
newObject theClass.newInstance() System.out.pr
intln("object" newObject) method1(newObject)

6
Specifying Semantics
  • A BNF grammar can define the proper syntax of a
    language, but more is needed.
  • BNF cant define rules like all variable need to
    be declared prior to use or all variables must
    have been assigned a value prior to use or the
    types of the rhs and lhs of an assignment must be
    identical
  • To determine the meaning of a program we must
  • Insure that a program is syntactically correct
  • Insure that a program type checks.

7
void main() int n, i, result n 8 i
1 result 1 while(i lt n) i i 1
result result i
Type Checking in Jay
  • Jay (statically checked, strongly typed)
  • Each variable must have a unique identifier
  • Each variables type must be int or boolean
  • Each variable referenced must be declared
  • Every expression has a type
  • if the expression is a variable or value the type
    is the type of the variable or value
  • if the expressions operator is arithmetic
    (,-,,/) then its operands must be int and the
    resulting type is int
  • if the expressions operator is relational
    (lt,lt,,gt,gt,!) then its operands must be int
    and the resulting type is int
  • if the operator is logical (,,!) then the
    operands must be boolean and the resulting type
    is boolean
  • For every assignment, the type of the target and
    source must be identical
  • For every conditional and loop, the type of its
    expression must be boolean

8
Type Checking
  • Type checking is done by the parser for static
    languages
  • Can write functions to
  • Determine the type of a variable
  • Determine the type of a literal
  • Validate and determine the type of expressions
  • The next slides show how these functions can be
    designed.

9
Type Maps
  • A type-map is a set of associations of a type
    with a variable name
  • A type-map has the form
  • ltv1, t1gt, ltv2, t2gt, ,ltvn, tngt
  • where vi represents a variable name
  • and ti represents a type

ltcost, intgt, lttaxRate, floatgt, lttaxable,
booleangt
10
Type Maps
  • What parts of a program affect the type-map?
  • When we declare variables!
  • typing Declarations ? Typemap
  • i.e. declarations produce a typemap
  • More formally
  • typing(Declarations d)

boolean foo(int x) boolean flag int y
10 if(x lt y) flag true else
flag false return flag
Image from thepulp.net/PulpCompanion/
03summer/plot.html
11
Abstract Syntax for Jay
  • Program Declarations decpart Block body
  • Declarations Declaration
  • Declaration Variable v Type t
  • Type int boolean undef
  • Statement Skip Block Assignment
    Conditional Loop
  • Block Statement
  • Assignment Variable target Expression source
  • Conditional Expression test Statement
    thenBranch, elseBranch
  • Loop Expression test Statement body
  • Expression Variable Value Binary Unary
  • Variable String id
  • Value int intValue boolean boolValue
  • Binary Operator op Expression term1, term2
  • Operator BooleanOp RelationalOp
    ArithmeticOp UnaryOp

12
Java Implementation
class Declaration Variable v Type t
class Declarations extends Vector // vector of
Declaration
class TypeMap extends Hashtable // Java
hashtable, keyvariable, datatype
TypeMap typing (Declarations d) TypeMap map
new TypeMap() for (int i0 iltd.size() i)
map.put(((Declaration)(d.elementAt(i))).v,
((Declaration)(d.elementAt(i))).t) return
map
13
Static Type Checking in Java
  • Create rules for the semantics of valid types
  • Boolean-valued function V (meaning valid)
  • VClass?Boolean
  • True if list of declarations in an abstract
    syntactic class is valid
  • We really want a yes/no answer but good error
    messages are always helpful
  • Example express idea that the list of
    declarations is valid if all variables have
    mutually unique identifiers
  • Note that BNF is not expressive enough to
    represent this

Is implication
14
Type Checking
  • Type checking predicates can be written using
    type-maps
  • Each type rule is a function that takes a
    grammatical category and checks for type
    conformance

class Declaration Variable v Type t
class Declarations extends Vector
15
Type Checking(Operational Semantics)
public boolean V(Declarations d) for(int i0
iltd.size()-1 i) for(int ji1,
jltd.size()-1 j) if(((Declaration)(d.el
ementAt(i))).v).equals
(((Delcaration)(d.elementAt(j))).v)) return
false return true
16
Type Requirements for Program
  • For the complete program, we have the following
    abstract syntax

class Program Declarations decpart Block
body
Rule declarations must be valid, and types
within the body must be valid.
17
Java Implementation
public boolean V (Statement s, TypeMap tm) if
(s instanceof Skip snull) return true if
(s instanceof Assignment) boolean b1
tm.containsKey(((Assignment)s).target)
boolean b2 V(((Assignment)s).source, tm)
if (b1 b2) // Assign only same types
return ((Type)tm.get(((Assignment)s).target)).id.e
quals (typeOf(((Assignment)s).sour
ce, tm).id) else return false if (s
instanceof Conditional) // If condition must be
boolean return V (((Conditional)s).test, tm)
typeOf(((Conditional)s).test,
tm).isBoolean() V (((Conditional)s).the
nbranch, tm) V (((Conditional)s).elsebr
anch, tm) if (s instanceof Loop) // Loop
condition must be boolean return V
(((Loop)s).test, tm)
typeOf(((Loop)s).test, tm).isBoolean()
V (((Loop)s).body, tm) if (s instanceof Block)
// Sub-blocks must be valid for (int
j0 j lt ((Block)s).members.size() j)
if (! V((Statement)(((Block)s).members.elementAt(j
)), tm)) return false return
true return false
18
Semantic Domains(Towards a semantic definition
of languages)
  • A semantic domain
  • any set whose properties and operations are well
    understood
  • functional semantic specifications are based
  • Examples include
  • Natural numbers (non-negative integers)
  • Integers
  • Boolean
  • Strings

19
Semantic Domains
  • Environment (?)
  • A mapping of variables with memory locations
  • Memory (?)
  • A mapping of memory locations with values

? lti, 154gt, ltj, 155gt ? lt0, undefgt, .,
lt154, 13gt, lt155, -1gt
20
Semantic Domains
  • State (?)
  • The product of environment and memory
  • For pedagogical purposes, treat the state without
    regard to low-level memory addressing issues.

? lti, 13gt, ltj, -1gt
Prior to execution of any program, what is the
state?
? ltVi, undefgt,, ltVn, undefgt
21
Semantic Domains
  • Define ?(exp) to be a function that returns the
    value of exp from the state ?

? lti, 13gt, ltj, -1gt
?(i) ??
?(ij) ??
22
State Transformations
  • Program statements usually change the state

? ltx, 1gt, lty, 2gt, ltz,3gt
y 2z 3
? ltx, 1gt, lty, 9gt, ltz,3gt
w 4
? ltx, 1gt, lty, 9gt, ltz,3gt, ltw, 4gt
23
State Transformations(a little set theory)
  • Overriding union X op Y ? replace in X all pairs
    ltx,vgt whose first member matches a pair ltx,wgt
    from Y by ltx,wgt and then add to X any remaining
    pairs in Y.
  • The overriding union is a general mathematical
    model of assignment.

24
Humpty Time
I don't know what you mean by glory, Alice
said. Humpty Dumpty smiled contemptuously. Of
course you don't till I tell you. I meant
there's a nice knock-down argument for you!'
" But glory' doesn't mean a nice
knock-down argument,' " Alice objected. When I
use a word, Humpty Dumpty said, in rather a
scornful tone, it means just what I choose it to
mean, neither more nor less. The question is,
said Alice, whether you can make words mean so
many different things. The question is, said
Humpty Dumpty, which is to be master-that's
all." . . . When I make a word do a lot of work
like that," said Humpty Dumpty, I always pay it
extra.
25
Ways of Specifying Semantics
  • Axiomatic Semantics
  • Formal specification of what the program should
    do
  • Rigorous proof that the program does what it is
    supposed to do via logical reasoning
  • Denotational Semantics
  • Program defined by state-transforming functions
    in the abstract syntax
  • Well implement this approach in Java for Jay

26
Denotational Semantics
  • Defines the meaning of a language as a set of
    functions
  • Functions manipulate environments and states of a
    program
  • Environment set of objects and types that are
    active at each step during execution
  • State of a program Set of all active objects and
    their values

27
Denotational Semantics
  • Consists of three parts
  • Abstract syntax of the language
  • Semantic algebra defining a computational model
  • Mapping functions that map the syntactic
    constructs of the language to the semantic
    algebra.
  • Meaning of a program is a sequence of state
    transformations caused by application of sequence
    of functions
  • Functional definitions are used as the basis for
    compiler/interpreter writers
  • Functions define the meaning of each programming
    construct

28
Denotational Semantics
  • Let ? be the set of all possible program states.
  • Define a meaning function M with signatures
  • M Program ? ?
  • M Statement x ? ? ?
  • M Expression x ? ? Value

29
Denotational Semantics
  • Meaning functions are partial functions
  • Not well defined for all inputs
  • Syntactically valid but not well defined meaning
  • Example
  • for (i1 igt-1 i) i--
  • No definite final state
  • Alternates endlessly between 0 and 1

30
Denotational Semantics
  • A program is defined in terms of each of its
    parts
  • Define the meaning functions of the parts
  • Combine them to define the meaning of the program
  • Traverse the abstract syntax tree to determine
    the meaning

31
Denotational Semantics
Meaning of a program produce final state
State M (Program p) return M
(p.body, initialState(p.decpart))
State initialState (Declarations d) State
sigma new State() Value undef new
Value() for (int i 0 i lt d.size() i)
sigma.put(((Declaration)(d.elementAt(i))).v,
undef) return sigma
State M (Program p) return M
(p.body, initialState(p.decpart))
State initialState (Declarations d) State
sigma new State() Value undef new
Value() for(Declaration decl d)
sigma.put(decl.v, undef) return sigma
32
Meaning for Statements
Lots of overloaded definitions for M
State M (Statement s, State sigma) if (s
instanceof Skip) return M((Skip)s, sigma) if
(s instanceof Assignment) return
M((Assignment)s, sigma) if (s instanceof
Conditional) return M((Conditional)s, sigma)
if (s instanceof Loop) return M((Loop)s,
sigma) if (s instanceof Block) return
M((Block)s, sigma) return null
See semantics.java, Appendix B for complete code
listing
33
Jay Denotational Semantics Example
Abstract syntax tree for an assignment zx2y
34
Meaning of Assignment
  • The meaning of assignment is to produce a new
    state.
  • Start state with the assignment target replaced
    by the meaning of the source expression

35
Assignment Example
  • Assume current state is s ltx,2gt,lty,-3gt,ltz,75gt
  • Meaning of instruction zx2y
  • M(a.source,s) M(x2y,s) M(x2y,ltx,2gt,lty,-3gt
    ,ltz,75gt)

Assuming that M(x2y,ltx,2gt,lty,-3gt,ltz,75gt)
is defined and returns the value of -4
36
Meaning of Arithmetic Expressions for Integers
Define ApplyBinary as the meaning of binary
operations
37
Denotational Semantics for Arithmetic Expressions
Recall that an Expression may contain
sub-expressions which may themselves contain
variables or literals.
38
Arithmetic Example
  • Compute the meaning of x2y
  • Current state sltx,2gt,lty,-3gt,ltz,75gt
  • Want to show M(x2y,s -4
  • x2y is Binary
  • From M(Expression e, State s) this is
  • ApplyBinary(e.op, M(e.term1, s), M(e.term2,s))
  • ApplyBinary(,M(x,s),M(2y,s))
  • ApplyBinary(,2,M(2y,s))
  • M(2y,s) is also Binary, which expands to
  • ApplyBinary(,M(2,s), M(y,s))
  • ApplyBinary(,2,-3) -6
  • Back up ApplyBinary(,2,-6) -4

39
Java Implementation
Value M (Expression e, State sigma) if (e
instanceof Value) return (Value)e if
(e instanceof Variable) if
(!sigma.containsKey((Variable)e)) return new
Value() else return (Value)(sigma.get((Vari
able)e)) if (e instanceof Binary)
return applyBinary (((Binary)e).op,
M(((Binary)e).term1, sigma),
M(((Binary)e).term2, sigma)) if (e
instanceof Unary) return applyUnary(((Unary)
e).op, M(((Unary)e).term, sigma)) return
null
Code close to the denotational semantic
definition! Sigma implemented with a Java Hash
Table
40
Semantics of Skip
  • Skip
  • Skip statement cant change the state

41
Semantics of Conditional
If (agtb) maxa else maxb
42
Conditional, continued
43
Semantics of Block
  • Block is just a sequence of statements
  • Example for Block b
  • fact fact i
  • i i 1

44
Block example
  • b1 fact fact i
  • b2 i i 1
  • M(b,s) M(b2,M(b1,s))
  • M(ii-1,M(factfacti,s))
  • M(ii-1,M(factfacti,lti,3gt,ltfact,1gt))
  • M(ii-1,lti,3gt,ltfact,3gt)
  • lti,2gt,ltfact,3gt

b
45
Expressions in Jay
  • Expressions are either values, variables, binary
    operations or unary operations.
  • The type of an expression is defined by its kind
    and its parts

Type of value
Value
Type of variable
Variable
int
Arithmetic Binary Operator
boolean
Relational Binary Operator
boolean
Unary Operator
46
Types of Expressions
  • Formally defining expression types in Jay
  • Expressions are Values, Variables, Binary
    (arithmetic and boolean), and Unary (negation)

47
Types of Expressions
Examples int x, y x2y xlt2y xlt2y
xgt0
48
Other Types of Semantics
  • Algebraic semantics Describe the meaning of a
    program by defining an algebra.
  • Axioms and equations
  • Translation semantics Describe how to translate
    a program into another language
  • Commonly a machine or assembly
  • Often used in compilers

49
Proof Rules Summary
  • Proof rules are used to prove that a program does
    what is intended.
  • Not very practical since
  • 1. It is difficult to apply these rules
  • 2. It is diffcult to attach rules for
    goto/break/continue statements.
  • 3. It makes many assumptions. For example,
    evaluating expressions will not change any
    variable.
  • Proof rules may be viewed as the definition of a
    language. This is called the axiomatic approach
    to formal semantics.
  • Pascal is a language designed with proof rules.
Write a Comment
User Comments (0)
About PowerShow.com