Skip to content

Conditional imports

Niklas Larsson edited this page May 30, 2014 · 1 revision

Under construction, apologies for the mess.

Motivation

In order to be able to build platform-independent libraries, there needs to be a mechanism that allows one to use a different platform-specific backend module in a module, due to divergent APIs. Traditionally this has been done either by linking in different object files or using preprocessor directives to select different swathes of code. Haskell has largely reused the C preprocessor for this.

CPP is not made for processing files other than C/C++, this has led to compability problems when using it for Haskell code. It also allows far more capabilities than we need. Using it would introduce a new syntax to Idris files.

Description

The goal is to be able to present a common lib on all the platforms Idris supports. Say we want to make a System.Timer library. The problem is that timers are accessed by very different APIs on Windows, Linux and Javascript. For libraries on the C side this could be handled by using a common C shim, but this has the drawback that we have to write C where we could have used Idris. It also isn't any help when it comes to Javascript.

I propose a directive %platform that is used like this:

module System.Timer

%platform javascript
import System.Timer.JS

%platform posix
import System.Timer.Posix

%platform windows
import System.Timer.Win

%platform java
import System.Timer.Java

%platform takes a comma-separated list of platforms.

The %platform directive would only be legal in front of an import statement. The import statement is ignored on systems that aren't one of the platforms mentioned in the directive.

What is a platform?

Above I have conflated operating systems and javascript and dub them platforms, the important differentiator between "platforms" is if their API environment differs. As posix-based systems share many commonalities, it makes sense to make them a single platform, but to be able to separate them when it is needed by making it a sum of sub-platforms. The same could be used for browser and node Javascript.

Possible list of platforms:

  • javascript
    • js-browser
    • js-node
  • windows
  • posix
    • darwin
    • linux
    • bsd
    • android
  • java

If a platform has subplatforms, the use of it just means "all of the ones below". %platform posix is equivalent to %platform darwin, linux, bsd, android.

Clone this wiki locally