Next: Resolve, Up: Overloading
As an example of overloading, consider adding realType to Mystery
as a new basic type.
The keyword REAL would be used to denote the new type in the source
program, and an appropriate floating-point representation will be used for
constants.
Here are the necessary rules:
RULE: Type ::= 'REAL'
COMPUTE Type.Type=realType;
END;
RULE: Expr ::= Float
COMPUTE PrimaryContext(Expr,realType);
END;
Addition and comparison operators must be defined and associated with the appropriate operator indications:
PreDefOpr(PlusInd, rAddOp, (realType,realType): realType)
PreDefOpr(GrtrInd, rGtrOp, (realType,realType): boolType)
These lines would be added to the file specified in the referto
parameter of the PreDefOp module instantiation
(see Language-Defined Operators).
No changes would be required in the definition of the type checking process within an expression discussed earlier (see Type Analysis in Expressions).
Consider expression nodes for the following two expressions in the extended language:
1 + 2
3.4 + 5.6
The value of the Operator.Oper attribute in the first case would be
set by the type analysis computation to iAddOp;
in the second case Operator.Oper would be set to the value rAddOp.
Suppose now that we wanted to add both negation and subtraction to the extended language. This would require definition of a monadic context:
RULE: Expr ::= Operator Expr
COMPUTE MonadicContext(Expr[1],Operator,Expr[2]);
END;
Negation and subtraction are usually both represented by the operator
indication -, so the following lines would be added to the file
specified in the referto parameter of the PreDefOp module
instantiation:
PreDefInd('-', Operator, MinusInd)
PreDefOpr(MinusInd, iNegOp, (intType): intType)
PreDefOpr(MinusInd, rNegOp, (realType): realType)
PreDefOpr(MinusInd, iSubOp, (intType,intType): intType)
PreDefOpr(MinusInd, rSubOp, (realType,realType): realType)
Notice that the - indication is associated with operators that have
different numbers of operands.
Consider the nodes of the expression tree corresponding to the following expression in the extended language:
(-1.2) - 3.4
The value of the Operator.Oper attribute in the monadic context
would be set by the type analysis computation to rNegOp;
in the dyadic context Operator.Oper would be set to the value
rSubOp.
If overloading is allowed, it may be impossible to identify an operator in a given context. For example, consider the following expression:
1 - 2.3
None of the operators related to MinusInd can accept
an integer value as its left operand and a real value as its right operand.
In such situations the type module cannot identify the operator;
it therefore sets the Operator.Oper attribute to NoKey and
reports an error
(see Error Reporting in Type Analysis).