Home > Raku > Yes, but don’t!

Yes, but don’t!

masukomi, likes to play with fire and who am I to stop him? In fact, I shall aid him by answering his question: “#RakuLang is there a way to augment / monkeypatch a class to give it another parent class ?”.

There are a few obstacles. First, a class tends to be composed when we get hold of it and secondly, the list of parents is in fact a List. Both problems vanish when we use nqp.

class A1 { }
class A2 { method cheating { say ‘Yes, but don't!’ } }

class B is A1 { }

use nqp;

my \parents := nqp::getattr(B.HOW, Metamodel::ClassHOW, '@!parents');
nqp::push(parents, A2);
B.^compute_mro;
B.^compose;

dd parents; # (A1, A2)
say B.^mro; # ((B) (A1) (A2) (Any) (Mu))

B.new.cheating; # Yes, but don't!

In addition to re-.compose we have to re-compute the MRO, as there is some caching going on. In fact, you should expect to upset the compiler quite a bit when fooling around with things that are meant to be rather static. If you burn yourself with this spell … well, it’s a level 9 fire spell after all.

The proper way to get the same result would be as follows.

use MONKEY;

class A3 { }

augment class B { also is A3 }

# ===SORRY!=== Error while compiling /home/dex/projects/raku/tmp/2021-03-08.raku
# Parents cannot be added to class 'B'after it has been composed

If I can muster the courage I shall challenge jnthn with a Rakubug.

Categories: Raku
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment