cs2403 programming languages preliminaries chung-ta king department of computer science national...
TRANSCRIPT
CS2403 Programming Languages
Preliminaries
Chung-Ta KingDepartment of Computer ScienceNational Tsing Hua University(Slides are adopted from Concepts of Programming Languages, R.W. Sebesta; Modern Programming Languages: A Practical Introduction, A.B. Webber)
2
Programming Language
A programming language is an artificial language designed to express computations or algorithms that can be performed by a computer
-- Wikipedia A program is computer coding of
an algorithm thatTakes inputPerforms some calculations on
the inputGenerates output
Input
Output
Program
3
Outline
Three models of programming languages A brief history
Programming design methodologies in perspective (Sec. 1.4.2)
Language evaluation criteria (Sec. 1.3)Language design trade-offs (Sec. 1.6)
Implementation methods (Sec. 1.7)
4
Models of Programming Languages
Programming is like …
5
1st View: Imperative & Procedural
Computers take commands and do operations Thus, programming is like …
issuing procedural commands to the computerExample: a factorial function in Cint fact(int n) { int sofar = 1; while (n>0) sofar *= n--; return sofar;}
Since almost all computers today use the von Neumann architecture PL mimic the arch.
6
The von Neumann Architecture
(Fig. 1.1)
Program counter
7
The von Neumann Architecture
Key features:Data and programs stored in memoryInstructions and data are piped from memory
to CPUFetch-execute-cycle for each machine
instructioninitialize the program counter (PC)repeat foreverfetch the instruction pointed by PCincrement the counterdecode the instructionexecute the instruction
end repeat
add A,B,C 0100 1001sub C,D,E 0110 1010br LOOP 1011 0110… …
Assembly code
Machinecode
8
Imperative Language and Arch.
Example: a factorial function in Cint fact(int n) { int sofar = 1; while (n>0) sofar *= n--; return sofar;}Indicates that data n, sofar, and program codeare stored in memory
Program code instructsCPU to do operations
n
sofar
int fact(int n) { int sofar = 1; while (n>0) sofar *= n--; return sofar; }
Program counter
9
Imperative Languages and Arch.
Imperative languages, e.g., C, C++, Java, which dominate programming, mimic von Neumann architectureVariables memory cellsAssignment statements data piping between
memory and CPUOperations and expressions CPU executionsExplicit control of execution flows prog.
counter Allow efficient mapping between language
and hardware for good execution performance, but limited by von Neumann bottleneck
10
High Level Language Program
High Level Language Program
Assembly Language Program
Assembly Language Program
Machine Language Program
Machine Language Program
Control Signal Specification
Compiler
Assembler
Machine Interpretation
temp = v[k];
v[k] = v[k+1];
v[k+1] = temp;
Layers of Abstraction/Translation
lw $15, 0($2)lw $16, 4($2)sw$16, 0($2)sw$15, 4($2)
0000 1001 1100 0110 1010 1111 0101 10001010 1111 0101 1000 0000 1001 1100 0110 1100 0110 1010 1111 0101 1000 0000 1001 0101 1000 0000 1001 1100 0110 1010 1111
ALUOP[0:3] <= InstReg[9:11] & MASK
All imperative!
11
2nd View: Functional
Programming is like …solving mathematical functions, e.g.,z = f(y, g(h(x)))A program, and its subprograms, are just
implementations of mathematical functionsExample: a factorial function in ML
Input
Output
Function
Input
Output
Program
fun fact x = if x <= 0 then 1 else x * fact(x-1);
12
Another Functional Language: LISP
Example: a factorial function in Lisp
Computations by applying functions to parametersNo concept of variables (storage) or assignment
Single-valued variables: no assignment, not storageControl via recursion and conditional expressions
Branches conditional expressions Iterations recursion
Dynamically allocated linked lists 2nd-oldest general-purpose PL still in use (1958)
(defun fact (x) (if (<= x 0) 1 (* x (fact (- x 1)))))
13
3rd View: Logic
Programming is like …logic inductionProgram expressed as rules in formal logicExecution by rule resolutionExample: relationship among people
fact: mother(joanne,jake). father(vern,joanne).
rule: grandparent(X,Z) :- parent(X,Y), parent(Y,Z).goal: grandparent(vern,jake).
14
Logic Programming
Non-proceduralOnly supply relevant facts (predicate calculus)
and inference rules (resolutions) System then infer the truth of given
queries/goals Highly inefficient, small application areas
(database, AI)Example: a factorial function in Prolog
fact(X,1) :- X =:= 1.fact(X,Fact) :- X > 1, NewX is X - 1, fact(NewX,NF), Fact is X * NF.
15
Summary: Language Categories
Logic LanguageImperativeLanguage
Functional Language
Memory
ALU Control
von Neumann Architecture
16
Summary: Language Categories
ImperativeVariables, assignment statements, and iterationInclude languages that support object-oriented
programming, scripting languages, visual languagesEx.: C, Java, Perl, JavaScript, Visual BASIC .NET
FunctionalComputing by applying functions to given
parametersEx.: LISP, Scheme, ML
LogicRule-based (rules are specified in no particular
order)Ex.: Prolog
17
Outline
Three models of programming languages A brief history
Programming design methodologies in perspective (Sec. 1.4.2)
Language evaluation criteria (Sec. 1.3)Language design trade-offs (Sec. 1.6)
Implementation methods (Sec. 1.7)
18
Programming Design Methodology
1950s and early 1960s: simple applications; worry about machine efficiency (FORTRAN)
Late 1960s: people efficiency important; readability, better control structures (ALGOL)Structured programming, free format lexicalTop-down design and step-wise refinement
Late 1970s: process-oriented to data-orientedData abstraction
Middle 1980s: object-oriented programmingData abstraction + inheritance + dynamic binding
19
Genealogy of Common Languages
(Fig. 2.1)
20
Outline
Three models of programming languages A brief history
Programming design methodologies in perspective (Sec. 1.4.2)
Language evaluation criteria (Sec. 1.3)Language design trade-offs (Sec. 1.6)
Implementation methods (Sec. 1.7)
21
What Make a Good PL?
Language evaluation criteria: Readability: the ease with which
programs can be read and understood Writability: the ease with which a
language can be used to create programs Reliability: a program performs to its
specifications under all conditions Cost
22
Features Related to Readability
Overall simplicity: lang. is more readable ifFewer features and basic constructs
Readability problems occur whenever program’s author uses a subset different from that familiar to reader
Fewer feature multiplicity (i.e., doing the same operation with different ways)
Minimal operator overloading Orthogonality
A relatively small set of primitive constructs can be combined in a relatively small number of ways
Every combination is legal, independent of context Few exceptions, irregularities
23
Features Related to Readability
Control statementsSufficient control statements for structured prog.
can read program from top to bottom w/o jump
Data types and structuresAdequate facilities for defining data type &
structure Syntax considerations
Identifier forms: flexible composition Special words and methods of forming
compound statementsForm and meaning: self-descriptive constructs,
meaningful keywords
24
Writability
Simplicity and orthogonalityBut, too orthogonal may cause errors
undetected Support for abstraction
Ability to define and use complex structures or operations in ways that allow details to be ignored
Abstraction in process (e.g. subprogram), data Expressivity
A set of relatively convenient ways of specifying operations
Example: the inclusion of for statement in many modern languages
25
Reliability
Type checkingTesting for type errors, e.g. subprogram parameters
Exception handlingIntercept run-time errors & take corrective
measures Aliasing
Presence of two or more distinct referencing methods for the same memory location
Readability and writabilityA language that does not support “natural” ways of
expressing an algorithm will necessarily use “unnatural” approaches, and hence reduced reliability
26
Cost
Training programmers to use language Writing programs (closeness to particular
applications) Compiling programs Executing programs: run-time type
checking Language implementation system:
availability of free compilers Reliability: poor reliability leads to high
costs Maintaining programs
27
Others
PortabilityThe ease with which programs can be moved
from one implementation to another Generality
The applicability to a wide range of applications
Well-definednessThe completeness and precision of the
language’s official definition Power efficiency?
28
Language Design Trade-Offs
Reliability vs. cost of executione.g., Java demands all references to array
elements be checked for proper indexing but that leads to increased execution costs
Readability vs. writabilitye.g., APL provides many powerful operators
(and a large number of new symbols), allowing complex computations to be written in a compact program but at the cost of poor readability
Writability (flexibility) vs. reliabilitye.g., C++ pointers are powerful and very
flexible but not reliably used
29
Outline
Three models of programming languages A brief history
Programming design methodologies in perspective (Sec. 1.4.2)
Language evaluation criteria (Sec. 1.3)Language design trade-offs (Sec. 1.6)
Implementation methods (Sec. 1.7)
30
Implementations of PL
It is important to understand how features and constructs of a programming language, e.g., subroutine calls, are implementedImplementation of a PL construct means its
realization in a lower-level language, e.g. assembly mapping/translation from a high-level language to a low-level language
Why the need to know implementations?Understand whether a construct may be implemented efficiently, know different implementation methods and their tradeoffs, etc.
31
Implementation by Compilation
Translate a high-level program into equivalent machine code automatically by another program (compiler)
Compilation process has several phases: Lexical analysis: converts characters in the
source program into lexical unitsSyntax analysis: transforms lexical units into
parse trees which represent syntactic structure of program
Semantics analysis: generate intermediate codeCode generation: machine code is generatedLink and load
32
Compilation Process
(Fig. 1.3)
33
Implementation by Interpretation
Program interpreted by another program (interpreter) without translationInterpreter acts a simulator or virtual machine
Easier implementation of programs (run-time errors can easily and immediately displayed)
Slower execution (10 to 100 times slower than compiled programs)
Often requires more space Popular with some Web scripting
languages (e.g., JavaScript)
34
Hybrid Implementation Systems
A high-level language program is translated to an intermediate language that allows easy interpretationFaster than pure interpretation
35
Summary
Most important criteria for evaluating programming languages include:Readability, writability, reliability, cost
Major influences on language design have been application domains, machine architecture and software development methodologies
The major methods of implementing programming languages are: compilation, pure interpretation, and hybrid implementation