OEP

157

Title

User-defined operators

Summary

Allow user-defined new operators, with overloading on built-in and user-defined types.

Owner

David Wood

Status

Accepted

Date-Proposed

2006-11-17

Keywords

language operators

In occam 2.1, there are a fixed set of operators working only on the built-in primitive types. This proposal extends this for occam-pi through user-definable operators on any types (primitive, array or user-defined). User-defined operators may be monadic (prefix) or dyadic (infix). A modified FUNCTION definition syntax (with operator symbols instead of function names) is proposed:

    
--* Complex number data type
--
DATA TYPE COMPLEX
  RECORD
    INT real:            --* real part
    INT imaginary:       --* imaginary part
:


--* Complex addition (infix operator)
--
-- @param a The first argument
-- @param b The second argument
--
-- @return The complex sum
--
COMPLEX FUNCTION "+" (VAL COMPLEX a, b) IS
  [a[real] + b[real], a[imaginary] + b[imaginary]]:


--* Complex negation (prefix operator)
--
-- @param a The argument
--
-- @return The negative of the argument
--
COMPLEX FUNCTION "-" (VAL COMPLEX a) IS
  [-a[real], -a[imaginary]]:


--* Complex product (infix operator)
--
-- @param a The first argument
-- @param b The second argument
--
-- @return The complex product
--
COMPLEX FUNCTION "*" (VAL COMPLEX a, b) IS
  [(a[real] * b[real]) - (a[imaginary] * b[imaginary]),
   (a[real] * b[imaginary]) + (a[imaginary] * b[real])]:

Operators are overloaded, with resolution by both argument and return types. We can have operators on any occam-pi types.

The following existing dyadic operators may be overloaded:

+ - * / \ PLUS MINUS TIMES AFTER
/\ \/ >< AND OR = <> <= >=

together with these existing monadic operators:

- MINUS ~ NOT

In addition, these new operator symbols may be used, which may be either dyadic or monadic:

@@ $$ % %% && <% %> <& &> <] [> <@ @> @ ++ == ^

Operators with the same symbol are distinct if their parameter and result signatures are distinct. Otherwise, normal block structured scoping rules apply – operators are resolved to the closest enclosing definition whose parameter and result signature matches the context of use.

The types of occam-pi literals are usually inferred from context, but this is not possible when they're being used as arguments to user-defined operators. To avoid ambiguity in this context, integer literals are assumed to be INTs, character literals to be BYTEs and real literals to be REAL32s – unless their types are explicitly flagged. The same rules apply to array literals.

OEP/157 (last edited 2008-03-10 20:39:16 by phw)