Skip to content

benzap/fif

Repository files navigation

fif - Stack-based Programming in Clojure(script)

Try it Online!

https://travis-ci.org/benzap/fif.svg?branch=master

https://img.shields.io/clojars/v/fif-lang/fif.svg

./doc/logo.svg

fif is a Stack-based Programming Language in Clojure(script). It is interpreted, extensible, and simple. It was developed to be its own sandboxed scripting language to perform operations on clojure(script) applications. fif is based off of Forth, but has adopted clojures core libraries for familiarity.

(require '[fif.core :as fif])

(fif/reval "Hello World!" . cr) ;; => '()
;; <stdout>: Hello World!

(fif/reval 1 1 +) ;; => '(2)

(fif/reval
 fn yeaa!
   #_"( n -- ) Prints yeeee{n}hhh!"
   "yeeee" .
   0 do "a" . loop
   "hhh!" . cr
 endfn

 5 yeaa!) ;; => '()
;; <stdout>: yeeeeaaaaaahhh!

(fif/reval

 fn factorial
   dup 1 > if dup dec factorial * then
 endfn
   
 5 factorial) ;; => '(120)

;;
;; Most of the clojure functions are available, with more being ported
;; and tested.
;;

(fif/reval (1 2 3 4) rest) ;; => '((2 3 4))

(fif/reval (1 2 3 4) first) ;; => '(1)

(fif/reval (1 2 3 4) 5 conj) ;; => '((5 1 2 3 4))

(fif/reval [1 2 3 4] 5 conj) ;; => '([1 2 3 4 5])

;;
;; More Advanced Features
;;

;; Functional Programming

(fif/reval *+ [1 2 3 4] reduce) ;; => '(10)

(fif/reval *inc [1 2 3 4] map) ;; => '([2 3 4 5])

(fif/reval *even? [1 2 3 4] filter) ;; => '([2 4])

;; Inner Sequence Evaluation (Termed "Realizing")

(fif/reval [4 1 do i inc loop] ?) ;; => '([2 3 4 5])

1 Requirements

fif requires clojure 1.9+

This could be relaxed to clojure 1.7 with interest.

2 Installation

For the latest version, please visit clojars.org

Leiningen/Boot

[fif-lang/fif "1.3.1"]

Clojure CLI/deps.edn

fif-lang/fif {:mvn/version "1.3.1"}

Gradle

compile 'fif-lang:fif:1.3.1'

Maven

<dependency>
  <groupId>fif-lang</groupId>
  <artifactId>fif</artifactId>
  <version>1.3.1</version>
</dependency>

3 Introduction

In stack-based programming, operations are performed on data using Postfix Notation: ex. 1 2 +. This is the complete opposite of Polish Notation used in lisp languages: ex. + 1 2.

The basic principles behind how stack-based programming operates is by pushing values onto a stack, and having defined symbols, called words perform operations on the pushed stack values.

(fif/reval 1 2) ;; => '(1 2)
(fif/reval 1 2 +) ;; => '(3)

Forth is one of the more well known languages which uses this approach, and it is used as a baseline for the implementation of fif.

Although fif is similar to forth in a lot of ways, I like to think that fif is less restrictive, but also more error-prone (hopefully less so with later developments). Forth has a compile mode, which only allows certain defined words to be used while defining new words. None of this exists in fif. Everything is interpreted the moment a dribble of data appears to the stack-machine.

;; conditionals are compile-mode only in Forth, but allowed in fif
(fif/reval 1 0 = if "Ya" else "Nah" then) ;; => '("Nah")

;; do loop is compile-mode only in Forth, along with the rest of the
;; conditional-loops. All of this is allowed in fif.
(fif/reval 4 0 do i loop) ;; => '(0 1 2 3 4)

;; defining functions inside functions doesn't exist in forth to the
;; best of my knowledge.
(fif/reval fn func_define_add
             fn add2 2 + endfn
           endfn

           func_define_add
           2 add2) ;; => '(4)

3.1 Clojure Language Interoperability and Data Representation

Code is presented to fif in the form of the edn data format, which means that only valid data values in clojure are allowed within fif. This comes as a huge advantage, since it means fif has a wealth of data structures at its disposal, and allows for seamless interoperability within the clojure environment.

(fif/reval 1 has-flag? namespace/value.thing why!?!? {:a 123} [1 2 3] #{:mental-asylum :ledger})
;; => (1 has-flag? namespace/value.thing why!?!? {:a 123} [1 2 3] #{:ledger :mental-asylum})

(defn self-destruct [] "yes")
(fif/reval (self-destruct) fn self-destruct "no" endfn self-destruct) ;; => '((self-destruct) "no")

For a detailed breakdown on valid data that can be passed to fif please refer to the Built-in elements section in the edn format github page.

3.2 Printing to Standard Output

fif maintains a few operators for displaying to standard output.

;; Drop the Top value and display it on standard output
(fif/reval 1 2 .) ;; => '(1)
;; <stdout>: 2

;; Carriage return is provided with `cr`
(fif/reval "Hello " . cr "There!" . cr) ;; => '()
;; <stdout>: Hello 
:: <stdout>: There!
;; <stdout>: 

;;
;; Clojure equivalent print functions have been maintained
;;   

(fif/reval "Hello World!" println) ;; => '()
;; <stdout>: Hello World!
;; <stdout>: 

(fif/reval "Hello World!" print) ;; => '()
;; <stdout>: Hello World!

(fif/reval "Hello World!" prn) ;; => '()
;; <stdout>: "Hello World!"
;; <stdout>: 

(fif/reval "Hello World!" pr) ;; => '()
;; <stdout>: "Hello World!"

3.3 Basic Arithmetic and Stack Manipulation

Note that these examples are similar to Learn Forth in Y Minutes

;;
;; Arithmetic
;;

;; Addition
(fif/reval 5 4 +) ;; => '(9)

;; Subtraction
(fif/reval 5 4 -) ;; => '(1)

;; Multiplication
(fif/reval 6 8 *) ;; => '(48)

;; Division
(fif/reval 12 4 /) ;; => '(3)

;; Modulo
(fif/reval 13 2 mod) ;; => '(1)

;; Negation
(fif/reval 99 negate) ;; => '(-99)

;; Absolute Value
(fif/reval -99 abs) ;; => '(99)

;; Maximum and Minimum Value
(fif/reval 52 23 max) ;; => '(52)
(fif/reval 52 23 min) ;; => '(23)

;; Increment and Decrement Value
(fif/reval 1 inc) ;; => '(2)
(fif/reval 2 dec) ;; => '(1)

;;
;; Stack Manipulation
;;

;; Duplicate Stack Value
(fif/reval 3 dup dup) ;; => '(3 3 3)

;; Swap First and Second Values
(fif/reval 2 5 swap) ;; => '(5 2)

;; Rotate Top 3 Values
(fif/reval 1 2 3 rot) ;; => '(2 3 1)

;; Drop Top Value
(fif/reval 1 2 drop) ;; => '(1)

;; Drop the Second Value
(fif/reval 1 2 3 nip) ;; => '(1 3)

;;
;; More Advanced Stack Manipulation
;;

;; Duplicate the Top Value, and place it between the Second Value and Third Value
(fif/reval 1 2 3 4 tuck) ;; => '(1 2 4 3 4)

;; Duplicate the Second Value, and place on the top
(fif/reval 1 2 3 4 over) ;; => '(1 2 3 4 3)

3.4 Conditional Operators

Conditionals produce the clojure equivalent boolean true and false values. However, conditional flags within fif also treat 0 as false and any non-zero number as true.

Note: The implementation of this can be found at fif.stdlib.conditional/condition-true?

(fif/reval 5 3 <)    ;; => '(false)
(fif/reval 5 5 <=)   ;; => '(true)
(fif/reval 1 0 =)    ;; => '(false)
(fir/reval 1 0 not=) ;; => '(true)
(fif/reval 5 2 >)    ;; => '(true)
(fif/reval 3 1 >=)   ;; => '(true)

The only conditional structures within fif are:

<condition> if <true-body> then

<condition> if <true-body> else <false-body> then

Examples:

;; zero values are considered false
(fif/reval 0 if 1 then) ;; => '()
(fif/reval nil if 1 then) ;; => '()
(fif/reval false if 1 then) ;; => '()

;; non-zero values are considered true
(fif/reval 1 if 1 then) ;; => '(1)
(fif/reval -1 if 1 then) ;; => '(1)
(fif/reval true if 1 then) ;; => '(1)

;; Anything else is evaluated by passing to `clojure.core/boolean`
(fif/reval [] if 1 then) ;; => '(1)

(fif/reval 0 if 1 else 2 then) ;; => '(2)
(fif/reval 1 1 - if 1 else 2 then) ;; => '(2)

;; if conditions can be nested
(reval
 fn check-age
   dup 18 <  if drop "You are underage"      else
   dup 50 <  if drop "You are the right age" else
   dup 50 >= if drop "You are too old"       else
   then then then
 endfn

 12 check-age
 24 check-age
 51 check-age) ;; => '("You are underage" "You are the right age" "You are too old")

3.5 Creating Functions

Functions within fif are called word definitions and have the syntax:

fn <name> <body...> endfn

Functions are stored globaly within the stack machine. This holds true when you attempt to define functions while within a function.

Few Examples:

(fif/reval
 
 fn square dup * endfn

 5 square) ;; => (25)

(fif/reval
 
 fn add2 2 + endfn
 fn add4 add2 add2 endfn

 4 add4) ;; => '(8)

3.6 Loops

There are currently four standard loops in fif:

<end> <start> do <body> loop

<end> <start> do <body> <step> +loop

begin <body> <flag> until

begin <flag> while <body> repeat

Examples:

;; do loops are inclusive
(fif/reval 2 0 do "Hello!" loop) ;; => '("Hello!" "Hello!" "Hello!")

;; do loops also have special index words i, j and k
(fif/reval 2 0 do i loop) ;; => '(0 1 2)

;; These are useful for nested loops
(->> (fif/reval 2 0 do 3 0 do j i loop loop)
     (partition 2))
;; => ((0 0) (0 1) (0 2) (0 3) (1 0) (1 1) (1 2) (1 3) (2 0) (2 1) (2 2) (2 3))

;; do loops have a special increment based loop with +loop
(fif/reval 10 0 do i 2 +loop) ;; => '(0 2 4 6 8 10)

;; begin-until performs the action until its clause is true
(fif/reval begin 1 true until) ;; => '(1)

(fif/reval begin 1 false until) ;; => '(1 1 1 1 1 ........

(fif/reval 0 begin dup inc dup 5 = until) ;; => '(0 1 2 3 4 5)

;; begin-while-repeat performs the action while its while clause is true
(fif/reval begin false while 1 repeat) ;; => '()

(fif/reval begin true while 1 repeat) ;; => '(1 1 1 1 1 .......

(fif/reval 0 begin dup 5 < while dup inc repeat) ;; => '(0 1 2 3 4 5)

;; You can break out of any loop prematurely using `leave`
(fif/reval begin true while leave repeat) ;; => '() No Infinite Loop!

(fif/reval 0 begin true while dup inc dup 5 = if leave then repeat) ;; => '(0 1 2 3 4 5)

3.7 Word Referencing

fif uses the concept of Word Referencing, which is a means of pushing already defined words onto the stack. This becomes useful for setting variables and for functional programming as shown in the next two sections.

;; Already defined words won't end up on the stack
(fif/reval 2 2 +) ;; => '(4)

(fif/reval +) ;; ERROR

;; A word reference involves placing an asterisk '*' infront of the
;; word you want on the stack.

(fif/reval 2 2 *+) ;; => '(2 2 +)
(fif/reval *+) ;; => '(+)

;; These can be chained for deeper referencing

(fif/reval **+) ;; => '(*+)

(fif/reval ***+) ;; => '(**+)

(fif/reval ********+) ;; => ....

;; Multiplication remains unaffected

(fif/reval 2 2 *) ;; => '(4)

3.8 Functional Programming

fif supports some of the usual functional programming idioms seen in other popular languages. The currently implemented functional programming operators are reduce, map, and filter.

<fn ( xs x -- 'xs )> <coll> reduce

<fn ( item -- 'item )> <coll> map

<fn ( item -- boolean )> <coll> filter

(fif/reval *+ [1 2 3 4] reduce) ;; => '(10)

(fif/reval *inc [1 2 3 4] map) ;; => '((2 3 4 5))

(fif/reval *even? [1 2 3 4 5] filter) ;; => '((2 4))

(fif/reval *inc [1 2 3 4] map) ;; => '((2 3 4 5))

3.8.1 Lambda Expressions

The base functional operators can also be passed a sequence in place of a function, which will be treated as a lambda expression.

(fif/reval (2 +) [1 2 3 4] map) ;; => '((3 4 5 6))    

(fif/reval (:eggs not=) [:eggs :ham :green-eggs :eggs] filter)
;; => '((:ham :green-eggs))

3.9 Variables

fif strays away from Forth in the way it sets and gets variables. Since fif uses Word Referencing, the ability to get Word Variables simply requires you to place the word on the stack to retrieve the value. Setting the variable requires you to provide a Word Reference, as shown in the examples below.

Global variables within fif are declared using def, and are treated as word definitions. They can be set using the word operator setg. Local variables are declared using let, and can be set programmatically using setl.

Examples

(fif/reval
 
 ;;
 ;; Globally Scoped Variables
 ;;

 *X 2 2 + setg

 X . cr ;; => '(4)

 ;; Set X to 10
 def X 10

 ;; Get X
 X

 ;; Set X to 20 
 *X 20 setg

 ;;
 ;; Locally Scoped Variables
 ;;
 ;; Note that functions have a local dynamic scope.

 let y true

 y ;; => '(true)

 ;; They can be set programmatically with `setl`

 *y false setl

 y ;; => '(false)
 )

3.10 Macros

Macros are somewhat experimental, but for future macros, it would be interesting to see how easily it might be to manipulate the code stack in new and interesting ways. A very primitive macro system is implemented. As an example, I implemented an incomplete `?do` loop from Forth

Example:

(reval
 macro ?do
   over over >
   if
     _! inc do !_
   else
     _! do leave !_
   then
 endmacro

 fn yeaa!
   #_"(n -- ) Prints yeaa with 'n' a's"
   "yeeee" .
   0 ?do "a" . loop
   "hhh!" . cr
 endfn
 
 0 yeaa!
 5 yeaa!) ;; => '()
 ;; <stdout>: yeeeehhh!
 ;; <stdout>: yeeeeaaaaahhh!

4 Extending fif within Clojure

One interesting by-product of creating fif within clojure is how easy it is to extend fif from within clojure. There is a wealth of functionality that can be easily included in fif with only a few lines of code.

4.1 Extending fif with clojure functions

As an example, i’m going to make two functions. One function that adds items to a vector, and another which retrieves the vector.

(def *secret-notes (atom []))
(defn add-note! [s] (swap! *secret-notes conj s))
(defn get-notes [] @*secret-notes)

(add-note! "They're in the trees")
(add-note! {:date "March 14, 2018" :name "Stephen Hawking"})

(get-notes) ;; => ["They're in the trees" {:date "March 14, 2018" :name "Stephen Hawking"}]

I want two functions in fif to closely resemble the clojure equivalents, notably:

add-note!, which takes one value, and returns nothing

get-notes, which takes no values, and returns the list

Using the default stack machine fif.core/*default-stack*, we can extend it to include this functionality:

(require '[fif.core :as fif])
(require '[fif.def :refer [wrap-procedure-with-arity
                           wrap-function-with-arity
                           set-word-function]])

;; Wrap add-note! as a procedure which accepts 1 value from the
;; stack. Note that the procedure wrapper does not return the result
;; of our function to the stack.
(def op-add-note! (wrap-procedure-with-arity 1 add-note!))

;; Wrap get-notes as a function. Note that the function wrapper will
;; return its result to the stack.
(def op-get-notes (wrap-function-with-arity 0 get-notes))

(def extended-stack-machine
  (-> fif/*default-stack*
      (set-word-function 'add-note! op-add-note!)
      (set-word-function 'get-notes op-get-notes)))

;; Let's take our new functionality for a spin
(reset! *secret-notes [])
(fif/with-stack extended-stack-machine
  (fif/reval "I Hate Mondays" add-note!) ;; => '()
  (fif/reval-string "\"Kill Switch: Pineapple\" add-note!") ;; => '()
  (fif/reval get-notes)) ;; => '(["I Hate Mondays" "Kill Switch: Pineapple"])

More advanced functions can make use of the full stack machine, and a few of these functions can be seen in the fif.stdlib.ops namespace.

4.2 Implementing a fif Programmable Repl (prepl)

fif isn’t that useful interactively without facilities to capture stdout and stderr. A Programmable Repl (prepl) can be easily implemented within fif using `fif.core/prepl-eval`.

For this example, i’m going to create a prepl from the default-stack which will change state within an atom. Additional atoms will be used to capture stdout and stderr.

(require '[clojure.string :as str])
(require '[fif.core :as fif])

(def *sm (atom fif/*default-stack*))
(def *stdout-results (atom []))
(def *stderr-results (atom []))


(defn prepl-reset! []
  (reset! *sm fif/*default-stack*)
  (reset! *stdout-results [])
  (reset! *stderr-results []))


(defn output-fn
  "Standard Output/Error Handler Function. "
  [{:keys [tag value]}]
  (let [;; Remove platform specific newlines
        value (str/replace value #"\r\n" "\n")]
    (cond
     (= tag :out)
     (swap! *stdout-results conj value)
  
     (= tag :error)
     (swap! *stderr-results conj value))))


 (defn prepl [sinput]
   (swap! *sm fif/prepl-eval sinput output-fn)
   {:stack (-> @*sm fif/get-stack reverse)
    :stdout @*stdout-results
    :stderr @*stderr-results})
  
 (prepl "2 2") ;; => {:stack '(2 2) :stdout [] :stderr []}
 
 (prepl "+") ;; => {:stack '(4) :stdout [] :stderr []}

 (prepl "println") ;; => {:stack '() :stdout ["4\n"] :stderr []}

 (prepl-reset!)

The fif prepl functionality works in clojurescript, however, clojurescript lacks a standard error output, so it is not likely the :error tag would appear to the output function.

4.3 fif and clojure interoperability

Although this might not be taken as a feature, fif can have clojure s-exps evaluated within its comfy confines. The default set of fif evaluators over clojure data are subject to the same clojure reader shortfalls that prevent it from being used as a data format.

Note that reading in data as a string representation does not suffer from these shortfalls as discussed in another section

(fif/reval 1 #=(+ 1 1) +) ;; => '(3) Yikes!

(defn boiling-point-c [] 100)

(fif/reval #=(boiling-point-c) 1 +) ;; => '(101) Russians!

However, the preferred way to include additional data within fif is by either passing values onto the stackmachine, or by setting fif variables which can be accessed from within fif.

  
(require '[fif.core :as fif])
(require '[fif.stack-machine :as stack])
(require '[fif.def :refer [set-word-variable]])

(defn secret-stack-machine
  "Returns a stack machine with a `secret` value stored in the fif
  variable 'secret"
  [secret]
  (-> fif/*default-stack*
      (set-word-variable 'secret secret)))


(fif/with-stack (secret-stack-machine :fooey)
  (fif/reval secret)) ;; => (:fooey)


(defn pill-popping-stack-machine
  "Returns a stack machine with the values within `pills` placed on
  the stack"
  [& pills]
  (loop [sm fif.core/*default-stack*
         pills pills]
    (if-let [pill (first pills)]
      (recur (stack/push-stack sm pill)
             (rest pills))
      sm)))


(fif/with-stack (pill-popping-stack-machine :pink :green :blue)
  (fif/reval "The pill on the top of the stack is: " . .))
  ;; => '(:pink :green)
  ;; <stdout>: The pill on the top of the stack is: :blue

An additional alternative was introduced, which is to generate the quoted form with additonally evaluated clojure code included through an escape sequence. If the escape sequence is provided, ‘%=, the next value in the sequence is evaluated as clojure code. This would be useful when generating code from a client to plug into a fif stack machine as a server command.

(require '[fif.core :as fif])
(require '[fif.client :refer [form-string]])


(def secret-message "The Cake is a Lie")


(fif/reval-string (form-string "The secret message is: " %= secret-message str println))
;; <stdout>: The secret message is: The Cake is a Lie
;; <stdout>: 

4.4 Making fif safer, because Russians…?

Although using fif from within clojure might have its shortfalls, fif can avoid these shortfalls of clojure by passing in strings containing EDN data.

The same unsafe example from before:

(require '[fif.core :as fif])

(fif/reval-string "1 1 +") ;; => '(2)

(fif/reval-string "1 #=(+ 1 1) +") ;; ERROR
;; Unhandled clojure.lang.ExceptionInfo
;; No reader function for tag =.
;; {:type :reader-exception, :ex-kind :reader-error}

This means that fif could potentially (without liability on the author’s part) be used for remote execution. It could be used as a sandboxed environment which only extends to clojure functions which are deemed safe.

This brings me to the issue of erroneous infinite loops. The fif stack machine has the ability to limit stack operation to a max number of execution steps.

(require '[fif.core :as fif])
(require '[fif.stack-machine :as stack])

(defn limited-stack-machine [step-max]
  (-> fif/*default-stack*
      (stack/set-step-max step-max)))


(def default-step-max 200)
(defn eval-incoming [s]
  (let [sm (limited-stack-machine default-step-max)
        evaluated-sm (fif/with-stack sm (fif/eval-string s))
        max-steps (stack/get-step-max evaluated-sm)
        num-steps (stack/get-step-num evaluated-sm)]
    (if (>= num-steps max-steps)
      "Exceeded Max Step Execution"
      (-> evaluated-sm stack/get-stack reverse))))


(def incoming-fif-eval "3 0 do :data-value i loop")
(eval-incoming incoming-fif-eval) ;; => (:data-value 0 :data-value 1 :data-value 2 :data-value 3)


(def infinite-fif-eval "begin true while :data-value 1 repeat")
(eval-incoming infinite-fif-eval) ;; => "Exceeded Max Step Execution"


(def malicious-fif-eval "begin #=(fork-main-thread) false until")
(eval-incoming malicious-fif-eval) ;; ERROR
;; Unhandled clojure.lang.ExceptionInfo
;; No reader function for tag =.
;; {:type :reader-exception, :ex-kind :reader-error}

4.5 Running a fif Socket Repl Server

fif has the ability to start a socket repl server with a designated stack-machine which can be accessed through a raw socket connection. This has the benefit of providing a simple interface for configuring a server, while only exposing limited functionality.

(require '[fif.core :as fif])
(require '[fif.stack-machine :as stack])
(require '[fif.server.core :as fif.server])

(def server-name "Example Socket Server")
(def server-port 5005)

(def custom-stack-machine
  (-> fif/*default-stack*
      ;; prevents system error handler from throwing an error,
      ;; places it on the stack instead
      stack/enable-debug))

(defn start-socket-server []
  (fif.server/start-socket-server custom-stack-machine server-name :port server-port))

(defn stop-socket-server []
  (fif.server/stop-socket-server server-name))

Testing this server on linux can be done using netcat: netcat localhost 5005

If you are on Windows, it can be accessed with putty with these additional configuration options:

  • Set Connection Type to Raw
  • Under the Terminal Setting Category, enable Implicit CR in every LF

5 Using fif from the commandline

fif supports a fairly straightforward commandline repl, which is located at `fif.commandline/-main`. The commandline repl has the ability to load scripts containing fif/edn code, and also includes additional standard library word definitions for reading and writing files on the filesystem. These additional word definitions are located in the :stdlib.io group

The fif commandline can be accessed with lein run -- <arguments>

6 Native Executable

As of version 1.0.1, fif can be used as a standalone scripting language. Compilation into a native executable is done by using GraalVM with the native-image commandline-tool.

To generate this executable yourself:

  • clone this repository
  • make sure you have leiningen installed
  • download and unpack a copy of the graal repository
  • set the environment variable GRAAL_HOME as the root path of this graal repository
  • While at the root of the fif repository, run the build-native.sh script.

The generated executable should be placed in the ./bin/ folder of the repository.

$ fif -e 2 2 + println
4
$ fif -h
fif Language Commandline repl/eval

Usage:
  fif [options]
  fif <filename> [arguments..] [options]

Options:
  -h, --help    Show this screen.
  -e            Evaluate Commandline Arguments

Website:
  github.com/benzap/fif

Notes:
  * Commandline Arguments are placed in the word variable $vargs
  * The :stdlib.io group includes additional io operations for reading
  and writing files

$ fif
Fif Repl
 'help' for Help Message
 'bye' to Exit.
> 2 2 + println
4
> bye
For now, bye!

The resulting binary starts incredibly fast (<20ms), and has the advantage of directly manipulating EDN configuration files.

$ fif -e '"./deps.edn" dup load-file [:deps fif] {:mvn/version "1.0.2"} assoc-in spit'

It can also be used like any standard scripting language. As an example, i’m going to write a primitive script to add, remove and list dependencies from a “deps.edn” file called clj-deps

#!/usr/bin/env fif

def help-message "clj dependency tool

Usage:
  clj-deps add <package> <version>
  clj-deps remove <package>
  clj-deps list

Example:
  clj-deps add fif 1.0.2
"

*cargs $vargs count setg
*command $vargs first setg
*package $vargs second dup nil? not if read-string first then setg
*version $vargs 2 get setg

cargs 3 =
command "add" =
and
if
  "deps.edn" read-file first
  [:deps package] ?
  {} :mvn/version version assoc assoc-in
  "deps.edn" <> spit
else

cargs 2 =
command "remove" =
and
if
  "deps.edn" read-file first
  dup :deps get package dissoc :deps <> assoc
  "deps.edn" <> spit
else

cargs 1 =
command "list" =
and
if
  "deps.edn" read-file first
  :deps get (dup first . ":" . second :mvn/version get . cr nil) <> map
else
  help-message println
then then then

An example of it’s use:

$ echo "{}" > deps.edn
$ clj-deps add fif 1.0.2
$ clj-deps add clock 0.3.2
cat deps.edn
{:deps {fif {:mvn/version "1.0.2"}, clock {:mvn/version "0.3.2"}}}
$ clj-deps remove clock
$ clj-deps list
fif:1.0.2
$ clj-deps
clj dependency tool

Usage:
  clj-deps add <package> <version>
  clj-deps remove <package>
  clj-deps list

Example:
  clj-deps add fif 1.0.2

7 Development

You can pull the project from github. Clojure tests are run via lein test, and Clojurescript tests are run via lein doo. Clojurescript tests require you to have node on your Environment PATH.

I welcome any and all pull requests that further improve what is currently here, especially things which further improve security and improve error messages.

I’m still not sure where to go with respect to the standard library, and i’m open to suggestions for making manipulation of clojure data as painless as possible.

8 Upcoming Features

A few things to look out for:

  • Implementation in Clojurescript included since 0.3.0-snapshot
  • Regex Support (#”” tagged literal is not valid EDN) use ‘regex’ word definition
  • Improved Error Messages
  • Socket Repl included since 0.4.0-snapshot
  • Commandline Repl included since 0.4.0-snapshot
  • Programmable Repl in Clojure and Clojurescript included since 0.4.0-snapshot
  • Improved repl word definitions On-Going
  • Additional Standard Library Word Definitions On-Going
  • Improved Fif Macros
  • A Time Machine Debugger

9 Related Readings

10 FAQ

10.1 Why fif?

fif is meant to be a play on forth. The name forth was originally meant to be spelt fourth, but had to be reduced in order to fit within the restrictions of computers at the time of it’s creation, and so the name stuck. I recommend you check out the wiki page for an interesting read.

It also helps to note that fif kind of sounds like you have a lisp :)

10.2 Do you plan on using fif in production?

It’s at the point where it is a viable scripting language for my own projects. It has the benefits of being completely sandboxed, and with the addition of the socket repl server, it could be used as an alternative to exposing functionality for setting and getting server configuration data, or even for automating certain functionality with external scripts.