How to work WebSharper translator? - f#

Could anyone explain how to work WebSharper translator in conjunction with the F#?
Is it translate F# code to JS itself or using F# compiler for it?
In second case, what F# compiler are doing when finds [] attribute in source? Does compiler generate functions in any case and in runtime construct JS as reflection from compiled bytecode or there something other?

I develop WebSharper. Good question!
Roughly the compilation looks like this:
a.dll: a.fs b.fs c.fs
fsc ...
a.dll.js: a.dll
WebSharper.exe ..
When functions are annotated with [<JavaScript>], which is an alias for [<ReflectedDefinition>], the F# compiler does not only compile these functions to .NET IL, but also stores the representation of their syntax in the DLL metadata. This representation has type Quotations.Expr and can be recovered by reflection. Have a look at Quotations.DerivedPatterns.MethodWithReflectedDefinition.
WebSharper is therefore a source to source translator, and it is pretty direct (preserves lambdas, for example). In WebSharper 2.0 we have an intermediate Scheme-like language, but that is only there to help optimize the generated code.

Related

How does sightly HTML files access global implicit objects in AEM 6

Unlike inclusion of global.jsp with every component jsp in CQ5, sightly does not include any such dependency. How does it actually access all the global objects. What is the backend process of it. And how sightly code compiles to java??
how sightly code compiles to java?
Sling sightly API has two bundles to support this, the first step is to compile sightly into Abstract Syntax Tree (The Abstract Syntax Tree maps plain Java source code in a tree form. This tree is more convenient and reliable to analyse and modify programmatically than text-based source.) This is done by Apache Sling Scripting Sightly Compiler
Next is to convert (transpile) the Abstract Syntax Tree into java source code. This is achieved in bundle Java Compiler
How does it actually access all the global objects.
To understand this you need to understand how script resolution occurs in Sling and how are resource resolved to scripts which is core to Sling Scripting engine. To understand basics of ScriptEngine look at java docs here, implementation of this is SightlyScriptEngine
The way script resolution works is that the resource is adapted to DefaultSlingScript , this is done by SlingScriptAdapterFactory.
SlingScriptAdapterFactory has references to BindingsValuesProvider which is passed to the DefaultSlingScript. One of the implementation of BindingsValuesProvider is AEMSightlyBindingsValuesProvider (you can see this as a service in /system/console/services) which provides the default objects.
The DefaultSlingScript then responsible for invoking SightlyScriptEngine and calling its method eval which populates the default objects in binding and then setting this binding as request attribute.

Vala - Equation parsing

I am trying to learn a bit about Vala and wanted to create a Calculator to test how Gtk worked. The problem is that I coded everything around the supposition that there would be a way to parse a string that contained the required operations. Something like this:
string operation = "5+2/3*4"
I have done this with Python and it is as simple as using the compilers parser. I understand Python is math oriented, but I thought that perhaps there would be Vala library waiting for me as an answer... I haven't found it if it does exist, but as I was looking at the string documentation, I noticed this part:
/* Strings prefixed with '#' are string templates. They can evaluate
* embedded variables and expressions prefixed with '$'.
* Since Vala 0.7.8.
*/
string name = "Dave";
println (#"Good morning, $name!");
println (#"4 + 3 = $(4 + 3)");
So... I thought that maybe there was a way to make it work that way, maybe something like this:
stdout.printf(#"$(operation)")
I understand that this is not an accurate supposition as it will just substitute the variable and require a further step to actually evaluate it.
Right now the two main doubts I am having are: a) Is there a library function capable of doing this? and b) Is it possible to work out a solution using string templates?
Here's something I found that would do the work. I used the C++ libmatheval library, for this I first required a vapi file to bind it to Vala. Which I found here. There are a lot of available vapi files under the project named vala-extra-apis, and they are recognized in GNOME's Vala List of Bindings although they are not included at install.
You could parse the expression using libvala (which is part of the compiler).
The compiler creates a CodeContext and runs the Vala parser over a (or several) .vala file(s).
You could then create your own CodeVisitor decendant class that visits the necessary nodes of the parse tree and evaluates expressions.
As far as I can see there is no expression evaluator that does this, yet. That is because normally vala code is translated to C code and the C compiler then does compile time expression evaluation or the finished executable does the run time evaluation.
Python is different, because it is primarily a scripting language and has evaluation build directly into the runtime / interpreter.

F# Fractal - a bug I can't figure out

I'm trying to make an example I've found on the net work. It's a 3D fractal in F#. Here it is: http://tomasp.net/blog/infinite-cheese.aspx. The source code is available for download at the end of the article. The article and the sample were written in 2007, so I think the code is just slightly obsolete. There is one block of code that causes error and the code won't compile:
// Returns a cube with filtered sides
let private get_cube(incl_sides) =
[ for (side,trigs) in cube
when Set.mem side incl_sides
->> trigs ]
The when keyword is underlined, and the error message goes as follows:
Unexpected keyword 'when' in expression. Expected '->' or other token.
I can't figure out what's wrong with this. In an attempt to understand the code better, I searched the langauge specs. As far as I know, there is nothing about the Set.mem function or the ->> operator. Do you have any idea what could be wrong?
Try
[for (side, trigs) in cube do
if Set.contains side incl_sides then
yield! trigs]
The language has undergone a lot of changes since that code was written. In particular, the ->> operator has been replaced by yield!, Set.mem has been renamed to the more descriptive Set.contains, and comprehensions now use if ... then instead of when.
Yes, the version of the source code that is linked from the blog post is a bit old. You can find the latest (updated) version in the F# samples project on CodePlex. I think there may be some other changes, so it is best to get the version from CodePlex. (It includes FractalSimple.fs which is simpler version and Fractal.fs which also removes cube sides that are not visible).
The project contains standard Visual Studio 2008/2010 .fsproj project. The original version on the blog was written using F# CTP (from VS 2005 times) which had a completely different Visual Studio integration and used an obsolete .fsharpp project format (before MSBUILD format existed).
The when and ->> constructs have been used as a lightweight syntax for writing queries, but are now deprecated, to keep the syntax inside comprehensions consistent with the rest of the language. As kvb points out, you can use ordinary if .. then and the only non-standard thing is yield!, which means return all elements of the given sequence.

How to compile F# library from another F# program

I want to make my Application configuration as F# file wich will be compiled to dll. (like XMonad configuration with xmonad.hs on haskell). I found it more interesting and just better way then using XML serialization.
So is there any way how can I compile single file (or more) to Library with some configuration like
module RNExcel.Repository
open RNExcel.Model
type ExpenseReportRepository() =
member x.GetAll() =
seq{ yield {Name="User1"
Role="someRole"
Password = "123321"
ExpenseLineItems =
[{ExpenseType="Item1"
ExpenseAmount="50"};
{ExpenseType="Item2"
ExpenseAmount="50"}]}
yield {Name="User2"
Role="Estimator"
Password = "123123"
ExpenseLineItems =
[{ExpenseType="Item1"
ExpenseAmount="50"};
{ExpenseType="Item2"
ExpenseAmount="125"}]} }
my idea was to run shell .... and msbuild the project , but I don't think it will works for every user with .net 4
Check out the F# Power Pack, specifically the FSharp.CodeDom library. You can use this library to compile F# code at run-time and, with a little Reflection thrown in, can likely achieve your goal of code-as-configuration with minimal fuss.
I think that using CodeDOM provider from the PowerPack as Ben suggested is a way to go. I'd just like to add a few things (and it didn't fit into the comment box).
To parse and compile the F# code with the configuration, you need just to compile the source file that the users write using F# PowerPack. The compilation part of PowerPack is complete and works just fine. It invokes the F# compiler under the cover and gives you the compiled assembly back. The only problem is that the users of your application will need to have F# compiler installed (and not just the redist).
The incomplete part of F# CodeDOM provider is generating F# code from CodeDOM trees (because the trees were not designed to support F#), but that's not needed in this case.

Ant (or NAnt) in Lisp

In his article The Nature of Lisp, Slava Akhmechet introduces people to lisp by using Ant/NAnt as an example. Is there an implementation of Ant/NAnt in lisp? Where you can use actual lisp code, instead of xml, for defining things? I've had to deal with creating additions to NAnt, and have wished for a way to bypass the xml system in the way Slava shows could be done.
Ant is a program that interprets commands written in some XML language. You can, as justinhj mentioned in his answer use some XML parser (like the mentioned XMLisp) and convert the XML description in some kind of Lisp data and then write additional code in Lisp. You need to reimplement also some of the Ant interpretation.
Much of the primitive stuff in Ant is not needed in Lisp. Some file operations are built-in in Lisp (delete-file, rename-file, probe-file, ...). Some are missing and need to be implemented - alternative you can use one of the existing libraries. Also note that you can LOAD Lisp files into Lisp and execute code - there is also the REPL - so it comes already with an interactive frontend (unlike Java).
Higher level build systems in Common Lisp usually are implementing an abstraction called 'SYSTEM'. There are several of those. ASDF is a popular choice, but there are others. A system has subsystems and files. A system has also a few options. Its components also have options. A system has either a structural description of the components, a description of the dependencies, or a kind descriptions of 'actions' and their dependencies. Typically these things are implemented in an object-oriented way and you can implement 'actions' as Lisp (generic) functions. Lisp also brings functions like COMPILE-FILE, which will use the Lisp compiler to compile a file. If your code has, say, C files - you would need to call a C compiler - usually through some implementation specific function that allows to call external programs (here the C compiler).
As, mentioned by dmitry-vk, ASDF is a popular choice. LispWorks provides Common Defsystem. Allegro CL has their own DEFSYSTEM. Its DEFSYSTEM manual describes also how to extend it.
All the Lisp solution are using some kind of Lisp syntax (not XML syntax), usually implemented by a macro to describe the system. Once that is read into Lisp, it turns into a data representation - often with CLOS instances for the system, modules, etc.. The actions then are also Lisp functions. Some higher-order functions then walk over the component graph/tree and execute actions of necessary. Some other tools walk over the component graph/tree and return a representation for actions - which is then a proposed plan - the user then can let Lisp execute the whole plan, or parts of the plan.
On a Lisp Machine a simple system description looks like this:
(sct:defsystem scigraph
(:default-pathname "sys:scigraph;"
:required-systems "DWIM")
(:serial "package" "copy" "dump" "duplicate" "random"
"menu-tools" "basic-classes" "draw" "mouse"
"color" "basic-graph" "graph-mixins" "axis"
"moving-object" "symbol" "graph-data" "legend"
"graph-classes" "present" "annotations" "annotated-graph"
"contour" "equation" "popup-accept" "popup-accept-methods"
"duplicate-methods" "frame" "export" "demo-frame"))
Above defines a system SCIGRAPH and all files should be compiled and load in serial order.
Now I can see what the Lisp Machine would do to update the compiled code:
Command: Compile System (a system [default Scigraph]) Scigraph (keywords)
:Simulate (compiling [default Yes]) Yes
The plan for constructing Scigraph version Newest for the Compile
operation is:
Compile RJNXP:>software>scigraph>scigraph>popup-accept-methods.lisp.newest
Load RJNXP:>software>scigraph>scigraph>popup-accept-methods.ibin.newest
It would compile one file and load it - I have the software loaded and changed only this file so far.
For ASDF see the documentation mentioned on the CLIKI page - it works a bit different.
Stuart Halloway's upcoming book Programming Clojure goes through the construction of Lancet throughout the book as an example app. Lancet is a Clojure build system which (optionally) integrates directly with Ant. Source code and examples are available.
If all you want to do is generate Ant XML files using Lisp code, you could use something like clj-html for Clojure or CL-WHO for Common Lisp. Generating XML from Lisp s-exps is fun and easy.
Common Lisp's ASDF (Another System Definition Facility) is analogous to Make/Ant (but not a full analogue — it is aimed at building lisp programs, not generic systems like make or ant). It is extensible with Lisp code (subclassing systems, components, adding operations to systems). E.g., there is an asdf-ecs extensions that allows including (and compiling) C source files into system.
Perhaps you could define things in lisp and convert them to XML at the point you pass them to NAnt.
Something like XMLisp makes it easier to go back and forth between the two representations.
Edit: Actually, xml-emitter would make more sense.

Resources