morloc README

The project's README from github.com/morloc-project/morloc. As one markdown file: README.md.

github release   license: Apache 2.0   Manual   Discord   Paper   X   BlueSky   Email

Composition

Morloc

Make the function, not the application, the unit of composition

Morloc composes functions across languages under a common type system and transforms modules into rich CLIs, APIs, and MCPs.

Write ordinary code in ordinary languages, source it into a Morloc script, and provide a type. These functions are then first class citizens. They can be used freely within a rich functional language. The Morloc compiler generates the CLI, API, MCP model, and usage statements from the types and declarative docstring instructions.

Install

Morloc runs natively on Linux, macOS (new ARM chips), and Windows WSL.

Run this to install the Morloc Installation Manager (mim):

curl -fsSL https://raw.githubusercontent.com/morloc-project/morloc-manager/main/scripts/install.sh | sh
mim new     # bulid the environment
mim shell   # drop into a shell
mim demo    # pull cool morloc demos

The build is native by default, add the --engine docker flag to build in a container (or podman or apptainer). The environment automatically handles dependencies for Morloc builds via the Pixi package manager. See the manual section Getting Started for more info.

You may freeze Morloc environments into Docker images with mim freeze.

An example

Two functions, in two languages, neither aware of the other. A C++ sum:

// foo.hpp
#pragma once
#include <vector>

double sum(const std::vector<double>& vec) {
    double sum = 0.0;
    for (double value : vec) {
        sum += value;
    }
    return sum;
}

and a parallel map in Python:

# foo.py
import multiprocessing as mp

def pmap(f, xs):
    with mp.Pool() as pool:
        results = pool.map(f, xs)
    return results

Neither file imports anything from Morloc. The Morloc module gives each a type and composes them:

-- sums.loc
module m (sum, sumOfSums)

import root-py
import root-cpp

source Py from "foo.py" ("pmap")
source Cpp from "foo.hpp" ("sum")

pmap :: (a -> b) -> [a] -> [b]

--' Add up a list of numbers
sum :: [Real] -> Real

--' Add up a list of lists, summing each in parallel
sumOfSums :: [[Real]] -> Real
sumOfSums = sum . pmap sum

. is function composition, so sumOfSums reads right to left: pmap sum sums each inner list in parallel, and the outer sum adds the results.

$ morloc make sums.loc
$ ./sums sumOfSums '[[1,2],[3,4,5]]'
15

A Python function called a C++ function across a process boundary, and you wrote no binding, no serializer, and no argument parser.

Free stuff that the compiler generates based on the type

Building the program creats a CLI tool from the given types and docstrings:

$ ./sums -h
Usage: ./sums <nexus_options> <command> <command_options>

Commands:
  sum        Add up a list of numbers
  sumOfSums  Add up a list of lists, summing each in parallel

General Options:
  -h, --help  Print help; -hh adds details and examples, -hhh adds schemas
              (nexus options: -h @)

./sums sum -h goes further and prints the argument types the compiler derived.

It can also serve as an MCP server (./sums --mcp-tools emits JSON Schema tool definitions), an HTTP, TCP, and Unix-socket service, and a module that another Morloc module can import and re-export. None of these are separate builds or a separate descriptions, so none of them can drift from the functions: changing a return type changes all interfaces.

Where the project stands

Morloc has been in development for about ten years and is in beta. I use it for my own work and am currently trying to build a community.

The test suite is massive and growing, but many bugs remain. The core feature is slowly stabilizing, but I still make regular backwards incompatible changes. Play with the cutting edge and you might bleed. Track your blood over here: issue tracker.

Getting involved

The hard part is finished. The ongoing work is the long tail of bug fixes and ecosystem development. That is where I need people. Here's what I'm looking for:

If you are interested in playing with Morloc (or want to drown my in money), feel free to contact me at [email protected].

License

Apache 2.0. See LICENSE.

morloc (morloc-project/morloc)

Searching Database…

219 ·GitHub
Что это такое?Morloc — это компилятор с сильной типизацией, поддерживающий несколько языков: он объединяет функции, написанные на разных языках, под одной общей системой типов и превращает каждый модуль в CLI, API и MCP-сервер.
Это язык программирования, компилятор или фреймворк?Это компилятор для собственного небольшого функционального скриптового языка. Вы пишете функции на обычных языках, подключаете их в Morloc-скрипт, задаёте им типы, а всё остальное собирает компилятор.
Как его установить и собрать?Запустите install-скрипт, чтобы получить Morloc Installation Manager (mim) — он собирает Morloc нативно на Linux, macOS на новых ARM-чипах и в Windows WSL. Добавьте флаг --engine docker, чтобы собрать проект в контейнере.
Нужно ли сначала установить что-то ещё?Вручную ничего не нужно: mim сам подтягивает зависимости для сборки через пакетный менеджер Pixi. Docker, Podman или Apptainer требуются только для сборки в контейнерах, а команда mim freeze превращает окружение в Docker-образ.
Насколько это стабильно — можно ли строить на этом проект?Пока нет: примерно после десяти лет разработки Morloc всё ещё в бете, багов много, а автор регулярно вносит изменения, ломающие обратную совместимость. Поиграете на переднем крае — можете пораниться.
Как функция на Python может вызвать функцию на C++ в Morloc?Компилятор сам генерирует весь связующий код: вызов происходит через границу процессов, и вам не нужно писать ни биндинги, ни сериализаторы, ни парсеры аргументов — достаточно задать типы обеим функциям в Morloc-модуле.
Что я получу, когда соберу Morloc-модуль?Одна сборка даёт CLI с автоматически сгенерированной справкой, MCP-сервер (флаг --mcp-tools создаёт определения инструментов в формате JSON Schema), сервис поверх HTTP, TCP и Unix-сокетов, а также импортируемый модуль — всё это генерируется из одних и тех же типов, поэтому интерфейсы не могут разойтись с кодом.
На каких языках я могу писать свои функции?В README показана совместная работа кода на C++ и Python, а Morloc изначально мультиязычный. Поддержка языков продолжает расширяться — автор приглашает контрибьюторов добавлять новые языки в экосистему.
Автор говорит, что самое сложное уже сделано, — какая помощь ему нужна?Отчёты об ошибках, типизированные модули для библиотек, которые вы уже поддерживаете, инструменты для редакторов, новые языки и теория систем типов. Контакты: [email protected].
What are similar projects?swift, unison, crystal, reason, scala, TypeScript, carbon-lang, elixir
Size
23.1 MB
Stars
219
Age
9y
Commits · 90 Days