• This repository has been archived on 28/Jul/2020
  • Stars
    star
    191
  • Rank 202,877 (Top 4 %)
  • Language
    Scala
  • License
    MIT License
  • Created over 10 years ago
  • Updated almost 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Spire's macros for zero-cost operator enrichment

Machinist

Build Status

"Generic types and overloaded operators would let a user code up all of these, and in such a way that they would look in all ways just like types that are built in. They would let users grow the Java programming language in a smooth and clean way."

-- Guy Steele, "Growing a Language"

Overview

One of the places where type classes incur some unnecessary overhead is implicit enrichment. Generic types have very few methods that can be called directly, so Scala uses implicit conversions to enrich these types with useful operators and methods.

However, these conversions have a cost: they instantiate an implicit object which is only needed to immediately call another method. This indirection is usually not a big deal, but is prohibitive in the case of simple methods that may be called millions of times.

Machinist's ops macros provide a solution. These macros allow the same enrichment to occur without any allocations or additional indirection. These macros can work with most common type class encodings, and are easily extensible. They can also remap symbolic operators (e.g. **) to text names (e.g. pow).

Machinist started out as part of the Spire project.

For a more detailed description, you can read this article at typelevel.org.

Examples

Here's an example which defines a very minimal typeclass named Eq[A] with a single method called eqv. It is designed to support type-safe equals, similar to scalaz.Equal or spire.algebra.Eq, and it is specialized to avoid boxing primtive values like Int or Double.

import scala.{specialized => sp}

import machinist.DefaultOps

trait Eq[@sp A] {
  def eqv(lhs: A, rhs: A): Boolean
}

object Eq {
  implicit val intEq = new Eq[Int] {
    def eqv(lhs: Int, rhs: Int): Boolean = lhs == rhs
  }

  implicit class EqOps[A](x: A)(implicit ev: Eq[A]) {
    def ===(rhs: A): Boolean = macro DefaultOps.binop[A, Boolean]
  }
}

object Test {
  import Eq.EqOps

  def test(a: Int, b: Int)(implicit ev: Eq[Int]): Int =
    if (a === b) 999 else 0
}

Here are some intermediate representations for how the body of the test method will be compiled:

// our scala code
if (a === b) 999 else 0

// after implicit resolution
if (Eq.EqOps(a)(Eq.intEq).===(b)) 999 else 0

// after macro application
if (Eq.intEq.eqv(a, b)) 999 else 0

// after specialization
if (Eq.intEq.eqv$mcI$sp(a, b)) 999 else 0

There are a few things to notice:

  1. EqOps[A] does not need to be specialized. Since we will have removed any constructor calls by the time the typer phase is over, it will not introduce any boxing or interfere with specialization.

  2. We did not have to write very much boilerplate in EqOps beyond specifying which methods we want to provide implicit operators for. We did have to specify some type information though (in this case, the type of rhs (the "right-hand side" parameter) and the result type.

  3. machinist.DefaultOps automatically knew to connect the === operator with the eqv method, since it has a built-in mapping of symbolic operators to names. You can use your own mapping by extending machinist.Ops and implementing operatorNames.

Including Machinist in your project

Machinist supports Scala 2.10, 2.11, 2.12, and 2.13.0-M3. If you have an SBT project, add the following snippet to your build.sbt file:

libraryDependencies += "org.typelevel" %% "machinist" % "0.6.4"

Machinist also supports Scala.js. To use Machinist in your Scala.js projects, include the following build.sbt snippet:

libraryDependencies += "org.typelevel" %%% "machinist" % "0.6.4"

Shapes supported by Machinist

Machinist has macros for recognizing and rewriting the following shapes:

// unop
conversion(lhs)(ev).method()
  -> ev.method(lhs)

// unop0
conversion(lhs)(ev).method
  -> ev.method(lhs)

// unopWithEv
conversion(lhs).method(ev)
  -> ev.method(lhs)

// binop
conversion(lhs)(ev).method(rhs)
  -> ev.method(lhs, rhs)

// rbinop, for right-associative methods
conversion(rhs)(ev).method(lhs)
  -> ev.method(lhs, rhs)

// binopWithEv
conversion(lhs).method(rhs)(ev)
  -> ev.method(lhs, rhs)

// rbinopWithEv
conversion(rhs).method(lhs)(ev)
  -> ev.method(lhs, rsh)

Machinist also supports the following oddball cases (which may only be useful for Spire):

// binopWithLift
conversion(lhs)(ev0).method(rhs: Bar)(ev1)
  -> ev.method(lhs, ev1.fromBar(rhs))

// binopWithSelfLift
conversion(lhs)(ev).method(rhs: Bar)
  -> ev.method(lhs, ev.fromBar(rhs))

In both cases, if "method" is a symbolic operator, it may be rewritten to a new name if a match is found in operatorNames.

Details & Fiddliness

To see the names Machinist provides for symbolic operators, see the DefaultOperatorNames trait.

One caveat is that if you want to extend machinist.Ops yourself to create your own name mapping, you must do so in a separate project or sub-project from the one where you will be using the macros. Scala macros must be defined in a separate compilation run from where they are applied.

It's also possible that despite the wide variety of shapes provided by machinist.Ops your shape is not supported. Machinist only provides unary and binary operators, meaning that if your method takes 3+ parameters you will need to write your own macro.

It should be relatively easy to extend Ops to support these cases, but that work hasn't been done yet. Pull requests will be gladly accepted.

Copyright and License

All code is available to you under the MIT license, available at http://opensource.org/licenses/mit-license.php as well as in the COPYING file.

Code of Conduct

See the Code of Conduct

Copyright Erik Osheim and Tom Switzer 2011-2018.

More Repositories

1

cats

Lightweight, modular, and extensible library for functional programming.
Scala
5,182
star
2

fs2

Compositional, streaming I/O library for Scala
Scala
2,359
star
3

doobie

Functional JDBC layer for Scala.
Scala
2,161
star
4

scalacheck

Property-based testing for Scala
Scala
1,908
star
5

cats-effect

The pure asynchronous runtime for Scala
Scala
1,817
star
6

spire

Powerful new number types and numeric abstractions for Scala.
Scala
1,761
star
7

skunk

A data access library for Scala + Postgres.
Scala
1,579
star
8

simulacrum

First class syntax support for type classes in Scala
Scala
937
star
9

squants

The Scala API for Quantities, Units of Measure and Dimensional Analysis
Scala
922
star
10

kind-projector

Compiler plugin for making type lambdas (type projections) easier to write
Scala
915
star
11

frameless

Expressive types for Spark.
Scala
879
star
12

cats-collections

Data structures for pure functional programming in Scala
Scala
557
star
13

kittens

Automatic type class derivation for Cats
Scala
531
star
14

jawn

Jawn is for parsing jay-sawn (JSON)
Scala
431
star
15

log4cats

Logging Tools For Interaction with cats-effect
Scala
400
star
16

Laika

Site and E-book Generator and Customizable Text Markup Transformer for sbt, Scala and Scala.js
Scala
387
star
17

algebra

Experimental project to lay out basic algebra type classes
Scala
378
star
18

mouse

A small companion to cats
Scala
365
star
19

sbt-tpolecat

scalac options for the enlightened
Scala
328
star
20

discipline

Flexible law checking for Scala
Scala
328
star
21

natchez

functional tracing for cats
Scala
324
star
22

cats-tagless

Library of utilities for tagless final encoded algebras
Scala
314
star
23

cats-mtl

cats transformer type classes.
Scala
308
star
24

CT_from_Programmers.scala

Scala sample code for Bartosz Milewski's CT for Programmers
Scala
279
star
25

fs2-grpc

gRPC implementation for FS2/cats-effect
Scala
270
star
26

cats-parse

A parsing library for the cats ecosystem
Scala
233
star
27

cats-effect-testing

Integration between cats-effect and test frameworks
Scala
191
star
28

shapeless-3

Generic programming for Scala
Scala
185
star
29

paiges

an implementation of Wadler's a prettier printer
Scala
183
star
30

grackle

Grackle: Functional GraphQL for the Typelevel stack
Scala
176
star
31

sbt-typelevel

Let sbt work for you.
Scala
170
star
32

munit-cats-effect

Integration library for MUnit & cats-effect
Scala
149
star
33

feral

Feral cats are homeless, feral functions are serverless
Scala
144
star
34

catbird

Birds and cats together
Scala
139
star
35

otel4s

An OpenTelemetry library for Scala based on Cats-Effect
Scala
138
star
36

fs2-chat

Sample project demonstrating use of fs2-io to build a chat client and server
Scala
123
star
37

spotted-leopards

Proof of concept for a cats-like library built using Dotty features
Scala
112
star
38

fabric

Object-Notation Abstraction for JSON, binary, HOCON, etc.
Scala
110
star
39

literally

Compile time validation of literal values built from strings
Scala
106
star
40

toolkit

Quickstart your next app with the Typelevel Toolkit!
Scala
94
star
41

cats-time

Cats Instances for Java Time
Scala
91
star
42

typelevel-nix

Development tools for Typelevel projects
Nix
87
star
43

cats-effect-cps

An incubator project for async/await syntax support for Cats Effect
Scala
81
star
44

vault

Type-safe, persistent storage for values of arbitrary types
Scala
81
star
45

shapeless-contrib

Interoperability libraries for Shapeless
Scala
79
star
46

scalacheck-effect

Effectful property testing built on ScalaCheck
Scala
76
star
47

coop

Cooperative multithreading as a pure monad transformer
Scala
68
star
48

claimant

Library to support automatic labeling of ScalaCheck properties.
Scala
68
star
49

typeclassic

Everything you need to make type classes first class.
Scala
61
star
50

scalaz-contrib

Interoperability libraries & additional data structures and instances for Scalaz
Scala
55
star
51

twiddles

Micro-library for building effectful protocols
Scala
55
star
52

monoids

Generic Monoids for Scala
Scala
51
star
53

fs2-netty

What it says on the tin!
Scala
47
star
54

sbt-catalysts

sbt utilities for open source projects
Scala
45
star
55

natchez-http4s

Glorious integration layer for Natchez and Http4s.
Scala
44
star
56

typelevel.github.com

Web site of typelevel.scala
HTML
40
star
57

jawn-fs2

Integration between jawn and fs2
Scala
38
star
58

keypool

A Keyed Pool Implementation for Scala
Scala
34
star
59

scalaz-specs2

Specs2 bindings for Scalaz
Scala
34
star
60

catalysts

Scala
34
star
61

simulacrum-scalafix

Simulacrum as Scalafix rules
Scala
34
star
62

case-insensitive

A case-insensitive string for Scala
Scala
34
star
63

scalaz-outlaws

outcasts no longer allowed in the ivory tower
Scala
28
star
64

bobcats

Typelevel's very own CryptoKitties!
Scala
28
star
65

scalac-options

A library for configuring scalac options
Scala
27
star
66

weaver-test

A test framework that runs everything in parallel.
Scala
27
star
67

ce3.g8

Scala
24
star
68

scalaz-scalatest

Scalatest bindings for scalaz.
Scala
23
star
69

general

Repository for general Typelevel information, activity and issues
19
star
70

discipline-munit

MUnit binding for Typelevel Discipline
Scala
18
star
71

cats-testkit-scalatest

Cats Testkit for Scalatest
Scala
18
star
72

unique

Unique Functional Values for Scala
Scala
17
star
73

discipline-scalatest

ScalaTest binding for Discipline
Scala
17
star
74

typelevel-scalafix

Scalafix rules for Typelevel projects
Scala
17
star
75

semigroups

Scala
16
star
76

cats-effect-shell

Command line debugging console for Cats Effect
Scala
15
star
77

jdk-index

A Jabba compatible index of JDK versions
Scala
14
star
78

cats-uri

URI implementation based on cats-parse with cats instances
Scala
14
star
79

typelevel.g8

A typelevel.g8 based on sbt-typelevel
Scala
14
star
80

catapult

Scala
13
star
81

discipline-specs2

Specs2 Integration for Discipline
Scala
9
star
82

governance

Typelevel governance
Scala
7
star
83

catz-cradle

Testbed for scala libraries and tools, based on examples from cats docs
Scala
7
star
84

spire-contrib

Interoperability libraries for spire
Shell
7
star
85

idna4s

Cross-platform Scala implementation of Internationalized Domain Names in Applications
Scala
7
star
86

scalac-compat

Lightweight tools for tackling Scalac version incompatibilities
Scala
6
star
87

steward

Runs Scala Steward for Typelevel projects
5
star
88

cats-effect-main

3
star
89

sacagawea

Common infrastructure for tracing functional effects
Scala
3
star
90

scalacheck-xml

Scalacheck instances for scala-xml
Scala
3
star
91

sorcery

WIP
2
star
92

scalacheck-web

ScalaCheck Web Site
Nix
2
star
93

sbt-catalysts.g8

Scala
2
star
94

feral.g8

Giter8 template for feral serverless
Scala
2
star
95

download-java

2
star
96

toolkit.g8

A Giter8 template for Typelevel Toolkit!
Scala
2
star
97

sbt-tls-crossproject

sbt-crossproject plugin for Typelevel Scala
Scala
1
star
98

await-cirrus

Depend on Cirrus CI from a GitHub Actions workflow
JavaScript
1
star
99

catalysts-docker

Shell
1
star
100

.github

a โœจspecial โœจ repository for project defaults and organization readme
1
star