Записки программиста
Устанавливаем самую свежую версию компилятора Haskell
В 99% случаев если вам требуется компилятор Haskell, то Haskell Platform решит все ваши проблемы. В платформу входит не только непосредственно стабильная версия компилятора GHC, но и такие утилиты, как cabal и haddock, а также некоторые часто используемые библиотеки. При этом с помощью cabal можно обновить, пожалуй, всю платформу, не считая разве что самого GHC. Но иногда хочется поиграться с версией GHC посвежее. Вот тому, как это сделать, и посвящена сия заметка.
Причин отказаться от стабильной и надежной версии GHC в пользу сырой и непроверенной может быть много. Кому-то просто хочется поиграться с новыми возможностями, кто-то желает проверить совместимость своих пакетов с грядущей версией компилятора, а кто-то, например, может надеяться увеличить производительность своего приложения, собрав его компилятором поновее. Есть и такие, кому просто нравится использовать все самое новое и собирать в связи с этим кучу граблей. Ну и, конечно же, не забудем самих разработчиков GHC, а также людей, решивших помочь с его бета-тестированием.
На момент написания этих строк стабильной версией GHC считается 7.6.3, а новой, уже почти готовой к релизу, но все еще допиливаемой — 7.8.1. Сначала мы попробуем установить бинарную сборку GHC 7.8.1, а затем рассмотрим сборку GHC из исходников. Я проделовал все написанное ниже под Ubuntu Linux, но подозреваю, что многое также будет справедливо в отношении других операционных систем и дистрибутивов Linux. Вся приведенная информация может сильно устареть к моменту, когда вы будете читать эти строки. Поэтому прежде, чем действовать, обязательно сверяйтесь с информацией в багтрекереах, файлами README, INSTALL и так далее.
Устновка последней бинарной сборки GHC
Бинарные сборки GHC для различных окружений доступны на официальном сайте языка. На момент написания этих строк самые свежие сборки были доступны по адресу:
Прежде, чем действовать, сносим платформу:
/ haskell
cd temp
wget https: // www.haskell.org / path / to / some / file.tar.bz2
tar -xvjf ghc-7.8.0.20140228-x86_64-unknown-linux-deb7.tar.bz2
cd ghc-7.8.0.20140228 /
. / configure —prefix = / home / eax / haskell
make install
… и в консоли говорим:
Если вдруг ghci ругается на то, что не может найти libgmp:
… просто даем ему libgmp:
В общем-то, это все. Самая свежая бинарная сборка GHC установлена!
Собираем Cabal
Очень грустно писать на Haskell без наличия под рукой cabal. Так давайте же самостоятельно соберем его из исходников! На багтрекере GHC есть замечание к GHC 7.8, что cabal нужно брать из репозитория на GitHub, а не с haskell.org, иначе он не соберется. Я проверил, действительно не собирается 🙂 Ну ОК, с гитхаба, так с гитхаба:
Сначала собираем и устанавливаем библиотеку Cabal:
Затем переходим к установке утилиты cabal, которая на самом деле cabal-install:
Утилита cabal зависит от некоторых сторонних пакетов, например, network, text и parsec. Скрипт bootstrap.sh тянет и собирает эти зависимости, затем собирает сам cabal.
Если все было сделано правильно, пакет должен успешно установиться, после чего в ghci появится возможность подгрузить модуль GA.Simple и поиграться с ним. Поздравляю, теперь вам доступно более 5000 пакетов с Hackage!
Сборка GHC из исходников
И все-таки, бинарная сборка — это, можно сказать, прошлый век, ведь в ней нет самых-самых последних коммитов! Есть только один способ получить самый свежак, собрать GHC самостоятельно.
Для этого нам понадобятся кое-какие дополнительные инструменты:
Также нам понадобятся свежие версии Alex и Happy:
Клонируем git-репозиторий и делаем чекаут нужной ветки:
Для удобства исходный код GHC разбит на несколько репозиториев. К сорсам прилагается скрипт sync-all. Это такой скрипт на Perl, который подтягивает зависимости GHC из других репозиториев. Что-то вроде самопального rebar из мира Erlang. Список зависимостей задается в файле packages, складываются зависимости в каталог libraries. Например, чтобы подтянуть все зависимости GHC 7.8, говорим:
Также с помощью sync-all разработчики GHC подтягивают новые патчи. Команда sync-all pull тянет все новые патчи из оригинального репозитория в дерево репозиториев в локальном каталоге.
Переходим к сборке:
/ ghc- 7.8 -2014mmdd
perl boot
. / configure —prefix = / home / eax / ghc- 7.8 -2014mmdd
make
/.zshrc, после всех ранее добавленных строчек пишем:
… чтобы путь к новому GHC оказался первым в списке $PATH. Потом говорим source . , ну вы уже поняли. Теперь у вас действительно самый свежак. Осталось разве что добавить задание в crontab, чтобы GHC автоматически пересобирался каждую ночь!
Заключение
- Тут пишут, что есть энтузиасты, поддерживающие PPA со свежими сборками GHC. Я проверял, не такие уж эти сборки и свежие, но может вам и такие норм;
- Недавно была опубликована занятная статья с обзором новых возможностях Haddock. В частности, документацию наконец-то можно писать на родном японском, и вообще любом юникоде;
- А тут можно найти много интересных сведений о том, как правильно тестировать GHC, как включить в нем опциональные возможности и тд;
- На Reddit обсуждаются причины задержки релиза GHC 7.8.1;
Как видите, ничего сложного. Вопросы и дополнения, как это было испокон веков, горячо приветсвуются!
Downloads
There are three widely used ways to install the Haskell toolchain on supported platforms. These are:
Minimal installers: Just GHC (the compiler), and build tools (primarily Cabal and Stack) are installed globally on your system, using your system’s package manager.
Stack: Installs the stack command globally: a project-centric build tool to automatically download and manage Haskell dependencies on a project-by-project basis.
Haskell Platform: Installs GHC, Cabal, and some other tools, along with a starter set of libraries in a global location on your system.
These options make different choices as to what is installed globally on your system and what is maintained in project-specific environments. Global installations allow more sharing across users and projects, but at the cost of potential conflicts between projects. To avoid these conflicts, each option has a lightweight sandboxing feature that creates largely self-contained, per-project environments. With Minimal you can optionally sandbox the libraries, avoiding most conflicts. Stack sandboxes the compiler, tools and libraries, so avoids nearly all kinds of conflicts between projects. With Platform you can also optionally sandbox libraries, but not the globally installed platform libraries.
Haskell IDEs & other distributions
In addition to the generic, cross-platform Haskell toolchain described above, there are also easy-to-use, platform-specific distributions and IDEs. The Haskell Wiki contains a list of the most popular ones.
Minimal installers
What they are
Minimal installers provide centrally the GHC compiler and the Cabal and Stack tools for installing packages. Some may install further build tools (i.e.В for parsing and lexing) as well.
What you get
- Only the core libraries necessary for each platform are included.
- Cabal or Stack must be used to download and install packages after installation.
How to get them
Where to get help
- For help learning Haskell itself, start with the Documentation page on the Haskell Wiki.
- If you need help with GHC—the Haskell compiler—there is a comprehensive GHC User Manual.
- For help using Cabal to download or create additional packages (see below), there is the Cabal User Guide.
- For help using Stack to download or create packages, see the stack documentation below.
- Finally, you can ask questions of other Haskell users and experts on the #haskell IRC channel on the Freenode IRC network.
Stack
What it is
Stack is a cross-platform build tool for Haskell that handles management of the toolchain (including the GHC compiler and MSYS2 on Windows), building and registering libraries, and more.
What you get
- Once downloaded, it has the capacity to download and install GHC and other core tools.
- Project development is isolated within sandboxes, including automatic download of the right version of GHC for a given project.
- It manages all Haskell-related dependencies, ensuring reproducible builds.
- It fetches from a curated repository of over a thousand packages by default, known to be mutually compatible.
- It can optionally use Docker to produce standalone deployments.
How to get it
The install and upgrade page describes how to download Stack on various platforms, although the main three are repeated here:
Instructions for other Linux distributions, including Debian, Fedora, Red Hat, Nix OS, and Arch Linux, are also available.
Where to get help
For help with Haskell and GHC in general, see the links mentioned above. For Stack itself there are also the following resources:
- The README offers a general overview, and help with installation.
- There is an in-depth guide to using Stack.
- Getting started with Stack introduces how to build new projects using Stack.
- You may post issues and feature requests on its GitHub issue tracker.
- There is a mailing list for Stack
- There is a dedicated #haskell-stack IRC channel on the Freenode IRC network.
- The StackOverflow haskell-stack tag has many stack-specific questions and answers.
Haskell Platform
What it is
The Haskell Platform is a self-contained, all-in-one installer. After download, you will have everything necessary to build Haskell programs against a core set of useful libraries. It comes in both core versions with tools but no libraries outside of GHC core, or full versions, which include a broader set of globally installed libraries.
What you get
- The Glasgow Haskell Compiler
- The Cabal build system, which can install new packages, and by default fetches from Hackage, the central Haskell package repository.
- the Stack tool for developing projects
- Support for profiling and code coverage analysis
- 35 core & widely-used packages
How to get it
The Platform is provided as a single installer, and can be downloaded at the links below.
Where to get help
- You can find a comprehensive list of what the Platform offers.
- See the general help mentioned above, which covers the usage of GHC, as well as the Cabal and Stack tools.
Additional Libraries
In Haskell, packages are configured and built with the Cabal package system built into GHC (and other compilers). For more specific details, see The Cabal User Guide. The command line tools to download and install packages are either cabal or stack , each having different workflows. For details on their usage, see the documentation above.
Hackage
Hackage is a repository of packages to which anyone can freely upload at any time. The packages are available immediately and documentation will be generated and hosted there. It can be used by cabal install.
You can install a package using cabal by running:
Note that if you are not in a sandbox, this will install the package globally, which is often not what you want, so it is recommended to set up sandboxes in your project directory by running cabal sandbox init .
LTS Haskell
LTS Haskell is a stackage-based long-term support set of packages which build and pass tests together, with backported bug fixes.
Stackage Nightly
Stackage is a nightly generated stable repository of snapshots of package sets in which only packages which build and pass tests together are bundled together into a snapshot.
From source control repositories
Installing from a source repository is also possible. For example, to clone and install the network package from source, you would run:
Truly portable Haskell installation on Windows
Is it possible to have a truly portable Haskell installation on Windows so everything Haskell related happens under a single directory. I want to be able to have Haskell installation on a USB stick so I can use it on any other Windows computer just by plugging it in.
That would mean when I say cabal install somePackage everything happens locally and relative to that single directory (n.b. for different computers there might be a different drive letter assigned to the USB drive). I would like to be able to run that cabal install somePackage on any Windows computer. Also, it would be nice if I could copy the contents of the USB stick to a local hard disk and it still works from there (on some Windows machines USB sticks are mounted read only).
I am aware of the following related StackOverflow questions here and here. Can I setup cabal’s config file in such a way it uses relative paths? What about other Haskell tools (e.g. winghci)?
So, how should I do it? Install Haskell Platform in a portable mode and then do what?
2 Answers 2
Follow the process as described below:
Use portable install to install Haskell Platform in e.g. h:\dev\hp . Select Do not create shortcuts. For Haskell Stack Setup, choose h:\dev\hp\local\bin as the destination folder. Deselect Add to user %PATH%.
You should get the following (first level) directory structure:
Create additional subfolders:
Download and extract junction utility in the user folder. Create user\create-symlink.bat with the following contents. Then run it.
Create haskell.bat in the h:\dev\hp folder with the following contents:
Run haskell.bat and in the command line type these commands. This should create additional folder structure under user\AppData\Roaming
To make cabal’s config file ( user\AppData\Roaming\cabal\config ) relocatable, edit it and change the tags as follows:
Using your favourite text editor do multi-file search and replace on the following files: user\AppData\Roaming\ghc\i386-mingw32-8.0.1\package.conf.d\*.conf
- Search for absolute paths and replace them using $topdir (It evaluates to a directory under 8.0.1 , I think it is h:\dev\hp\8.0.1\lib ). So, for example if you see h:\\dev\\hp\user\\Application Data replace it with $topdir\\..\\..\\user\\AppData\\Roaming . Or, if you see h:\dev\hp\8.0.1 , then replace it with $topdir\.. .
Do the same search and replace process in the stack’s snapshot folders, e.g. user\AppData\Roaming\stack\snapshots\XXX\pkgdb :
Update the global and user and stack package cache:
If you install new packages, you might need to repeat the search&replace step. Or you can try cabal install —enable-relocatable
and see if that works instead.
You should be able to rename the installation folder, copy it to new location on the same machine, or on the different machine altogether and it should all work. Just use the haskell.bat to set up the environment and get a command prompt from which you should be able to run ghc , cabal , stack , winghci , etc.
There is one issue still remaining. If you try to install a package that requires gcc to be built, you might get the following error:
The reason is that configure script gets passed the wrong path to gcc ( h:\dev\hp\80227D
1.1Ăé´ÉŐĂőýŽÇ┬ćýŁŻ┬îŃąÇĂéňżö┬łŃŽ«ĂéŃąÇĂéň庤ťO ). I know how to build the offending package manually, but don’t know how to install it: