Sunday 29 August 2021

Proxying a Function, Callable Attempt and More

As of late I've been again delving into some unfrequent features found in some languages like Groovy and Phyton. One of those features is the "callable" concept in python. Any object is callable (that is, invokable with "()") if it has a __call__ method in its class (or any class up in its inheritance chain). It wrongly came to my mind that we could simulate this feature in javascript by means of creating a Proxy for a function with the apply trap.

I have to admit that I have never used proxies for functions. It's so simple to wrap a function with another function that I've never seen the reason to use the Proxy machinery. So it seemed cool to have found a use case (my main idea behind doing an object callable would be to express with a "myInstance();" call that I want to invoke the main, most important method in that object). Well, if I had fully read the documentation, I would have seen this: The target must be a callable itself. That is, it must be a function object.. So my approach was useless. The curious thing is that you won't get an error when creating the Proxy with the apply trap for a "non function", but when you try to invoke it.


class Formatter{
    constructor(){
        this.defaultWrapText = "||";
    }

    format(str){
        return str.toLowerCase();
    }

    wrapAndFormat(txt, wrapText){
        wrapText = this.defaultWrapText || wrapText;
        return wrapText + this.format(txt) + wrapText;
    }
}

let formatter1 = new Formatter();
console.log(formatter1.wrapAndFormat("HI"));

//let's try to do the formatter1 object a "callable" that would invoke "format". It's like a way to express a "main-default" method in the object 
let callableF1 = new Proxy(formatter1, {
    apply: function(target, thisArg, argumentsList) {
        console.log("invoking as callable");
        return target.format(...argumentsList);
      }
});

//does not work: "caught TypeError: callableF1 is not a function"
// from MDN: The target must be a callable itself. That is, it must be a function object. 
try{
    console.log(callableF1("HeY"));
}
catch(ex){
    console.log(`${ex.name}:\n${ex.message}`);
}

After this I found this article where a very smart guy explains how to do callable objects in JavaScript by inheriting from Function.

The use of a Proxy around the original object/function should be completely transparent to the final user, I already talked about it. For example if I get the name of a proxied function, the name of the target function will be returned. However, there is one case where this "Proxy transparency" seems to fail. If we do a "toString" on a proxied function, we don't get the source of the target function, but a "function () { [native code] }" string, quite odd. Let's see both cases:


function sayHi(){
	console.log("hi");
}

console.log(sayHi.toString());

//output:
/*
function sayHi(){
	console.log("hi");
}
*/

let f3 = new Proxy(sayHi, {
	apply(target, thisArg, argumentsList) {
        console.log("invoking sayHi");
        return target();
	}
});

f3();

//the Proxy is transparent, it returns the name of the target
console.log(f3.name);
//sayHi

//however, toString does not return the source of the target function!
console.log(f3.toString());
//output:
//function () { [native code] }


The behaviour of Function.prototype.bind when applied to a Proxy has quite surprised me. As it returns a new "bound" function, I was expecting that this new function would not be proxied, but it is. So it returns a new Proxy object around the new bound function!


function formatText(txt, str1, str2){
    return str1 + str2 + txt + str2 + str1;
}

let formatProxied = new Proxy(formatText, {
    apply(target, thisArg, argumentsList) {
        console.log("invoking formatText");
        return target(...argumentsList);
	}
});

console.log("- using proxy:");
console.log(formatProxied("Bonjour", "|", "+"));
console.log(formatProxied.name); //formatText

console.log("---------------");
console.log("- after binding");

let boundFormatProxied = formatProxied.bind(null, "Bonjour");
console.log(boundFormatProxied("*", "+"));
//it returns a new Proxy object that proxies the new bound function!!!

// I can see how the name now is "bound formatText"
console.log(boundFormatProxied.name);

console.log("---------------");

// output:
- using proxy:
invoking formatText
|+Bonjour+|
formatText
---------------
- after binding
invoking formatText
*+Bonjour+*
bound formatText
---------------


Notice in the example above that when we bind a function, the name of the returned function is: "bound 'original name'"

Sunday 22 August 2021

Torture-free Town

In the last years my perception of Spain has changed a lot. I still has a very strong Asturian and European identity (and that plays a role in my strong attachment to France, that at one point was the maximum expression of European civilization), but I'm not "in conflict" with Spain anymore. I no longer think Asturies should break away from Spain. After many centuries of living together with the other different cultures of the Peninsula I think there are enough common points to stay together (though for sure it's really important that the image that Spain projects outside stops being focused on Southern and Mediterranean Spain and finally starts to show the sheer diversity and plurality of the country). This said, there are things that the world associates with Spain that I profoundly distaste and continue to ashame me (me and a huge part of the population). Obviously bullfighting is one of them.

Modern "Spanish bullfighting" is rooted in southern Spain, but the disease was spread all over the country, as a form of trying to create a common tradition working as one of the basis of a fictitiously homogeneous country (as I've just said, Spain is a very heterogenous country due to its geography, climate, history...). This form of public torture made its way into northern Spain long ago. In Asturies, Uvieu used to have bullfights (corridas), but they declined in popularity and took place for the last time in 2007. After that the bullring (plaza de toros) went into a dilapidated state and though there are plans to restore it, it will be used only for cultural purposes (concerts...), and there's no intention to bring back torture to it. Unfortunately, for whatever the reason, bullfighting remained popular enough (I read years ago that it was maintained thanks to public fonds) in my town, Xixón, to continue perpetrating these acts of sadism for several days each year in August, during the "Semana Grande" (festivities week). In the last years the demonstrations and gatherings in front of the "Plaza de Toros" to protest against this heinous spectacle and demand its discontinuation have grown in strenght, but no signs from the city council made us think that they would come to an end. The previous, center-"conservative", major was indeed fond of this brutal "tradition", and the current "progressist" one had not given any sign of intending to change this (which indeed was rather disappointing).

So the announcement this week from the major that bullfighting was over has come as a beautiful surprise. While other Spanish minicipalities or autonomous communities officially banned bullfighting, the procedure in Xixón has been fair more simple. The license for organizing bullfights in town expires this year, so a new bid should be organized for the next years, and the city council has decided not to organize it. Simple and straightforward. Obviously a change of major could bring them back, but well, let's enjoy the present!

Obviosly local rednecks have condemned this and are trying to stop it, but I hope it will be to not avail. The local branch of the conservative party PP is collecting signatures against this measure, and the bastards of Vox (there are some stances of this party regarding immigration and criminality that I fully support, but their positions regarding Asturian language, Euthanasia, Animal Rights... make me feel a profund disdain for these idiots) promise to fight back...

It seems like what finally prompted the local council to take this decision was the fact that in this year's bullfights one of the bulls being tortured and murdered was named "feminista" and another one "nigeriano". Obviously this is disgusting, but animal rights and public honor should have been enough to make them take this step.

For all those saying that stopping bullfighting in our town will have negative economical consequences (in commerces, cafes...), well, for sure the abolishment of enslavement meant that some people stopped earning some money... It's funny cause one day after I said this in a family discussion, the local major made some similar remarks.

Same as in Uviéu, the intention is to reuse the bullring for cultural acts (concerts). Indeed I think it has already been used like that in the past. Honestly, I find the architecture of bullrings really ugly (it's not just that they smell to blood and cruelty, it's that the architecture has this sort of Arabic (neo-mudejar) trails that really disturb me), and also in order to prevent future majors to bring bullfighting back, I'd really love to see the building demolished.

You can find some information about this in English here

Sunday 15 August 2021

Kalifat

I've recently watched Kalifat/Caliphate, an extraordinary Swedish series. I can not express how good this series is, it kept me glued to the screen for its 8 episodes, and with the last ones I almost had anxiety to watch what happened next.

If you know nothing about radical Islam and how it brainwashes people and seeds an infinite hatred in our Western world, this series will wake you up to the enormous threat that we're facing. If you have some knowledge about this topic, this series will move you to the next level. If you know quite a lot about this topic (like me) you'll be amazed by how real this series is, how perfectly it shows the horrendous reality to which our societies are confronted, how carefully it shows our enemies, the ones that have travelled to Syria to rape women and kill infidels, the ones that here at home take advantage of our freedoms and welfare state to wage war against us, the ones that seemed to be normal people but indeed had inside that tribal hatred against us that is easily waken up by some smart liar, and finally, the idiotic "pure European" loser that in order to give sense to his pathetic life goes through an "express conversion" and turns into the most fanatical and hate fueled Islamist (as a decade ago he would have joined a neonazi gang...)

The story is captivating and the characters are excellent. The immigrant family of middle-eastern origin gives us such a good portrait of how people coming from a same culture can move forward or backwards. The father is a perfect example of integration/assimilation. He does not like joining another part of the family that have not integrated ("they continue to live as if they where there..." he says) and feels horrified when during a family gathering that part of the family expresses their joy for the Charlie Hebdo massacre... His eldest daughter is the perfect example of a piece of shit. Alredy before undergoing her Islamist tranformation she expresses her disdain for "the whites" (yes, those horrible Swedish "vikings" that have given her everything she has). His wife is also integrated, but she is more "Muslim friendly". When the daughter starts to show her first signs of radicalization (she decides to wear a Hijab and starts to talk about how oppressed Muslims are...) she's tolerant for her new dress-code, and avoids confronting her saying tha she knows nothing about politics (while the father fairly reacts very strongly against the hijab and her comments). Then, when the mother finds that her daughter has been watching jihadist videos she finally understand what is happening and is in shock. As for the younger sister, well, I'll just say that at the end of the film she becomes the icing of the cake. If we were lucky enough to have a second season of this masterpiece I think she should play a central role.

The "Swedish" couple that joined ISIS and live in Raqqa are also pretty interesting. They man is a weak, confused idiot with a low IQ, so the perfect prey to be drawn into hatred and jihad. His wife, Petri, is strong and smart and at the present time she does not look like a fanatical, so maybe (this is my guessing here) she was drawn into the ISIS madness slightly deluded, thinking about joining a perfect and pure Muslim society, but not thinking about behading people and supporting the rape and enslavement of infidel women.

As for the Swedish police woman, Fatima, the character is perfect. A Swedish woman of Bosniak descent (we learn that she's Bosniak because she wears a Sarajevo t-shirt and eats Balkan food when she is hidden in one family's friend flat), bearing a Muslim name but completely unrelated to that religion (she drinks beer, smokes some pot, enjoys sex not being married... ). She is stubborn, obsessive, does not necessary follow orders if they make no sense, and is willing to risk everything to fight the Islamist monster. Choosing these origins for the main character has been a beautiful choice from the director, that is a Swedish guy born in Sarajevo himself. Probably he is quite aware of how the Salafists are trying to take control of the once very moderate Bosnian Islam. I love how she does not seem to empathize at all with Petri. She's going to help Petri just in exchange for information, but she sees her as the only one to blame for her situation (as she says to her colleague "she's there because she decided to go there"), and during most of the story she's using and putting pressure on her without any sort of kindness. It's only at the end of the story when she seems to get some feelings for her, but this is indeed intermixed with the fact that after Petri has fullfilled her part of the agreement, now she has to do her own, whatever it costs.

I could spend hours talking about this gorgeous piece of cinematography, but you better enjoy it yourself.

Saturday 7 August 2021

GraalVM

I've been reading about GraalVM recently, and it's an interesting piece of technology. The thing is that I had to read several articles to get a clear understanding of what GraalVM is. At first sight you could think that it's a completely new Java VM, that's wrong. It's some specific pieces of the Java VM that are new, not the whole one (the Garbage Collectors and Heap Memory structure, Class Loader, ByteCode format... remain the same). GraalVM is a high-performance JDK distribution designed to accelerate the execution... When you download the Community GraalVM what you are getting basically is the HotSpot/OpenJDK with some extra (very important) pieces. Mainly

  • The GraalVM Compiler. This is the essential part, and the one that is important for 95% of people. The essential idea is that this ins not a new Java source code)compiler (like javac) but a new JIT compiler, that compiles Java Bytecodes to Native code.
  • The GraalVM Native Image. This technology compiles java applications ahead of time to native code. The resulting native applications do not run on a JVM (there's no need for an interpreter, JIT or I think even class loaders), but it needs some runtime components (GC, Thread scheduling...) that are called "Substrate VM" (though I don't think this can be considered as a VM).
  • The Truffle Language Implementation Framework. This is a beast on its own and maybe I'll write a separate post about it. It allows "easily" writing programming languages implementations as interpreters (written in Java) for self-modifying Abstract Syntax Trees (what?!). It has allowed the creation of very efficient Ruby, Python and JavaScript implementations to run in the GraalVM. As these implementations are written in Java you can run them on a standard JVM, but they'll be slow, as it's the GraalVM JIT compiler who allows these implementations to run efficiently, so that's why Truffle is so linked to GraalVM. This is a really good (and thick) read.

GraalVM Compiler
The Java HotSpot VM uses an hybrid model to run the bytecode that javac generates and puts in your .class files. It first runs your code with an interpreter, then uses a fast but not optimized JIT compiler, C1, to transform to native code those methods that are being used frequently (hot methods). Then those methods that are called very frequently (very hot methods) are JIT compiled by C2, an optimized but slower JIT compiler. You can read a good explanation here. This is awesome, but is not specific to the Hotspot JVM, as I explaine here and here. Even though the C2 JIT compiler seems particularly advanced with its use of Profile Guided Optimization, some smart folks thought they could replace it with an even (much) better beast, and that's what the GraalVM Compiler is, an speculative, profile-guided JIT Compiler to act as a replacement for C2.

The Hot Spot JVM features the JVMCI (Java Virtual Machine Compiler interface). Your code can use this interface to pass bytecodes to a JIT compiler, get them compiled and then install that native code into the VM. Through JVMCI you can plug a JIT compiler implementing that interface into the VM, that's how the GraalVM (JIT) Compiler is added to the VM replacing the C2 JIT.

The GraalVM Compiler is included in your normal OpenJDK (and Oracle JDK) distribution. To use it rather than the standard C2 JIT compiler, you have to start the VM with these options: -XX:+UnlockExperimentalVMOptions -XX:+EnableJVMCI -XX:+UseJVMCICompiler
The other, more common option, is installing the GraalVM JDK distribution, that comes with the GraalVM Compiler already switched on, along with the other related technologies that I've previously mentioned: Native Image, Truffle, Substrate...

The GraalVM Compiler is written in Java, so its bytecodes have to be converted to native code at some point, this is what is called bootstrapping. From what I've understood here and what I can envision on my own, I think there are 2 options, either compile it ahead of time with Native Image, or use C1 to initially compile it to not optimized native code, and then allow it to optimize itself as its methods become hot.

It's mentioned here that the GraalVM compiler uses an Intermediate Representation (IR). I was a bit confused about what this means with regards to standard Java bytecodes, and this article came to the rescue. Basically: Java ByteCode -> IR -> Machine Code

In short, the just-in-time compiler will convert Java bytecode into SSA IR. To be more precise, it is an IR graph containing control flow and data flow. Each bytecode corresponds to several nodes (note that some bytecodes do not have corresponding IR nodes). Then, the just-in-time compiler optimizes on the IR graph.

In all this post I've been saying that GraalVM Compiler is a replacement for the C2 JIT compiler, but I've found this article saying that it replaces both C1 and C2, I think that's wrong. In most places I've read, like here, it clearly says that it only replaces the C2.