Lunar Programming Language

by David A. Moon
January 2017 - January 2018



Protocols

A protocol involves one or more classes (usually abstract) and one or more function bundles. Informally, a protocol requires that each of those function bundles must have an applicable method for all members of each of those classes. It may have different methods for different members. A protocol also requires that that method returns a result that is a member of a specific type.

The compiler warns if it determines that a required method is missing or cannot be proven to return the correct type. Requirements are not guaranteed to be enforced; the compiler just warns when it can.

TODO: Do we need run-time enforcement of result types that cannot be checked at compile time?

The compiler can use result types declared in protocols to infer the static type of the results of expressions.

More precisely, a protocol is defined by a series of require statements, each of which defines one requirement. The require statements can immediately follow the defclass statement or can be separate.

A requirement has the same syntax as a method definition, except there is no method body and it starts with require instead of def. As in a method definition, an optional result type can be placed at the end of a requirement, introduced by =>. If not present, the result type defaults to everything. The syntax is

$require methodhead

For any possible list of actual parameters to the function, if a method with the same formal parameters as the requirement would have been applicable if it existed, there must be a method applicable to those actual parameters. The formal parameters of that method need not be the same as the formal parameters of the requirement; usually they are subtypes. The result returned by the most specific applicable method must be a member of the result type specified in the requirement.

Like a method definition, a requirement can be generic.

In a requirement, the name ? can be used in place of a formal parameter type or a result type. This stands for a type that is not specified by the requirement. An applicable method with any type for that formal parameter, or returning any type of result, will do.

If ? appears more than once in a requirement, the corresponding types do not have to be the same type.

For examples, see Sequences


Previous page   Table of Contents   Next page



Creative Commons License
Lunar by David A. Moon is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Please inform me if you find this useful, or use any of the ideas embedded in it.
Comments and criticisms to dave underscore moon atsign alum dot mit dot edu.