Document Sample
Graphics Powered By Docstoc
					159.331 Programming Languages
         & Algorithms
               Lecture 10 - Imperative
          Programming Languages - Part 6 -
           Program Composition Continued

159.331               Prog Lang & Alg        1
              Modules & Packages
• Sometimes we want to bind together related
  declarations of types, variables, routines,…
• A module or package lets us do this
• Module consists of two parts:
   – Specification part - describes interface - aimed at user as well
     as the implementing programmer
   – Implementation part - might like to only “release as a
     binary”, source code seen only by the implementer
• Ada and java use the keyword package
• Module boundaries can be “kind of implemented” with
  header files (mylib.h) and object files (mylib.o) in C
   159.331                   Prog Lang & Alg                     2
          Module Definition
• Demonstrate using a calendar example
  with code bundled into a Date package
• In Ada we have package specification
  and package body
• In C we have header file and normal
  source code file for the implementation
(You can tell this idea was grafted onto C
  and is rather less than orthogonal…)
159.331            Prog Lang & Alg           3
159.331   Prog Lang & Alg   4
The Ada syntax distinguishes
between the
package specification and the
package body

   159.331                  Prog Lang & Alg   5
C does not distinguish so strongly between specification
and implementation, but conventionally we use .h and .c files,

 159.331                   Prog Lang & Alg                       6
159.331   Prog Lang & Alg   7
• Two kinds of names supported:
   – Public - accessible to the user (of the package)
   – Private - inaccessible to the user
• Languages have various mechanisms for enforcing these
  (or not)
• C++ and other OO languages like Java generally have
  explicit keywords for this sort of data hiding
• C uses extern keyword for public names, and static
  for private ones (another non-orthogonal use of the
  static keyword!)
• Ada does it by syntactic means (ie you can tell whether
  something is public or private from the other syntax)
• Some Pascals and older languages like Modula use
  export statements
    159.331                    Prog Lang & Alg          8
                   Module Use
• Having set up the module interface and provided an
  implementation (in a file or library) Ada allows
  us to use the package via its with clause
• C convention is just to #include the .h file
• Generally this means that all the package definitions
  become available (in scope) and can be used
  without the compiler complaining it does not
  understand your “type appliance occurrences”
• C++ has a using namespace mechanism, Java has
  an import statement
  159.331               Prog Lang & Alg                   9
159.331   Prog Lang & Alg   10
159.331   Prog Lang & Alg   11
            Module Scope Rules
• In Ada, defining a package only declares its name
• Any public name in it will need to be de-referenced
  using dot notation
• eg we write Text_IO.Put instead of just Put
• Or import java.applet.Applet; to allow access to the
  Applet class
• Sometimes this is annoying so have in Ada use clause
  or using namespace in C++, or import java.applet.*;
  in Java
• Modula has a FROM Module IMPORT N1, N2,… to
  avoid the problems of namespace clutter from Ada’s
  all-or-nothing approach.
  159.331              Prog Lang & Alg            12
• Remember why it is useful to have only enough
  of a package in scope as we need…
• It enables the type checking process
• It means we do not accidentally get confused
  between one of our own identifiers and some
  that got imported from an obscure package
  namespace we did not realise we were
• Generally your own declarations will hide
  (make invisible) those imported - this can cause
  you unexpected effects.
  159.331             Prog Lang & Alg          13
               Representation Parts
• It is unfortunate that representation internals are
  displayed openly in the specification part of data (both in
  Ada and C - it is of course done for efficiency)
• This internal structure is actually what we want to hide
• Strictly this representation part information does not
  belong in either the specification part nor the
  implementation part
• The compiler should not have to have access to the
  implementation (source code) to do type checking on the
  user’s usage code
• Few languages do this properly (with good orthogonality
  between specification, representation and implementation
    159.331                Prog Lang & Alg              14
             Abstract Data Types
• A normal data type is a set of values often available as
  literals, together with a set of operations for their
• An abstract data type (ADT) is a named data type
  defined solely through operations for creating and
  manipulating values of that data type
• Surprisingly many modern languages do not have an
  explicit ADT mechanism. Module/package with
  private parts is almost adequate in many cases - but
  it is not a proper ADT mechanism
• Modules just contain types, whereas an ADT is a
  159.331                Prog Lang & Alg               15
Ada has no ADT mechanism so this is just in “pseudo-Ada”

159.331                Prog Lang & Alg                     16
• In an ADT the operations (or functions) that
  can be done on them are part of the ADT
  specification itself

• The ADT idea is the basis for classes and
  Objects in Object-Oriented languages
• where they are supplemented by the powerful
  ideas of inheritance and dynamic binding

 159.331            Prog Lang & Alg          17
• Often a lot of the code we write is more specific than it
  really needs to be
• For example if we write a linked-list we have in some
  language s no choice but to say explicitly what type of
  data items the list will contain
• Languages with the idea of generics allow us to write
  one linked list code once and for all, that can be
  customised later to deal with lists of any data type
• Ada has generic routines and modules, C does not. C++
  has the template mechanism for generics, Java from
  JDK 1.5 onwards has generics.
   159.331               Prog Lang & Alg               18
• A generic unit (of code) is a template from
  which the actual unit(s) of code is/are made
  by the compiler - in a process known as
• So if we have a “recipe” or template for a
  binary-tree generic, we can have this
  instantiated to make a binary-tree-of-dates
  for example
• Ada also has generic types - known as
  discriminated types in Ada and with a
  different notation

 159.331             Prog Lang & Alg             19
159.331   Prog Lang & Alg   20
159.331   Prog Lang & Alg   21
• A program will generally be composed of modules
  (perhaps only one which may be anonymous or
• Some languages and their environments allow
  separate compilation of smaller units than modules
• In many systems a an object file (nothing to do with
  OO) from a single routine is indistinguishable from
  that from a whole compiled module
• Generally what we care about is the dependency
  relationships between the parts of programs
• If I change one part of my huge program just how
  much do I need to recompile?
  159.331               Prog Lang & Alg              22
• When a module B uses the specification part
  of module A we say B is dependent on A
• This means that information from A may be
  (and probably is) incorporated into the object
  file for B - so if I have changed A I will
  need to recompile B as well as A to ensure
  consistency of the final binary executable
• Even modern languages do not address this
  issue much - we need some tools at the
  operating system or programming
  environment level like make or ant
 159.331             Prog Lang & Alg           23
  Specifying Program Composition
• This is not an easy task
• Various conventions help us but often a system inserts
  all possible necessary object files in a library and
  compiles/links against the whole library hoping all
  references will be retrieved and resolved.
• Often works if libraries well designed but can get
  conflicts if names reused and we end up having to
  worry about the order of search for the libraries
• Ada works this way. C can do too but is more likely
  to result in conflicts

  159.331               Prog Lang & Alg              24
             Dependency Conflicts
• Makefile - see man make or GNU gmake
• This defines you dependencies a nd rules for
  making your program - a simple example:
all : myprog.exe
myprog.exe : myprog.c mysubs.c myheader.h
   gcc -o myprog.exe myprog.o mysubs.o -lm
make knows how to make .o files from .c files, and here
 we tell it to use the gcc compiler to link our program
 files alongwith the maths library into our binary
 executable file. If we edit files, their timestamps can be
 used to resolve what needs to be recompiled.
   159.331               Prog Lang & Alg                25
• Make can go wrong if the timestamps on the file are
  inconsistent on for example a distributed filesystem
• Note that the indent character in a makefile has to be a
  tab character
• Make is widely available on many proprietary systems
  and there is also a free GNU version
• It has some quite sophisticated built in rules and is
  relatively easy to customise
• A similar (newer) program is ant - which uses XML
  to specify the dependencies and rules etc, instead of
  make’s syntax.
• There is also a program called Imake for making

  159.331               Prog Lang & Alg              26
              Orthogonality of Program
• Although blocks, subprograms, modules and
  programs form a hierarchy to which orthogonality
  need not apply, most languages that have blocks,
  subprograms and modules do allow them to be
  combined freely inside one another.
• Obviously programs - at the top of the hierarchy are
  not allowed inside other structures.

    159.331            Prog Lang & Alg           27
  Examples of Imperative Languages
• We have mentioned at             • Mentioned in passing
  various levels:                    also SETL and ABC
   –   C
   –   Ada
                                   • See the HOPL link on
   –   Algol 68
                                     the web pages
   –   Pascal
   –   Modula-2                    • Some striking features
   –   COBOL                         of two less common
   –   Fortran                       languages :
   –   BASIC
                                           – Icon
                                           – Postscript

   159.331               Prog Lang & Alg                  28
• Looks close to Pascal - but has cunning idea
  that some computations yield more than one
• eg roots of quadratic :
  -b +/- sqrt( b^2 - 4ac ) / ( 2a)
• Yields two answers, as does:
  every write( find( “m”, “Amsterdam” ) )
• Icon allows suspension of an expression and
  consequent resumption of a function to get the
  next value
  159.331                Prog Lang & Alg         29
Think of the (multiple) results getting suspended in some way
on an output stack

  Suspendable expressions are called generators in Icon

 159.331                   Prog Lang & Alg                      30
• Primarily intended as a control language for
  sophisticated(90’s) / all (now) printing
• Send a PostScript program to the printer
  rather than just a plain piece of text - the
  program encapsulates all the desired
  formatting information to render the piece
  of text the way you want
159.331            Prog Lang & Alg           31
• PostScript programs a stack machine
• every operand is pushed anonymously onto a stack, the
  operand stack, and
• every operator works on the top N elements of the
  operand stack, replacing them with M results
   – eg 40 20 add puts 40 on the stack, then 20, then pulls them
     both off and leaves the value 60 on the stack
• Flow-of-control done through operators that work on
   – eg a b gt {P} {Q} ifelse stacks boolean a > b, stacks 2
    procedures then unstacks three items and pushes either {P} or
    {Q} onto execution stack - like if a > b then P else Q endif
• PostScript has about 250+ built-in operators of which
  100+ manipulate graphics. The showpage operator
  effects the final printing
   159.331                 Prog Lang & Alg                  32
     Imperative Languages Summary
• Imperative languages are based on the fully specified and
  fully controlled manipulation of named data in a step-wise
• A data declaration binds a name to a type and possibly to a
• Typical basic types are integers, characters and real
  numbers. New types can be made using type constructors.
  Examples of type constructors are enumerations, arrays and
• Types are name-equivalent if they have the same names,
  and structure-equivalent if they have the same values and
  allow the same operations. Coercions and casts allow minor
  evasions of a type system.
    159.331               Prog Lang & Alg              33
• Two features in a language are orthogonal if they
  can be freely combined without restricting each
  other in any way
• Internal state is modified through assignment
  statements, external state through output
  statements. The values used derive from
• The main flow-control mechanisms are
  sequencing, selection, repetition and routine
• Run-time errors can be caught by using signals
  and exceptions. They turn the error into a flow-
  of-control issue. Neither method is perfect.
   159.331            Prog Lang & Alg          34
• In program construction, four levels of hierarchy
  can be distinguished: blocks; routines; modules
  or packages; and programs.
• Scope rules determine which declaration(s) define
  a given name. If more than one declaration is
  identified from the syntactic scope rules then
  contextual scope rules are needed to
• Procedures do not yield a value, functions do,
  and operators are just a different notation for
  functions. The main parameter passing
  mechanisms are call-by-value and call-by-
   159.331            Prog Lang & Alg          35
• A module defines an interface, represented by its
  specification part. The implementation part is separate
  and hidden from the interface user. In principle a separate
  representation part is needed, but in many languages this
  is included in the specification part.
• An Abstract Data Type (ADT) is a named data type
  defined solely through routines for creating, manipulating
  and deleting values of that data type; all internal structure is
  hidden from the user. It differs from a module in that a
  module contains a type definition from which items can be
  declared, whereas an ADT is a type that is used directly to
  declare items
• A generic x-unit is a template that is used to derive x-units
  from. The derivation process is called instantiation.
  Generic units can be parameterized.
     159.331                Prog Lang & Alg                 36
• Final program            • Imperative programming
  composition is generally   is covered in Chapter 2
  done through the system    of Bal & Grune, and in
  linker. The main           Chapters 5,6,7,8,9,10,11
  problem is of ensuring     of Sebesta.
  the consistency of the
  object files linked. The
  help of some program     • Next - the Objected
  management system is       Oriented programming
  indispensable, since       language paradigm -
  programming languages      which builds on the ADT
  do not contain much to
  help with this.

 159.331              Prog Lang & Alg            37