Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
language:types2 [2026/06/25 11:00] – [Macros] rajitlanguage:types2 [2026/06/27 20:05] (current) – [Example user-defined type with macros and methods] rajit
Line 285: Line 285:
  
 <code act> <code act>
-defproc stack (chan(int)? in; chan(int)!out )+defproc stack (chan(int)? in; chan(int)! out)
  
   ...   ...
Line 317: Line 317:
  
 <code act> <code act>
-defproc stack (chan(int)? in; chan(int)!out )+defproc stack (chan(int)? in; chan(int)! out)
  
   ...   ...
Line 384: Line 384:
 In the linked example, ''fixpoint<a,b>'' corresponds to a fixed-point number with ''a'' integer bits and ''b'' fractional bits following the standard Q(a,b) format. In the linked example, ''fixpoint<a,b>'' corresponds to a fixed-point number with ''a'' integer bits and ''b'' fractional bits following the standard Q(a,b) format.
  
 +==== Example user-defined type with macros and methods ====
 +
 +Combining some of these ideas, the following is an example of a user-defined type corresponding to an N-bit signed integer. Only some methods are defined.
 +
 +<code act>
 +template<pint W>
 +deftype signed_int (int<W> x)
 +{
 +    { W > 1 : "Need sign bit plus one bit at a minumum" };
 +    methods {
 +        function plus (signed_int<W> s) : signed_int<W>
 +        {
 +            chp {
 +               self.x := x + s.x // 2's complement!
 +             }
 +         }
 +        macro display()
 +        {
 +            [ x{W-1} = 1 -> log_p("-", (~x+1)) 
 +            [] else -> log_p(x)
 +            ]
 +         }
 +         macro set(int<W> v)
 +         {  
 +              x := v
 +          }
 +     }
 +}
 +</code>
 +
 +In this scenario, the following CHP adds two numbers, and then displays the result using a ''log'' statement.
 +<code act>
 +defproc test()
 +{
 +   signed_int<8> u, v;
 +   chp {
 +       v.set(1);
 +       u.set(-3);
 +       v := v + u;
 +       log_st("");
 +       v.display();
 +       log_nl("")
 +    }
 +}
 +</code>
 +This should display ''-2'' as a log message when run using ''actsim''.