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
intro_example:pure_struct [2025/05/07 09:08] – [Methods] rajitintro_example:pure_struct [2025/05/18 15:07] (current) rajit
Line 1: Line 1:
 ====== Using pure structures ====== ====== Using pure structures ======
  
-A [[language:types2:data#pure_structures|pure structure]] is a user-defined data type that contains only ''int''/''bool'' or other pure structures. An example of a pure structure is:+A [[language:types2:data#pure_structures|pure structure]] is a user-defined data type that contains only ''int''/''bool'' or other pure structures. Pure structures are analogous to C/C++ ''struct''s, and can be used to organize data and  
 +make CHP more human-readable. An example of a pure structure is:
  
 <code act> <code act>
Line 56: Line 57:
  
  
-defproc cache(chan?(int<32>) A; chan?(bool) RD; chan!(int<32>) DI; chan!(int<32>) DO)+defproc cache(chan?(int<32>) A; chan?(bool) RD; chan?(int<32>) DI; chan!(int<32>) DO)
 { {
    cache_entry C[256];    cache_entry C[256];
Line 74: Line 75:
              DI?ce.data;              DI?ce.data;
              ce.tag := addr{31..8};              ce.tag := addr{31..8};
 +             C[addr{7..0}] := ce
 +      ]
 +   ]
 +  }                  
 +}
 +</code>  
 +
 +Note that method functions, like other functions in ACT, are pure functions. In other words, they cannot change the fields of the structure. If you need to modify the fields of the structure, special ''macro'' methods are supported. These can contain arbitrary CHP fragments.
 +
 +<code act>
 +deftype cache_entry (bool valid; int<32> data; int<24> tag) 
 +
 +    methods {
 +        function match (int<32> addr) : bool
 +        {
 +           chp {
 +              self := valid & tag = addr{31..8}
 +           }
 +         }
 +         macro setval (int<32> addr; int<32> dv) {
 +            valid+; 
 +            data := dv;
 +            tag := addr{31..8}
 +         }
 +    }
 +}
 +
 +defproc cache(chan?(int<32>) A; chan?(bool) RD; chan?(int<32>) DI; chan!(int<32>) DO)
 +{
 +   cache_entry C[256];
 +   int<32> addr, dv;
 +   bool cmd;
 +   cache_entry ce;
 +   
 +   chp {
 +     *[ A?addr,RD?cmd;
 +        [cmd -> // read command
 +              ce := C[addr{7..0}];
 +             [ ce.match(addr) -> log ("cache hit!"); DO!ce.data
 +             [] else -> log ("cache miss!"); DO!0
 +             ]
 +       []~cmd -> // write command
 +             DI?dv;
 +             ce.setval (addr, dv);
              C[addr{7..0}] := ce              C[addr{7..0}] := ce
       ]       ]