How are set argument to nix-expression - nixos

I'm new to Nix and I'm trying to understand the hello derivation given in example.
I can understand the syntax and what is supposed to do, however I don't understand
how the initial arguments (and the especially the perl one_ are fed ?
I mean, who is setting the perl argument before calling this derivation.
Does that mean that perl is a dependency of hello ?

Packages are typically written as set of dependencies -> derivation functions, to be assembled later. The arguments you ask about are fed from pkgs/top-level/all-packages.nix, which holds the set of all packages in Nixpkgs.
When you find the hello's line in all-packages.nix, you'll notice it's using callPackage - it's signature is path to Nix expression -> overrides -> derivation. callPackage loads the path, looks at the function it loaded, and for each arguments provides either value from overrides or, if not given, from the huge set in all-packages.nix.
For a nice description of callPackage see http://lethalman.blogspot.com/2014/09/nix-pill-13-callpackage-design-pattern.html - it's a less condensed explanation, showing how you could have invented callPackage yourself :-).

Related

Best way to bring the contents of a textfile into a reflex project

I have a 70 line text file, whose contents I want to have as the initial value of a text area within my project. What is the best way to do this? Normally I would use readFile but I can't seem to use it in this context.
You can use Template Haskell to load the file at compile time and store its contents in a toplevel definition. The file-embed package on Hackage implements this functionality for you:
This module uses Template Haskell. Following is a simplified
explanation of usage for those unfamiliar with calling Template
Haskell functions.
The function embedFile in this modules embeds a file into the
executable that you can use it at runtime. A file is represented as a
ByteString. However, as you can see below, the type signature
indicates a value of type Q Exp will be returned. In order to
convert this into a ByteString, you must use Template Haskell
syntax, e.g.:
$(embedFile "myfile.txt")
This expression will have type ByteString.

Is it possible / easy to include some mruby in a nim application?

I'm currently trying to learn Nim (it's going slowly - can't devote much time to it). On the other hand, in the interests of getting some working code, I'd like to prototype out sections of a Nim app I'm working on in ruby.
Since mruby allows embedding a ruby subset in a C app, and since nim allows compiling arbitrary C code into functions, it feels like this should be relatively straightforward. Has anybody done this?
I'm particularly looking for ways of using Nim's funky macro features to break out into inline ruby code. I'm going to try myself, but I figure someone is bound to have tried it and /or come up with more elegant solutions than I can in my current state of learning :)
https://github.com/micklat/NimBorg
This is a project with a somewhat similar goal. It targets python and lua at the moment, but using the same techniques to interface with Ruby shouldn't be too hard.
There are several features in Nim that help in interfacing with a foreign language in a fluent way:
1) Calling Ruby from Nim using Nim's dot operators
These are a bit like method_missing in Ruby.
You can define a type like RubyValue in Nim, which will have dot operators that will translate any expression like foo.bar or foo.bar(baz) to the appropriate Ruby method call. The arguments can be passed to a generic function like toRubyValue that can be overloaded for various Nim and C types to automatically convert them to the right Ruby type.
2) Calling Nim from Ruby
In most scripting languages, there is a way to register a foreign type, often described in a particular data structure that has to be populated once per exported type. You can use a bit of generic programming and Nim's .global. vars to automatically create and cache the required data structure for each type that was passed to Ruby through the dot operators. There will be a generic proc like getRubyTypeDesc(T: typedesc) that may rely on typeinfo, typetraits or some overloaded procs supplied by user, defining what has to be exported for the type.
Now, if you really want to rely on mruby (because you have experience with it for example), you can look into using the .emit. pragma to directly output pieces of mruby code. You can then ask the Nim compiler to generate only source code, which you will compile in a second step or you can just change the compiler executable, which Nim will call when compiling the project (this is explained in the same section linked above).
Here's what I've discovered so far.
Fetching the return value from an mruby execution is not as easy as I thought. That said, after much trial and error, this is the simplest way I've found to get some mruby code to execute:
const mrb_cc_flags = "-v -I/mruby_1.2.0_path/include/ -L/mruby_1.2.0_path/build/host/lib/"
const mrb_linker_flags = "-v"
const mrb_obj = "/mruby_1.2.0_path/build/host/lib/libmruby.a"
{. passC: mrb_cc_flags, passL: mrb_linker_flags, link: mrb_obj .}
{.emit: """
#include <mruby.h>
#include <mruby/string.h>
""".}
proc ruby_raw(str:cstring):cstring =
{.emit: """
mrb_state *mrb = mrb_open();
if (!mrb) { printf("ERROR: couldn't init mruby\n"); exit(0); }
mrb_load_string(mrb, `str`);
`result` = mrb_str_to_cstr(mrb, mrb_funcall(mrb, mrb_top_self(mrb), "test_func", 0));
mrb_close(mrb);
""".}
proc ruby*(str:string):string =
echo ruby_raw("def test_func\n" & str & "\nend")
"done"
let resp = ruby """
puts 'this was a puts from within ruby'
"this is the response"
"""
echo(resp)
I'm pretty sure that you should be able to omit some of the compiler flags at the start of the file in a well configured environment, e.g. by setting LD_LIBRARY_PATH correctly (not least because that would make the code more portable)
Some of the issues I've encountered so far:
I'm forced to use mrb_funcall because, for some reason, clang seems to think that the mrb_load_string function returns an int, despite all the c code I can find and the documentation and several people online saying otherwise:
error: initializing 'mrb_value' (aka 'struct mrb_value') with an expression of incompatible type 'int'
mrb_value mrb_out = mrb_load_string(mrb, str);
^ ~~~~~~~~~~~~~~~~~~~~~~~~~
The mruby/string.h header is needed for mrb_str_to_cstr, otherwise you get a segfault. RSTRING_PTR seems to work fine also (which at least gives a sensible error without string.h), but if you write it as a one-liner as above, it will execute the function twice.
I'm going to keep going, write some slightly more idiomatic nim, but this has done what I needed for now.

Haskell Haddock latex equation in comments

I'd like to use latex notation for equations in my source code.
For example, I would write the following comment in some haskell source file Equations.hs:
-- | $v = \frac{dx}{dt}$
In the doc directory, this gets rendered by haddock in Equations.tex as:
{\char '44}v = frac{\char '173}dx{\char '175}{\char '173}dt{\char '175}{\char '44}
I found this function in the source for Haddock's latex backend that replaces many characters that are used in latex formatting:
latexMunge :: Char -> String -> String
...
latexMunge '$' s = "{\\char '44}" ++ s
Is there any existing functionality that allows me to bypass this and insert latex equations in comments?
No. The main reason why this (and similar features) don't exist is that it's unclear what to do with the markup in the other backends, be it HTML one, Hoogle one or whatever else someone might be using. This is fairly commonly requested but there is no common agreement and more importantly, no patches.
Technically we don't support the LaTeX backend, it's kept around compiling so that the Haskell Report can be produced. If you or someone else wants to give it some new life (and features) then we'll happily accept patches.
tl;dr: no can do. I know people simply pre-render LaTeX and insert the resulting images in with the image syntax.

Adding Barewords to Lua

To implement a domain specific language, within lua,
I want to add barewords to the language.
So that
print("foo") could be written as print(foo)
The way I have done this is by changing the metatable of the enviroment table _G.
mt = {__index = function(tbl,key) return key end}
setmetatable(_G, mt)
And that works, because retrieving the value of variable foo is done by _G.foo which is equivalent to _G["foo"]
Is this a good approach?
Are there hidden downsides?
Is there a better way?
Can I do it so that barewords only work inside a certain file?
(Perhaps by executing that file, from another luascript, using loadstring)
As soon as someone declares a local with the same name of your "keywords" it will shadow your "keyword/global var" and your mechanism will fail:
print(foo) -- does what you think
local foo = 2
print(foo) -- argh!
and note that you cannot prevent the definition of local variables in a script.
Edit: (answering to a comment).
Are you using a customized Lua engine? You cannot prevent entering local scope, because you are always in local scope. It is exactly the other way around: technically there is no global scope in Lua (with the same meaning as in C, for example). There is a global namespace (implemented as a table), instead. The mechanisms for accessing globals differs between Lua 5.1 (function environments) and Lua 5.2 (implicit _ENV prefixing), but the concept is almost the same.
In particular, when a Lua script is loaded, whether by the interpreter, or by load, loadstring, dofile, etc., it is interpreted as the body of an anonymous function (a closure), usually referred to as the "main chunk". Thus there is always a local scope. In standard Lua you cannot prevent the definition of a local variable when the parser encounters a local statement in the script being loaded.

Embedding a domain specific language in an OCaml toplevel -- to Camlp4 or not?

I have some code that includes a menhir-based parser for a domain specific language (a logic). For the sake of my sanity while debugging, it would be great to be able to type instances of this language (formulas) directly in the toplevel like so:
# f = << P(x,y) & x!=y >>
Is campl4/5 my only option? If yes, I find the documentation rather intimidating. Is there an example/tutorial that is close-enough to my use case and that I could conceivably adapt? (For instance, syntax extensions that introduce new keywords do not seem relevant). Thanks!
If you're willing to call a function to do the parsing, you can use ocamlmktop to include your parser into the top level. Then you can install printers for your types using #install_printer. The sessions might look like this then:
# let x = parse ()
<< type your expression here >>
# x : type = <<formatted version>>
I have used specialed printers, and they definitely help a lot with complicated types. I've never gotten around to using ocamlmktop. I always just load in my code with #load and #use.
This is a lot easier than mastering camlp4/5 (IMHO). But maybe it's a bit too crude.
Yes, you can use camlp4 and it will work reasonably well (including in the toplevel), but no, it's not well-documented, and you will have to cope with that.
For an example that is close to your use-case, see the Lambda calculus quotation example of the Camlp4 wiki.
For the toplevel, it will work easily. You can dynamically load "camlp4o.cmo" then your syntactic extension in the toplevel, or use findlib which handles that: from the toplevel, #use "topfind";;, then #camlp4o;;, then #require "myfoo.syntax";; where myfoo.syntax is the name of the findlib package you've created to deploy your extension.

Resources