(Classic) Dual Execution Environment

Many KRL rulesets emit JavaScript. That means they execute in both KRE and the browser. The joint execution of both of these environments leads to the effect that we want from any given rule. 

If you are using KRL on the Web, any rulesets that are executed in any given transaction create JavaScript that is returned to the browser and executed there. 

  • If you are executing the ruleset from a bookmarklet or with embedded site tags, the JavaScript is executed in the context of the page itself. 
  • If the rulesets are being executed using a Kynetx browser extension, the JavaScript is executed in the context of the extension itself. For Chrome, for example, that is the background page for the extension. 

The interpreter takes care to ensure that ruleset semantics are transferred faithfully to the JavaScript:

  • Every ruleset creates a JavaScript closure so that it's declarations are not leaked to other JavaScript on the page.
  • Every rule creates a JavaScript closure inside the ruleset's closure so that declarations in a rule are protected from declarations in other rules.
  • Every declaration is transferred to the Javascript. The right-hand side expression of the declarations is executed and it's value is emitted int he JavaScript. 
  • Every Web action results in JavaScript being emitted consistent with the action. Sometimes this is a few simple lines of JavaScript, but often it is quite complex (e.g. (Classic) annotate()).  

There are some KRL expressions, such as a function, that cannot be translated to JavaScript, and so the value of the declaration is UNTRANSLATABLE_KRL_EXPRESSION

Variable Names

Take care when choosing variable names for rules that will generate JavaScript. The JavaScript generator is not hygienic and thus JavaScript keywords, when used as variable names, can result in code that does not work. The KRL program will execute fine, but the generated JavaScript will cause a runtime error. Looking at the browser's console window will usually quickly tell you if this is the case.

Copyright Picolabs | Licensed under Creative Commons.