the sr programming language chapters 2-6 scott mantei

32
The SR Programming Language Chapters 2-6 Scott Mantei

Post on 21-Dec-2015

226 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: The SR Programming Language Chapters 2-6 Scott Mantei

The SR Programming Language Chapters 2-6

Scott Mantei

Page 2: The SR Programming Language Chapters 2-6 Scott Mantei

Types, Variables, and Assignments

• An SR program is constructed out of sequences of tokens.

• The tokens include identifiers, keywords, literals, operators and separators.

• White space - blanks or tabs - may appear between any two tokens.

• Newline characters and semicolons can terminate declarations, statements, or expressions.

• SR provides two different types of comments:

# This is a one line comment

/* This is a multiple line comment. */

Page 3: The SR Programming Language Chapters 2-6 Scott Mantei

SR's Basic Types

• SR's basic types are bool, char, int, real, and string.

• bool has two literals: true and false, and it's operators are and, or, xor, not.

• int is an unsigned sequence of digits:

Decimal 0-9

Octal 0-7 followed by q or Q

Hexadecimal 0-9,a-f or A-F followed by x or X (must begin with a digit)

11 1333Q 0abcdefX

int operators include arithmetic operators (e.g. +, *, %); bitwise operators (e.g. not, or); and bit-shifting operators

(e.g. >>).

Page 4: The SR Programming Language Chapters 2-6 Scott Mantei

• A real (floating-point) has the general form

integer part . fraction_part exponent_part

11.2 0. .0 1.23e-45

real operators are the same arithmetic operators as for integers.

• Character literals are single ASCII characters enclosed in single quotes.

'a’ 'Z'

In addition, character literals can contain the special characters such as:

'\n' '\a'

• Strings are sequences of zero or more ASCII characters enclosed in double quotes.

• String literals may also contain special characters (e.g. '\n').

"" "alpha" "here is a \" in the middle"

• The string type has one binary operator, ||, for string concatenation. Each operand must be a string or a character.

• Relational operators compare operands and return a boolean value that reflects the result of the comparison (e.g. =, !=, <, <= )

Page 5: The SR Programming Language Chapters 2-6 Scott Mantei

User-Defined Types

• User defined types are defined by the programmer.

• They are array, enumeration, record, union and pointer.

• Enumeration types define symbolic literals. Each enumeration type is an ordered type.

enum( red, blue, yellow )

• A record type defines a collection of data values. Its definition contains a list of one or more field definitions seperated by semicolons.

• Each field definition defines one or more field names of the same type.

rec( height, width : real )

rec( name: string[10]; grade: int )

Page 6: The SR Programming Language Chapters 2-6 Scott Mantei

Unions

• A union type is a collection of other types, each with a tag (name).

• Unlike a record, the value of a union is just one of its named fields; which field is the union's current value can vary as the program executes.

union( radius, circumference: real ) union( name : string[10]; id: int )

Page 7: The SR Programming Language Chapters 2-6 Scott Mantei

Pointers

• Pointer types define references to data objects. They have two forms.

ptr type ptr any

• The first form defines a pointer to an object of a specific data type. The second form defines a pointer to an object of any type.

ptr int ptr rec(i1, i2: int) ptr [7] int

• The generic pointer type, ptr any, can reference a value of any type. Such a pointer can be assigned to and copied, but it can't be dereferenced.

• The pointer literal null is used to indicate a pointer value that points to no valid object.

Page 8: The SR Programming Language Chapters 2-6 Scott Mantei

Variables and Constants

• A variable can be simple, in which case it holds one value of its type.

• Or a variable can be an array, in which case it holds multiple values of its type.

var i, j, k: int var front: int := 0, rear: int := 0

var line: string[80] := ""

var k: person := person("karl", 92)

var a[10]: int

• A constant declaration is just a specific form of a variable declaration. const PI: real := 3.141592654

Page 9: The SR Programming Language Chapters 2-6 Scott Mantei

References and Dereferences

• A variable's name is used to refer to either the value of the variable or to the storage location associated with the variable.

• Which meaning is intended depends on the context in which the reference occurs.

• The value of a field in a record or union can be obtained by following the name of the variable by a dot (.) and the name of the desired field.

var x: rec( name: string[10]; grade: int )

use x.name and x.grade to reference the field literals.• With pointer variables, the value of the object to which the variable points

can be obtained by following the name of the variable by a hat (^).

var p: ptr int

p^ # the integer to which p points

Page 10: The SR Programming Language Chapters 2-6 Scott Mantei

Dynamic Storage Allocation

• Two predefined functions provide dynamic storage allocation and deallocation:

new (type) free (expr)

• new returns a pointer to a new instance of storage for a variable whose type is specified by the type argument.

• free releases the storage of an object allocated by new.

Page 11: The SR Programming Language Chapters 2-6 Scott Mantei

Assignment• An assignment operator evaluates an expression and assigns its value

to a variable.

variable := expr

• Assignment is defined for all types of variables.

• The type of the expression and the type of the variable must be compatible.

i := 1 sum := sum +1 j := i + sum

• There are also a group of assignment operators called increment and decrement operators.

i++ i +:= 1

• The swap operator exchanges the values of two variables, which must have the same type.

j :=: k

Page 12: The SR Programming Language Chapters 2-6 Scott Mantei

Basic Input Output

• Values can also be assigned to variables by reading them from input.

read (variable, variable, ...)

• This normally assigns one value from the standard input file to each variable in the given list.

• Values of expressions can be written to output.

write (expr, expr, ...)

• The write routine evaluates each expression and outputs its value to the standard output file.

Page 13: The SR Programming Language Chapters 2-6 Scott Mantei

Sequential Control

• SR statements that alter the flow of control in sequential programs.

• The skip statement has no effect and terminates immediately.

• The stop statement terminates execution of an entire program. It has one of two forms:

stop or stop(expr)

• If expr is present, its integer value is returned as the exit status.

Page 14: The SR Programming Language Chapters 2-6 Scott Mantei

• The if statement is SR's only alternative statement.

if x < 0 -> x := -x fi

if x <= y -> minimum := x

[] else -> minimum :=y

fi

• The do statement is used for indefinite iteration.

do X < Y -> Y := Y-X [] Y < X -> X := X-Y

od

Page 15: The SR Programming Language Chapters 2-6 Scott Mantei

• The for-all statement is used for definite iteration. fa i := 1 to 10 -> write(i) af

fa i := 1 to 20 by 2 -> write(i) af

fa i := 1 to 30 st j = 0 -> write(i) af

• The exit statement is used to force early termination of the smallest enclosing iterative statement.

exit

• The next statement is used to force return to the loop control of the smallest enclosing iterative statement.

next

Page 16: The SR Programming Language Chapters 2-6 Scott Mantei

Procedural Declaration• A procedure defines a body of code that can be invoked from other

code.

• It can take parameters and return a value.

procedure procedure_id ( formal_list ) returns variable_name : type

block

end

• A procedure is invoked by a call statement.

• A procedure must be declared before it is used. More precisely, the procedure heading, but not necessarily the entire body, must appear before the procedure is invoked.

• Parameters are passed to procedures by copying or by address; the return value is passed by copying.

Page 17: The SR Programming Language Chapters 2-6 Scott Mantei

• A return statement transfers control to the end of the enclosing procedure; it causes the procedure and the invocation it is servicing to terminate.

resource main()

procedure factorial(x: int)

var fact := 1

fa i := 2 to x -> fact *:= i af

write(x, "factorial is", fact)

end

#find factorial for each positive number input

var x: int

do true ->

writes("enter a number > 0 ")

writes("(or = 0 when done): ")

read(x)

if x = 0 -> exit

[] x < 0 -> write("number must be >= 0")

[] x > 0 -> call factorial(x)

fi

od

end

Page 18: The SR Programming Language Chapters 2-6 Scott Mantei

Operation and Proc Declarations

• A procedure is really an abbreviation for an operation declaration and a proc.

• A procedure is sufficient in simple cases.

• However, the requirement that a procedure be declared before it is used is a limitation - it constrains the order in which procedures appear within a resource, and it does not allow for mutually recursive procedures.

op insert(item: person) op differ(s1, s2: string[*]) returns place: int

op left(i: int) returns lft: int

Page 19: The SR Programming Language Chapters 2-6 Scott Mantei

• The operation declaration must appear before the proc is declared and before the operation is invoked.

• An operation restriction indicates how the operations can be invoked. The four different operation restrictions are

• {call} {send} {call, send} {send, call}

• The operation resulting from a procedure declaration has the call restriction.

• The send restriction is used in concurrent programming.

• The default restriction is {call, send}, i.e., no restriction

• Each operation is implemented by only one proc.

proc operation_id ( formal_list ) returns result_id block

end

Page 20: The SR Programming Language Chapters 2-6 Scott Mantei

Operation Types

• An operation type declaration introduces a new identifier that is a synonym for the specified type of operation.

• Optypes are used for the abstraction they provide in specifying related parameter specifications.

• They also help reduce repetitious typing...repetitious typing...repetitious typing...repetitious typing...repetitious typing...repetitious typing...repetitious typing...repetitious typing

optype intfun = (n: int) returns sum: int op fact: intfun

Page 21: The SR Programming Language Chapters 2-6 Scott Mantei

Operation Capabilities

• An operation capability is a pointer to an operation.

• Such pointers can be assigned to variables, passed as parameters, and used in invocation statements.

op d(x:int)

var x: cap d

x := d

x(387)

Page 22: The SR Programming Language Chapters 2-6 Scott Mantei

Resources and Globals

• In general, an SR program consists of a collection of resources and globals.

• Resources and globals both have modular structures, but they are created and used differently.

• A resource defines a template from which resource instances can be created dynamically; resource instances can also be destroyed.

• A global is essentially a single, unparameterized, automatically created instance of a resource.

Page 23: The SR Programming Language Chapters 2-6 Scott Mantei

• A resource can be viewed as an abstract data type in that it consists of a specification part, which specifies the interface of the resource, and a body part, which contains the code that implements the abstract object.

• A global is a collection of objects shared by resources and other globals in the same address space.

• In its simplest usage, a global contains declarations of types, constants, and variables that are used throughout the program.

• In its more complex usage, a global also contains operations and associated code to provide a library.

Page 24: The SR Programming Language Chapters 2-6 Scott Mantei

Resource Specifications and Bodies

• Each resource is composed of two parts: the spec, which specifies the interface of the resource, and the body, which contains the code that implements the resource.

resource resource_name

imports

constant, type, or operation declarations

body resource_name(parameters)

imports

declarations, statements, procs

final code

end resource_name

Page 25: The SR Programming Language Chapters 2-6 Scott Mantei

• The parameters and all the parts in the spec and body are optional, as is the resource name following end.

• The objects declared in a resource spec are implicitly exported and are visible to other resources.

• Import clauses are used to acquire access to objects exported by other components.

• A resource body gives the implementation of a resource.

• Body components may be declared in any order. Declarations and procs may be intermixed.

Page 26: The SR Programming Language Chapters 2-6 Scott Mantei

Creating and Destroying Resource Instances

• Instances of resources can be created during program execution.

• Since several instances of a given resource can be active at the same time, we need some means to distinguish between the different instances; this is provided by resource capabilities.

• A create expression is used to create an instance of a resource.

s1 := create Stack(10) s2 := create Stack(20)

• The destroy statement destroys a resource instance.

destroy s1

Page 27: The SR Programming Language Chapters 2-6 Scott Mantei

Initial and Final Code

• Initial code is executed when a resource is created.

• Initial code appears in the top-level along with procs and resource variables.

• Final code is executed when a resource is destroyed.

• Final code appears as a single block of code, introduced by the keyword final and terminated by the keyword end.

Page 28: The SR Programming Language Chapters 2-6 Scott Mantei

Globals• The simplest form of globals is used to declare constants, types, and variables

that will be shared by resources or other globals

global Characters const TAB := ‘\t’ # Horizontal Tab

const CR := ‘\r’ # Carriage Return

end

• A more general form of global also includes a body.global global_name

imports

declarations

body global_name

imports

declarations, statements, procs

final code

end global_name

Page 29: The SR Programming Language Chapters 2-6 Scott Mantei

• All names declared in the spec are exported: those in the body are private.

global Diagonal

const N := 20

var a[N,N]: real := ([N] ([N] 0.0))

body Diagonal

fa i := 1 to N -> a[i,i] := i af

end Diagonal

Page 30: The SR Programming Language Chapters 2-6 Scott Mantei

Files and File Access

• A variable of the type file contains a descriptor for a UNIX file.

• Three literals are used to access the corresponding UNIX file.

stdin the standard input device(usually the keyboard)

stdout the standard output device(usually the display)

stderr the standard error device(usually the display)

Page 31: The SR Programming Language Chapters 2-6 Scott Mantei

I/O Operations• read write provide simple I/O facility

• printf scanf provide formatted I/O

• get put provide I/O on streams of characters

• seek where support random access to disk files read(x)

write(x)

printf("a[%d] is %d\n", i, a[i])

scanf("%d",a)

get(f, buffer)

put(f, "*")

seek(f, ABSOLUTE, i) # can use ABSOLUTE RELATIVE # or EXTEND for 2nd parameter

n := where (f)

Page 32: The SR Programming Language Chapters 2-6 Scott Mantei

Command-Line Arguments

• Two predefined functions - numargs and getarg - provide access to the arguments of the UNIX command that invoked execution of an SR program.

• numargs returns the number of user-supplied arguments, not counting the command name.

n := numargs()

• getarg reads the command-line argument specified positionally by its first parameter into its second parameter.

var pn: string[40] getarg(1, pn)