1 / 32

The SR Programming Language Chapters 2-6

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.

gperry
Download Presentation

The SR Programming Language Chapters 2-6

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. The SR Programming Language Chapters 2-6 Scott Mantei

  2. 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. */

  3. 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. >>).

  4. 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. =, !=, <, <= )

  5. 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 )

  6. 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 )

  7. 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.

  8. 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

  9. 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 towhich p points

  10. 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.

  11. 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

  12. 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.

  13. 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.

  14. 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

  15. 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

  16. 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.

  17. 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

  18. 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

  19. 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

  20. 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

  21. 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)

  22. 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.

  23. 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.

  24. 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

  25. 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.

  26. 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

  27. 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.

  28. 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

  29. 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

  30. 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)

  31. 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)

  32. 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)

More Related